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

function get_migrated_files($pdo) {
    $stmt = $pdo->query("SHOW TABLES LIKE 'migrations'");
    if ($stmt->rowCount() > 0) {
        $stmt = $pdo->query('SELECT filename FROM migrations');
        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }
    return [];
}

function add_migrated_file($pdo, $filename) {
    $stmt = $pdo->prepare('INSERT INTO migrations (filename) VALUES (?)');
    $stmt->execute([$filename]);
}


try {
    $pdo = db();
    
    // Create migrations table if it doesn't exist
    $pdo->exec('CREATE TABLE IF NOT EXISTS migrations (filename VARCHAR(255) NOT NULL PRIMARY KEY)');

    $migrated_files = get_migrated_files($pdo);
    $migrations_dir = __DIR__ . '/migrations';
    $files = glob($migrations_dir . '/*.sql');
    
    $all_migrations_run = true;

    foreach ($files as $file) {
        $filename = basename($file);
        if (!in_array($filename, $migrated_files)) {
            $all_migrations_run = false;
            $sql = file_get_contents($file);
            try {
                $pdo->exec($sql);
                add_migrated_file($pdo, $filename);
                echo "Migrated: $filename\n";
            } catch (PDOException $e) {
                die("Migration failed on $filename: " . $e->getMessage());
            }
        }
    }

    if($all_migrations_run) {
        echo "All migrations are up to date.\n";
    } else {
        echo "\nMigrations complete.\n";
    }

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

