<?php
/**
 * Migration Runner
 * 
 * Run: php bin/migrate.php
 */

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

// Load config
$config = require __DIR__ . '/../config/app.php';

echo "fahrschuldesk Migration Runner\n";
echo "==============================\n\n";

// Database connection
$dsn = sprintf(
    'pgsql:host=%s;port=%d;dbname=%s',
    $config['db']['host'],
    $config['db']['port'],
    $config['db']['database']
);

try {
    $pdo = new PDO($dsn, $config['db']['username'], $config['db']['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
    echo "✓ Connected to database\n\n";
} catch (PDOException $e) {
    echo "✗ Database connection failed: " . $e->getMessage() . "\n";
    exit(1);
}

// Get all migration files
$migrationsPath = __DIR__ . '/../database/migrations';
$files = glob($migrationsPath . '/*.sql');

if (empty($files)) {
    echo "No migration files found.\n";
    exit(0);
}

sort($files);

echo "Found " . count($files) . " migration(s)\n\n";

// Create migrations table if not exists
$pdo->exec("
    CREATE TABLE IF NOT EXISTS migrations (
        id SERIAL PRIMARY KEY,
        name VARCHAR(255) NOT NULL UNIQUE,
        executed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
    )
");

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

// Run pending migrations
foreach ($files as $file) {
    $filename = basename($file);
    
    if (in_array($filename, $executed)) {
        echo "○ {$filename} (already executed, skipping)\n";
        continue;
    }
    
    echo "→ Running: {$filename}\n";
    
    try {
        $sql = file_get_contents($file);
        $pdo->exec($sql);
        
        $stmt = $pdo->prepare("INSERT INTO migrations (name) VALUES (:name)");
        $stmt->execute(['name' => $filename]);
        
        echo "✓ {$filename} completed\n";
    } catch (PDOException $e) {
        echo "✗ {$filename} failed: " . $e->getMessage() . "\n";
        exit(1);
    }
}

echo "\n==============================\n";
echo "All migrations completed!\n";