<?php
declare(strict_types=1);

$ADMIN_PASSWORD_HASH = '$2y$10$IrbPEkw0p0Bavt9oadJKWedAATFpByiLVkucGrTvv8toa01EUVQ/m';

session_start();

if (isset($_POST['password'])) {
    if (password_verify($_POST['password'], $ADMIN_PASSWORD_HASH)) {
        $_SESSION['security_admin_ok'] = true;
    }
}

if (isset($_GET['logout'])) {
    unset($_SESSION['security_admin_ok']);
    header('Location: ./');
    exit;
}

if (empty($_SESSION['security_admin_ok'])):
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Admin sécurité</title>
</head>
<body style="font-family:Arial;padding:30px;background:#111;color:white;">
<h1>🔐 Admin sécurité</h1>
<form method="post">
    <input type="password" name="password" placeholder="Mot de passe admin" style="padding:12px;">
    <button type="submit" style="padding:12px;">Connexion</button>
</form>
</body>
</html>
<?php
exit;
endif;

$logFile = dirname(__DIR__, 2) . '/privatedata/security-alerts.log';

if (isset($_POST['clear_logs'])) {
    file_put_contents($logFile, '', LOCK_EX);
    header('Location: ./');
    exit;
}

$lines = [];

if (file_exists($logFile)) {
    $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $lines = array_reverse($lines);
    $lines = array_slice($lines, 0, 200);
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Alertes sécurité Chrono Party</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{
    font-family:Arial;
    margin:0;
    padding:24px;
    background:#111827;
    color:white;
}
.card{
    background:#1f2937;
    border:1px solid rgba(255,255,255,.12);
    border-radius:18px;
    padding:18px;
    margin-bottom:14px;
}
.alert{
    background:#2b1d1d;
    border:1px solid rgba(255,80,80,.35);
    border-radius:14px;
    padding:12px;
    margin-bottom:10px;
    font-size:13px;
    line-height:1.5;
    word-break:break-word;
}
.btn{
    display:inline-block;
    padding:10px 14px;
    border-radius:10px;
    border:0;
    color:white;
    background:#7c3aed;
    font-weight:bold;
    text-decoration:none;
    cursor:pointer;
}
.btn.danger{
    background:#dc2626;
}
.empty{
    color:#cbd5e1;
}
</style>
</head>
<body>

<div class="card">
    <h1>🔐 Alertes sécurité Chrono Party</h1>
    <p>Total affiché : <?= count($lines) ?> alerte(s)</p>

    <form method="post" onsubmit="return confirm('Vider toutes les alertes ?');">
        <button class="btn danger" type="submit" name="clear_logs" value="1">Vider les alertes</button>
        <a class="btn" href="../">Retour admin</a>
        <a class="btn" href="?logout=1">Déconnexion</a>
    </form>
</div>

<?php if (empty($lines)): ?>
    <div class="card empty">
        Aucune alerte sécurité pour le moment.
    </div>
<?php else: ?>
    <?php foreach ($lines as $line): ?>
        <div class="alert"><?= htmlspecialchars($line, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endforeach; ?>
<?php endif; ?>

</body>
</html>