<?php
require __DIR__ . '/bootstrap.php';

$done = false;
$error = '';
$created = false;

function run_sql_file_ready(string $file): void
{
    $sql = file_get_contents($file);
    if ($sql === false) {
        throw new RuntimeException('Nao foi possivel ler o SQL.');
    }
    $pdo = Database::pdo();
    $statements = array_filter(array_map('trim', preg_split('/;\s*(?:\r?\n|$)/', $sql)));
    foreach ($statements as $statement) {
        if ($statement !== '') {
            $pdo->exec($statement);
        }
    }
}

try {
    $pdo = Database::pdo();
    $hasUsers = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='users'")->fetchColumn();
    if (!$hasUsers) {
        run_sql_file_ready(ROOT_PATH . '/database/sqlite.sql');
    }
    if (!User::findByEmail('admin@autoescola.local')) {
        User::createAdmin('Administrador', 'admin@autoescola.local', 'admin123');
        $created = true;
    }
    Settings::saveMany(Settings::defaults());
    if (!Professional::all()) {
        Professional::create('Instrutor Principal', 'Instrutor');
    }
    $done = true;
} catch (Throwable $e) {
    $error = $e->getMessage();
}
?><!doctype html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Instalador - CFC Autoescola Pro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
</head>
<body class="install-bg">
<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-7">
            <div class="card shadow-soft border-0 rounded-4">
                <div class="card-body p-4 p-md-5">
                    <h1 class="h3 fw-bold text-primary">CFC Autoescola Pro</h1>
                    <?php if ($done): ?>
                        <div class="alert alert-success">Banco verificado e painel pronto para uso.</div>
                        <div class="border rounded-4 p-3 bg-light mb-3">
                            <div><strong>Acesso admin:</strong></div>
                            <div>E-mail: <code>admin@autoescola.local</code></div>
                            <div>Senha: <code>admin123</code></div>
                        </div>
                        <p class="text-danger fw-semibold">Por seguranca, altere a senha do admin e apague o arquivo install.php depois de confirmar o acesso.</p>
                        <a class="btn btn-primary rounded-pill px-4" href="<?= e(url('login')) ?>">Entrar no sistema</a>
                    <?php else: ?>
                        <div class="alert alert-danger">Erro ao preparar o sistema: <?= e($error) ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
