<?php
require_once __DIR__ . '/config.php';

echo "Running migrations...\n";

try {
    $pdo = db();
    // 1. Create schema_migrations table if it doesn't exist
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS schema_migrations (
            version VARCHAR(255) NOT NULL PRIMARY KEY,
            applied_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    ");

    // 2. Get all migrations that have already been run
    $applied_migrations = $pdo->query("SELECT version FROM schema_migrations")->fetchAll(PDO::FETCH_COLUMN);

} catch (PDOException $e) {
    die("A database error occurred during setup: " . $e->getMessage());
}

// 3. Get all migration files on disk
$migrationsDir = __DIR__ . '/migrations';
$all_files = glob($migrationsDir . '/*.sql');
sort($all_files);

// 4. Determine and run new migrations
foreach ($all_files as $file) {
    $filename = basename($file);
    
    if (!in_array($filename, $applied_migrations)) {
        echo "Applying migration: $filename\n";
        
        try {
            $sql = file_get_contents($file);
            $pdo->exec($sql);
            
            // Record the migration
            $stmt = $pdo->prepare("INSERT INTO schema_migrations (version) VALUES (?)");
            $stmt->execute([$filename]);
            
            echo "  Success.\n";

        } catch (PDOException $e) {
            echo "  Error applying migration $filename: " . $e->getMessage() . "\n";
            // Stop on first error
            break;
        }
    } else {
        echo "Skipping already applied migration: $filename\n";
    }
}

echo "Migrations completed.\n";

