<?php
define('ANALYTICS_ROOT', __DIR__ . '/..');
define('ANALYTICS_VIEWS', ANALYTICS_ROOT . '/views');
define('ROOT_PATH', ANALYTICS_ROOT . '/../Audit');

require_once ANALYTICS_ROOT . '/lib/Env.php';
\Analytics\Lib\Env::load(ROOT_PATH . '/.env');

spl_autoload_register(function (string $class): void {
    $prefix = 'Analytics\\';
    if (strpos($class, $prefix) !== 0) return;
    $file = ANALYTICS_ROOT . '/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
    if (file_exists($file)) require_once $file;
});

$db = \Analytics\Lib\Database::getInstance();
$db->query("CREATE TABLE IF NOT EXISTS schema_migrations (
    migration  VARCHAR(255) NOT NULL UNIQUE,
    applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");

$applied = array_column($db->fetchAll('SELECT migration FROM schema_migrations'), 'migration');
$files   = glob(ANALYTICS_ROOT . '/database/migrations/*.sql');
sort($files);

foreach ($files as $file) {
    $name = basename($file);
    if (in_array($name, $applied, true)) {
        echo "SKIP $name\n";
        continue;
    }
    try {
        $sql = file_get_contents($file);
        foreach (array_filter(array_map('trim', explode(';', $sql))) as $stmt) {
            $db->query($stmt);
        }
        $db->insert('schema_migrations', ['migration' => $name, 'applied_at' => date('Y-m-d H:i:s')]);
        echo "OK   $name\n";
    } catch (\Throwable $e) {
        $msg = $e->getMessage();
        if (str_contains($msg, '1060') || str_contains($msg, 'Duplicate column') || str_contains($msg, '1050') || str_contains($msg, 'already exists')) {
            try { $db->insert('schema_migrations', ['filename' => $name, 'applied_at' => date('Y-m-d H:i:s')]); } catch (\Throwable $ie) {}
            echo "WARN $name\n";
        } else {
            echo "FAIL $name => $msg\n";
        }
    }
}
echo "Done.\n";
