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

function run_migrations() {
    $pdo = db();

    try {
        // Create migrations table if it doesn't exist
        $pdo->exec("CREATE TABLE IF NOT EXISTS migrations (id INT AUTO_INCREMENT PRIMARY KEY, migration VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");

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

        // Get all migration files
        $migration_files = glob('db/migrations/*.php');

        foreach ($migration_files as $file) {
            $migration_name = basename($file, '.php');

            if (!in_array($migration_name, $run_migrations)) {
                echo "Running migration: $migration_name...\n";
                require_once $file;
                
                try {
                    // Migration functions are named like migrate_001, migrate_002 etc.
                    $function_name = 'migrate_' . preg_replace('/[^0-9]/', '', $migration_name);
                    if(function_exists($function_name)){
                        $function_name($pdo);
                    } else {
                        // Fallback for older naming convention
                        $function_name = str_replace('.php', '', basename($file));
                        if(function_exists($function_name)) {
                            $function_name($pdo);
                        }
                    }
    
                    // Record migration
                    $stmt = $pdo->prepare("INSERT INTO migrations (migration) VALUES (?)");
                    $stmt->execute([$migration_name]);
                    echo "Migration $migration_name has been applied.\n";
                } catch (PDOException $e) {
                    echo "Error running migration $migration_name: " . $e->getMessage() . "\n";
                }
            } else {
                echo "Migration $migration_name already applied.\n";
            }
        }

        echo "All migrations have been run.\n";

    } catch (PDOException $e) {
        die("Migration failed: " . $e->getMessage());
    }
}

// If the script is run directly from the command line
if (php_sapi_name() === 'cli') {
    run_migrations();
}


