<?php
declare(strict_types=1);

/**
 * Pre-boot script: waits for MySQL, creates DB, runs migrations & seeds.
 * Called from entrypoint.sh — no shell escaping bullshit.
 */

echo "=== Boot Script Starting ===\n";

// Read env vars
$host = getenv('DB_HOST') ?: 'localhost';
$port = getenv('DB_PORT') ?: '3306';
$user = getenv('DB_USER') ?: 'root';
$pass = getenv('DB_PASS') ?: '';
$name = getenv('DB_NAME') ?: 'the_club_erp';

echo "DB_HOST: {$host}\n";
echo "DB_PORT: {$port}\n";
echo "DB_NAME: {$name}\n";
echo "DB_USER: {$user}\n";
echo "DB_PASS: " . (strlen($pass) > 0 ? '***SET***' : '***EMPTY***') . "\n";

// ── Wait for MySQL ──
echo "\nWaiting for MySQL...\n";
$maxTries = 30;
$pdo = null;
for ($i = 1; $i <= $maxTries; $i++) {
    try {
        $pdo = new PDO("mysql:host={$host};port={$port}", $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        ]);
        echo "MySQL is ready!\n";
        break;
    } catch (PDOException $e) {
        echo "  Attempt {$i}/{$maxTries}: " . $e->getMessage() . "\n";
        if ($i >= $maxTries) {
            echo "FATAL: MySQL not available after {$maxTries} attempts.\n";
            exit(1);
        }
        sleep(2);
    }
}

// ── Create database ──
echo "\nCreating database '{$name}' if not exists...\n";
try {
    $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    echo "Database ready!\n";
} catch (PDOException $e) {
    echo "FATAL: Could not create database: " . $e->getMessage() . "\n";
    exit(1);
}

$pdo = null; // close connection

// ── Run Migrations ──
echo "\n========================================\n";
echo "Running Migrations...\n";
echo "========================================\n";

chdir('/var/www/html');

require_once '/var/www/html/app/Core/Autoloader.php';
\App\Core\Autoloader::register();

// Load .env
$envFile = '/var/www/html/.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        if (str_contains($line, '=')) {
            [$k, $v] = explode('=', $line, 2);
            $k = trim($k);
            $v = trim($v);
            if (!isset($_ENV[$k])) {
                $_ENV[$k] = $v;
                putenv("{$k}={$v}");
            }
        }
    }
}

try {
    $db = new \App\Core\Database($host, (int) $port, $name, $user, $pass, 'utf8mb4');

    $migrationRunner = new \App\Core\Migration\MigrationRunner($db);
    $migrated = $migrationRunner->migrate();
    if (empty($migrated)) {
        echo "Nothing to migrate.\n";
    } else {
        echo "Ran " . count($migrated) . " migration(s):\n";
        foreach ($migrated as $m) {
            echo "  + {$m}\n";
        }
    }
} catch (Throwable $e) {
    echo "Migration error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "Continuing anyway...\n";
}

// ── Run Seeds ──
echo "\n========================================\n";
echo "Running Seeds...\n";
echo "========================================\n";

try {
    $seederRunner = new \App\Core\Seeder\SeederRunner($db);
    $seeded = $seederRunner->run();
    if (empty($seeded)) {
        echo "Nothing to seed.\n";
    } else {
        echo "Ran " . count($seeded) . " seed(s):\n";
        foreach ($seeded as $s) {
            echo "  + {$s}\n";
        }
    }
} catch (Throwable $e) {
    echo "Seed error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "Continuing anyway...\n";
}

echo "\n=== Boot Script Complete ===\n";