#!/usr/bin/env php
<?php
/**
 * Database Migration Script
 * Runs pending migrations
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';

$migrationsDir = __DIR__ . '/../database/migrations/';
$logFile = __DIR__ . '/../logs/migration.log';

function logMessage($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
    echo $message . "\n";
}

// Create migrations table if not exists
$pdo = getDB();
$pdo->exec("CREATE TABLE IF NOT EXISTS migrations (
    id INT PRIMARY KEY AUTO_INCREMENT,
    migration VARCHAR(255) NOT NULL,
    executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Get executed migrations
$executed = $pdo->query("SELECT migration FROM migrations")->fetchAll(PDO::FETCH_COLUMN);

// Get available migrations
$migrations = glob($migrationsDir . "*.sql");
sort($migrations);

$count = 0;
foreach ($migrations as $migration) {
    $migrationName = basename($migration);
    
    if (in_array($migrationName, $executed)) {
        logMessage("Skipping: $migrationName (already executed)");
        continue;
    }
    
    logMessage("Running migration: $migrationName");
    
    $sql = file_get_contents($migration);
    
    try {
        $pdo->exec($sql);
        $stmt = $pdo->prepare("INSERT INTO migrations (migration) VALUES (?)");
        $stmt->execute([$migrationName]);
        $count++;
        logMessage("✓ Completed: $migrationName");
    } catch (PDOException $e) {
        logMessage("✗ Error: " . $e->getMessage());
        exit(1);
    }
}

if ($count === 0) {
    logMessage("No pending migrations found.");
} else {
    logMessage("Completed $count migration(s).");
}