<?php
/** Simple shared-hosting friendly SQL migration runner. */
declare(strict_types=1);
define('BASE_PATH', dirname(__DIR__));
require_once BASE_PATH . '/src/config.php';
$pdo = db();
$dir = BASE_PATH . '/database';
$file = $argv[1] ?? '';
$files = [];
if ($file !== '') {
    $path = is_file($file) ? $file : $dir . '/' . $file;
    if (!is_file($path)) { fwrite(STDERR, "Migration not found: {$file}\n"); exit(1); }
    $files[] = $path;
} else {
    $files = glob($dir . '/UPDATE_*.sql') ?: [];
    sort($files, SORT_NATURAL);
}
foreach ($files as $path) {
    $sql = file_get_contents($path);
    if ($sql === false || trim($sql) === '') continue;
    echo "Applying " . basename($path) . "...\n";
    try {
        $pdo->exec($sql);
        echo "OK\n";
    } catch (Throwable $e) {
        fwrite(STDERR, "FAILED " . basename($path) . ": " . $e->getMessage() . "\n");
        exit(1);
    }
}
echo "Done\n";
