<?php
declare(strict_types=1);

require_once __DIR__ . '/common.php';

function checkPrintResult(string $label, bool $ok, string $detail = ''): void
{
    $status = $ok ? '[ok]' : '[fail]';
    installPrint($status . ' ' . $label . ($detail !== '' ? ' - ' . $detail : ''));
}

$argv = installArgv();

try {
    $options = installParseCliOptions($argv);
    $schemaPath = installResolveSchemaPath($argv, 'install/sql/mr.sql');

    $config = installLoadConfig();
    $pdo = installConnectPdo($config['db']);

    $schemaOk = file_exists($schemaPath);
    $coreTables = installCoreTables();
    $missing = [];
    foreach ($coreTables as $table) {
        if (!installHasTable($pdo, $table)) {
            $missing[] = $table;
        }
    }
    $coreTablesOk = ($missing === []);
    $migrationTableOk = installHasTable($pdo, installMigrationTableName());
    $pendingMigrations = $migrationTableOk ? installPendingMigrationKeys($pdo) : [];

    if (installIsCli()) {
        checkPrintResult('Konfiguration', true, installConfigPath());
        checkPrintResult('DB-Verbindung', true, (string) ($config['db']['host'] ?? 'localhost'));
        checkPrintResult('Basisschema', $schemaOk, $schemaPath);
        checkPrintResult('Kerntabellen', $coreTablesOk, $coreTablesOk ? 'vorhanden' : ('fehlend: ' . implode(', ', $missing)));
        checkPrintResult('Migrationstabelle', $migrationTableOk, installMigrationTableName());

        if (!empty($options['admin-email'])) {
            $validEmail = (bool) filter_var((string) $options['admin-email'], FILTER_VALIDATE_EMAIL);
            checkPrintResult('Admin-E-Mail', $validEmail, (string) $options['admin-email']);
        }

        if (array_key_exists('admin-password', $options)) {
            $pwOk = ((string) $options['admin-password']) !== '';
            checkPrintResult('Admin-Passwort', $pwOk, $pwOk ? 'gesetzt' : 'leer');
        }

        $overall = $schemaOk;
        installPrint('Gesamtstatus: ' . ($overall ? 'bereit' : 'Prüfung fehlgeschlagen'));
        exit($overall ? 0 : 1);
    }

    $rows = [
        ['Konfiguration', installConfigPath(), true],
        ['DB-Verbindung', (string) ($config['db']['host'] ?? 'localhost'), true],
        ['Basisschema', $schemaPath, $schemaOk],
        ['Kerntabellen', $coreTablesOk ? 'vorhanden' : ('fehlend: ' . implode(', ', $missing)), $coreTablesOk],
        ['Migrationstabelle', installMigrationTableName(), $migrationTableOk],
        ['Offene Migrationen', (string) count($pendingMigrations), true],
        ['Install-Lock', installIsLocked() ? 'aktiv' : 'nicht gesetzt', true],
    ];

    $tableHtml = '<table><tbody>';
    foreach ($rows as [$label, $detail, $ok]) {
        $tableHtml .= '<tr><th>' . installH($label) . '</th><td>' . installH($detail) . '</td><td>' . ($ok ? 'OK' : 'Fehler') . '</td></tr>';
    }
    $tableHtml .= '</tbody></table>';

    installRenderPage(
        'MailResponder Systemcheck',
        '<h1>MailResponder Systemcheck</h1>'
        . '<p class="muted">Prüft Konfiguration, Datenbank und Basisschema für Installation und Updates.</p>'
        . $tableHtml
        . '<div class="actions"><a class="btn btn-secondary" href="index.php">Zurück</a></div>'
    );
} catch (Throwable $e) {
    if (installIsCli()) {
        checkPrintResult('Prüfung', false, $e->getMessage());
        exit(1);
    }

    installRenderPage(
        'MailResponder Systemcheck',
        '<h1>MailResponder Systemcheck</h1><div class="box err"><strong>Prüfung fehlgeschlagen:</strong><br>' . installH($e->getMessage()) . '</div><div class="actions"><a class="btn btn-secondary" href="index.php">Zurück</a></div>'
    );
}