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

function run_migrations() {
    $pdo = db();
    $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 );");

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

    $migration_files = glob(__DIR__ . '/migrations/*.sql');
sort($migration_files);

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

        if (!in_array($migration_name, $ran_migrations)) {
            $sql = file_get_contents($file);
            $pdo->exec($sql);

            $stmt = $pdo->prepare("INSERT INTO migrations (migration) VALUES (?)");
            $stmt->execute([$migration_name]);

            echo "Migration run: " . $migration_name . "\n";
        } else {
            echo "Migration already run: " . $migration_name . "\n";
        }
    }
}

run_migrations();

