<?php
require_once 'db/config.php';
$db = db();
// Ensure buffered query is on if possible (though config might override)
$db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

$db->query("SET FOREIGN_KEY_CHECKS=0;");
$files = glob('db/migrations/*.sql');
sort($files);

foreach ($files as $file) {
    echo "Processing $file...\n";
    $sql_content = file_get_contents($file);
    $sql_content = preg_replace('/--.*$/m', '', $sql_content);
    $statements = explode(';', $sql_content);
    
    foreach ($statements as $sql) {
        $sql = trim($sql);
        if (empty($sql)) continue;
        
        try {
            // Use query() instead of exec() to handle potential result sets (like SELECT 1)
            // and close the cursor explicitly.
            $stmt = $db->query($sql);
            if ($stmt) {
                $stmt->closeCursor();
            }
            echo "Executed: " . substr(str_replace("\n", " ", $sql), 0, 60) . "...\n";
        } catch (PDOException $e) {
            $msg = $e->getMessage();
            if (strpos($msg, "Duplicate column") !== false || 
                strpos($msg, "already exists") !== false ||
                strpos($msg, "Duplicate key") !== false ||
                strpos($msg, "1062 Duplicate entry") !== false ||
                strpos($msg, "1054 Unknown column") !== false ||
                strpos($msg, "1146 Table") !== false ||
                strpos($msg, "1553 Cannot drop index") !== false || strpos($msg, "1826 Duplicate FOREIGN KEY") !== false || strpos($msg, "1828 Cannot drop column") !== false) {
                echo "Skipped (Exists): " . substr(str_replace("\n", " ", $sql), 0, 60) . "...\n";
            } else {
                echo "Error: " . $msg . "\n";
            }
        }
    }
}
$db->query("SET FOREIGN_KEY_CHECKS=1;");
echo "All migrations applied.\n";