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

function runMigrations() {
    $pdo = db();
    // Create migration table if not exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS migrations (
        id INT AUTO_INCREMENT PRIMARY KEY,
        migration_name VARCHAR(255) NOT NULL UNIQUE,
        applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
    
    $migrationsDir = __DIR__;
    $files = glob($migrationsDir . '/*.sql');
    sort($files);

    foreach ($files as $file) {
        $migration_name = basename($file);
        
        // Check if already applied
        $stmt = $pdo->prepare("SELECT id FROM migrations WHERE migration_name = ?");
        $stmt->execute([$migration_name]);
        if ($stmt->fetch()) {
            echo "Already applied: $migration_name" . PHP_EOL;
            continue;
        }

        echo "Applying: $migration_name" . PHP_EOL;
        $sql = file_get_contents($file);
        
        // Split SQL into individual statements by ; followed by newline
        $statements = preg_split('/;(?:\\s*[\r\n]+)/', $sql);
        
        $success = true;
        foreach ($statements as $statement) {
            $statement = trim($statement);
            if (empty($statement)) continue;
            
            // Basic comment removal
            $statement_lines = explode("\n", $statement);
            $clean_statement = "";
            foreach ($statement_lines as $line) {
                if (trim(substr(trim($line), 0, 2)) === '--') continue;
                $clean_statement .= $line . "\n";
            }
            $clean_statement = trim($clean_statement);
            if (empty($clean_statement)) continue;

            try {
                $stmt = $pdo->query($clean_statement);
                if ($stmt) {
                    $stmt->closeCursor();
                }
            } catch (PDOException $e) {
                $msg = $e->getMessage();
                // If the error is about a table already existing, it's fine for our idempotency
                if (strpos($msg, "already exists") !== false || 
                    strpos($msg, "Duplicate column") !== false || 
                    strpos($msg, "Duplicate entry") !== false ||
                    strpos($msg, "already a column") !== false ||
                    strpos($msg, "Duplicate key") !== false) {
                    continue;
                }
                echo "Error in $migration_name at statement: " . substr($clean_statement, 0, 100) . "... " . PHP_EOL;
                echo "Error: " . $msg . PHP_EOL;
                $success = false;
                break;
            }
        }
        
        if ($success) {
            $stmt = $pdo->prepare("INSERT INTO migrations (migration_name) VALUES (?)");
            $stmt->execute([$migration_name]);
            echo "Successfully applied migration: $migration_name" . PHP_EOL;
        } else {
            echo "Migration failed: $migration_name. Stopping." . PHP_EOL;
            break;
        }
    }
}

runMigrations();