<?php
/**
 * Run migrations
 * Uruchamia wszystkie migracje z katalogu /migrations
 */

require_once __DIR__ . '/panel/config/config.php';
require_once PANEL_PATH . '/classes/Database.php';

echo "=== Running migrations ===\n\n";

$db = Database::getInstance();
$conn = $db->getConnection();

// Stwórz tabelę migracji jeśli nie istnieje
$conn->exec("CREATE TABLE IF NOT EXISTS migrations (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    filename VARCHAR(255) UNIQUE NOT NULL,
    executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
)");

// Pobierz wykonane migracje
$executed = [];
$result = $conn->query("SELECT filename FROM migrations");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $executed[] = $row['filename'];
}

// Znajdź pliki migracji
$migrationsDir = __DIR__ . '/migrations';
if (!is_dir($migrationsDir)) {
    echo "No migrations directory found.\n";
    exit(1);
}

$files = glob($migrationsDir . '/*.sql');
sort($files);

$count = 0;
foreach ($files as $file) {
    $filename = basename($file);
    
    if (in_array($filename, $executed)) {
        echo "SKIP: {$filename} (already executed)\n";
        continue;
    }
    
    echo "RUN: {$filename}...";
    
    $sql = file_get_contents($file);
    
    try {
        // Usuń komentarze
        $sql = preg_replace('/--.*$/m', '', $sql);
        
        // Podziel na statementy po średniku (ale nie w środku stringa)
        $statements = [];
        $current = '';
        $inString = false;
        $stringChar = '';
        
        for ($i = 0; $i < strlen($sql); $i++) {
            $char = $sql[$i];
            
            if (!$inString && ($char === "'" || $char === '"')) {
                $inString = true;
                $stringChar = $char;
                $current .= $char;
            } elseif ($inString && $char === $stringChar) {
                // Sprawdź czy nie jest escaped
                if ($i > 0 && $sql[$i-1] !== '\\') {
                    $inString = false;
                }
                $current .= $char;
            } elseif (!$inString && $char === ';') {
                $statement = trim($current);
                if (!empty($statement)) {
                    $statements[] = $statement;
                }
                $current = '';
            } else {
                $current .= $char;
            }
        }
        
        // Dodaj ostatni statement jeśli nie pusty
        $statement = trim($current);
        if (!empty($statement)) {
            $statements[] = $statement;
        }
        
        foreach ($statements as $statement) {
            if (!empty($statement)) {
                $conn->exec($statement);
            }
        }
        
        // Zapisz wykonaną migrację
        $stmt = $conn->prepare("INSERT INTO migrations (filename) VALUES (:filename)");
        $stmt->bindValue(':filename', $filename, SQLITE3_TEXT);
        $stmt->execute();
        
        echo " OK\n";
        $count++;
    } catch (Exception $e) {
        echo " ERROR: " . $e->getMessage() . "\n";
        echo "Statement: " . substr($statement ?? '', 0, 100) . "...\n";
        exit(1);
    }
}

echo "\n=== Done. {$count} migration(s) executed. ===\n";
