#!/opt/cpanel/ea-php85/root/usr/bin/php
<?php

declare(strict_types=1);

use App\Support\Bootstrap;

require dirname(__DIR__) . '/vendor/autoload.php';

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, "This script must be run from the command line.\n");
    exit(1);
}

try {
    $bootstrap = new Bootstrap(dirname(__DIR__));
    $result = $bootstrap->migrationRunner()->run();
} catch (Throwable $e) {
    fwrite(STDERR, sprintf("Migration run failed: %s\n", $e->getMessage()));
    exit(1);
}

foreach ($result['applied'] as $migration) {
    echo "APPLIED  {$migration}\n";
}
foreach ($result['skipped'] as $migration) {
    echo "SKIPPED  {$migration} (already applied)\n";
}

printf("Done: %d applied, %d skipped.\n", count($result['applied']), count($result['skipped']));

/*
 * The admin panel (Box2) reads the schema from its own mirror table, not from
 * information_schema. A table or column the mirror does not know about makes
 * the panel screen come back EMPTY, with no error — it has already cost two
 * debugging sessions. We do not refresh it from here (the MCP core has no
 * business writing the panel's tables), but a migration that lands without the
 * refresh must not pass in silence.
 */
if ($result['applied'] !== []) {
    try {
        $stale = $bootstrap->connection()->select(
            "SELECT t.TABLE_NAME
               FROM information_schema.TABLES t
              WHERE t.TABLE_SCHEMA = DATABASE()
                AND t.TABLE_TYPE = 'BASE TABLE'
                AND NOT EXISTS (SELECT 1 FROM COLUMNS c WHERE c.TABLE_NAME = t.TABLE_NAME)"
        );

        if ($stale !== []) {
            $names = implode(', ', array_map(static fn (array $r): string => (string) $r['TABLE_NAME'], $stale));
            fwrite(STDERR, "\nAVISO: o espelho de schema do painel esta desatualizado.\n");
            fwrite(STDERR, "  Tabelas que o painel ainda nao enxerga: {$names}\n");
            fwrite(STDERR, "  As telas dessas tabelas vao aparecer VAZIAS, sem mensagem de erro.\n");
            fwrite(STDERR, "  Corrija rodando a rotina Info Schema no menu Sistema do painel.\n");
        }
    } catch (Throwable) {
        // No mirror table means the panel is not installed here — nothing to warn about.
    }
}
