#!/usr/bin/env php
<?php
/**
 * Run All Migrations
 * Executes migration files in order
 */

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

$pdo = getDB();
$migrationsDir = __DIR__;

// Create migrations table if not exists
$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
)");

$migrationFiles = glob($migrationsDir . "/*.sql");
sort($migrationFiles);

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

echo "Running database migrations...\n";

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

echo "\nAll migrations completed!\n";