<?php
require __DIR__ . '/auth.php';
auth_start_session();

$authData = auth_load();
$needsSetup = empty($authData['passwordHash']);
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'setup' && $needsSetup) {
        $pw1 = (string)($_POST['password'] ?? '');
        $pw2 = (string)($_POST['password2'] ?? '');
        if (strlen($pw1) < 8) {
            $error = "Le mot de passe doit faire au moins 8 caractères.";
        } elseif ($pw1 !== $pw2) {
            $error = "Les deux mots de passe ne correspondent pas.";
        } else {
            $authData['passwordHash'] = password_hash($pw1, PASSWORD_DEFAULT);
            auth_save($authData);
            session_regenerate_id(true);
            $_SESSION['auth'] = true;
            header('Location: index.php');
            exit;
        }
    } elseif ($action === 'login' && !$needsSetup) {
        if (!auth_rate_limit_ok()) {
            $error = "Trop de tentatives. Réessaie dans quelques minutes.";
        } else {
            $pw = (string)($_POST['password'] ?? '');
            if (password_verify($pw, $authData['passwordHash'])) {
                auth_rate_limit_reset();
                session_regenerate_id(true);
                $_SESSION['auth'] = true;
                header('Location: index.php');
                exit;
            } else {
                auth_rate_limit_record();
                $error = "Mot de passe incorrect.";
            }
        }
    }
}

header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: no-referrer');

if (auth_is_authenticated()) {
    // Connecté : on sert le tableau de bord tel quel.
    readfile(__DIR__ . '/tableau-de-bord.html');
    exit;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet">
<title><?php echo $needsSetup ? 'Configuration — Tableau de bord' : 'Connexion — Tableau de bord'; ?></title>
<style>
  :root{
    color-scheme: light;
    --surface:#fcfcfb; --plane:#f9f9f7; --ink:#0b0b0b; --ink-2:#52514e; --ink-muted:#898781;
    --ring:rgba(11,11,11,.10); --accent:#2a78d6; --accent-wash:#eaf1fb; --critical:#d03b3b;
    --radius:12px;
  }
  @media (prefers-color-scheme: dark){
    :root{
      color-scheme: dark;
      --surface:#1a1a19; --plane:#0d0d0d; --ink:#ffffff; --ink-2:#c3c2b7; --ink-muted:#898781;
      --ring:rgba(255,255,255,.10); --accent:#3987e5; --accent-wash:#1c2c40;
    }
  }
  *{box-sizing:border-box;}
  html,body{margin:0;height:100%;}
  body{
    background:var(--plane); color:var(--ink);
    font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
    display:flex; align-items:center; justify-content:center; min-height:100%; padding:20px;
  }
  .card{
    width:100%; max-width:340px; background:var(--surface); border:1px solid var(--ring);
    border-radius:var(--radius); padding:28px 24px;
  }
  h1{font-size:1.05rem; margin:0 0 4px;}
  p.sub{font-size:.83rem; color:var(--ink-2); margin:0 0 20px;}
  label{display:block; font-size:.78rem; color:var(--ink-2); margin:14px 0 5px;}
  input[type=password]{
    width:100%; padding:10px 12px; border:1px solid var(--ring); border-radius:9px;
    background:var(--plane); color:var(--ink); font-size:.95rem;
  }
  input[type=password]:focus{outline:2px solid var(--accent); outline-offset:1px;}
  button{
    width:100%; margin-top:20px; padding:11px; border:none; border-radius:9px;
    background:var(--accent); color:#fff; font-size:.9rem; font-weight:600; cursor:pointer;
  }
  button:hover{opacity:.92;}
  .error{
    margin-top:14px; padding:9px 12px; border-radius:8px; background:rgba(208,59,59,.1);
    color:var(--critical); font-size:.82rem;
  }
  .hint{margin-top:16px; font-size:.75rem; color:var(--ink-muted); line-height:1.5;}
</style>
</head>
<body>
  <form class="card" method="post" autocomplete="off">
    <?php if ($needsSetup): ?>
      <h1>Configuration du tableau de bord</h1>
      <p class="sub">Première visite — choisis le mot de passe qui protégera l'accès à ton tableau de bord.</p>
      <input type="hidden" name="action" value="setup">
      <label for="password">Mot de passe (8 caractères minimum)</label>
      <input type="password" id="password" name="password" required minlength="8" autocomplete="new-password">
      <label for="password2">Confirme le mot de passe</label>
      <input type="password" id="password2" name="password2" required minlength="8" autocomplete="new-password">
      <button type="submit">Créer mon accès</button>
      <div class="hint">Ce mot de passe est le seul moyen d'accéder à tes données — garde-le pour toi. Tu pourras le changer plus tard depuis le tableau de bord.</div>
    <?php else: ?>
      <h1>Tableau de bord Rémy GOUTHIER</h1>
      <p class="sub">Accès privé — entre ton mot de passe.</p>
      <input type="hidden" name="action" value="login">
      <label for="password">Mot de passe</label>
      <input type="password" id="password" name="password" required autocomplete="current-password" autofocus>
      <button type="submit">Se connecter</button>
    <?php endif; ?>
    <?php if ($error): ?>
      <div class="error"><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></div>
    <?php endif; ?>
  </form>
</body>
</html>
