<?php
require_once 'config.php';

try {
    // Connect without specifying a database to ensure the DB exists
    $pdo = new PDO('mysql:host='.DB_HOST, DB_USER, DB_PASS, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
    $pdo->exec('CREATE DATABASE IF NOT EXISTS '.DB_NAME);

    // Now connect to the specific database
    $pdo = db();

    // 1. 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
    )');

    // 2. Get all migration files
    $migration_files = glob(__DIR__ . '/migrations/*.sql');
    sort($migration_files);

    // 3. Get already executed migrations
    $executed_migrations_stmt = $pdo->query('SELECT migration FROM migrations');
    $executed_migrations = $executed_migrations_stmt->fetchAll(PDO::FETCH_COLUMN);

    foreach ($migration_files as $file) {
        $migration_name = basename($file);

        // 4. If migration has not been run, execute it
        if (!in_array($migration_name, $executed_migrations)) {
            $sql = file_get_contents($file);
            $pdo->exec($sql);

            // 5. Record the migration
            $stmt = $pdo->prepare('INSERT INTO migrations (migration) VALUES (?)');
            $stmt->execute([$migration_name]);

            echo "Executed migration: $migration_name" . PHP_EOL;
        }
    }

    echo "All migrations have been run." . PHP_EOL;

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