<?php
/**
 * install.php — Clean web/CLI installer.
 * Usage: php install.php   OR   open /install.php in browser
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/installer.php';

$isCli = (PHP_SAPI === 'cli');

try {
    $pdo = db();
    $log = run_install($pdo);
} catch (Throwable $ex) {
    $error = 'ERROR: ' . $ex->getMessage();
    if ($isCli) {
        fwrite(STDERR, $error . PHP_EOL);
        exit(1);
    }
    http_response_code(500);
    echo '<pre>' . htmlspecialchars($error) . '</pre>';
    exit;
}

if ($isCli) {
    echo implode(PHP_EOL, $log) . PHP_EOL;
    exit(0);
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Install · Panel</title>
    <style>
        body { font-family: system-ui, sans-serif; background: #0f0f13; color: #eee; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }
        h1 { font-size: 1.4rem; }
        ul { background: #1a1a22; border-radius: 12px; padding: 1.25rem 1.5rem; list-style: none; }
        li { padding: 0.35rem 0; font-size: 0.95rem; }
        .btn { display: inline-block; margin-top: 1.25rem; padding: 0.75rem 1.25rem; background: #6d28d9; color: #fff; text-decoration: none; border-radius: 8px; font-weight: 600; }
        .muted { opacity: 0.6; font-size: 0.85rem; margin-top: 1rem; }
    </style>
</head>
<body>
    <h1>Panel installation</h1>
    <ul>
        <?php foreach ($log as $line): ?>
            <?php if ($line === ''): ?>
                <li>&nbsp;</li>
            <?php else: ?>
                <li><?= htmlspecialchars($line) ?></li>
            <?php endif; ?>
        <?php endforeach; ?>
    </ul>
    <a class="btn" href="login.php">Go to login</a>
    <p class="muted">Idempotent — safe to run again. Default login: admin / admin</p>
</body>
</html>
