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

function get_executed_migrations($pdo) {
    try {
        $stmt = $pdo->query("SELECT `migration` FROM `migrations`");
        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    } catch (PDOException $e) {
        // If the migrations table doesn't exist, create it.
        if ($e->getCode() === '42S02') { // Base table or view not found
            $pdo->exec("CREATE TABLE `migrations` (`migration` VARCHAR(255) PRIMARY KEY, `executed_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
            return [];
        }
        throw $e;
    }
}

function mark_migration_as_executed($pdo, $migration_file) {
    $stmt = $pdo->prepare("INSERT INTO `migrations` (`migration`) VALUES (?)");
    $stmt->execute([$migration_file]);
}

try {
    $pdo = db();
    echo "Conectado ao banco de dados.\n";

    $executed_migrations = get_executed_migrations($pdo);
    echo "Migrações já executadas: " . (empty($executed_migrations) ? "Nenhuma" : implode(', ', $executed_migrations)) . "\n";

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

    $new_migrations_found = false;
    foreach ($migration_files as $file) {
        $filename = basename($file);
        if (!in_array($filename, $executed_migrations)) {
            $new_migrations_found = true;
            echo "Executando migração: $filename...\n";
            
            $sql = file_get_contents($file);
            $pdo->exec($sql);
            mark_migration_as_executed($pdo, $filename);
            
            echo "  -> Migração $filename concluída.\n";
        }
    }

    if (!$new_migrations_found) {
        echo "Nenhuma nova migração para executar. O banco de dados já está atualizado.\n";
    } else {
        echo "Todas as novas migrações foram concluídas com sucesso!\n";
    }

} catch (PDOException $e) {
    die("Falha na migração: " . $e->getMessage() . "\n");
}