<?php
// Safe migration runner: includes db_config.php and executes SQL file.
// Usage (PowerShell): C:\xampp\php\php.exe -f migrations\apply_migration.php

$base = __DIR__;
$dbConfig = realpath($base . '/../db_config.php');
$sqlFile = realpath($base . '/001_create_users_admins.sql');

if (!file_exists($dbConfig)) {
    echo "Error: db_config.php not found at $dbConfig\n";
    exit(1);
}
if (!file_exists($sqlFile)) {
    echo "Error: SQL file not found at $sqlFile\n";
    exit(1);
}

require $dbConfig; // provides $conn (mysqli)

$sql = file_get_contents($sqlFile);
if ($sql === false) {
    echo "Error: failed to read SQL file\n";
    exit(1);
}

if ($conn->multi_query($sql)) {
    do {
        if ($result = $conn->store_result()) {
            while ($row = $result->fetch_row()) {
                // no-op: just flush
            }
            $result->free();
        }
    } while ($conn->more_results() && $conn->next_result());

    echo "Migration applied successfully.\n";
    exit(0);
} else {
    echo "Migration failed: (" . $conn->errno . ") " . $conn->error . "\n";
    exit(2);
}
