<?php
/**
 * Mini-projet 04 — Formulaire de contact sécurisé
 * Démarrage : php -S localhost:8000 puis http://localhost:8000/solution.php
 */
session_start();

// Générer le token CSRF si inexistant
if (empty($_SESSION['csrf_contact'])) {
    $_SESSION['csrf_contact'] = bin2hex(random_bytes(32));
}

$erreurs = [];
$success = false;
$donnees = ['nom' => '', 'email' => '', 'sujet' => '', 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ── 1. Vérification CSRF ─────────────────────────────
    $tokenRecu = $_POST['csrf_token'] ?? '';
    if (!hash_equals($_SESSION['csrf_contact'], $tokenRecu)) {
        $erreurs['csrf'] = "Requête invalide (token CSRF incorrect)";
    }

    // ── 2. Honeypot anti-spam (champ caché rempli = robot) ─
    if (!empty($_POST['website'])) {
        $erreurs['spam'] = "Formulaire détecté comme spam";
    }

    if (empty($erreurs)) {
        // ── 3. Lecture et nettoyage ───────────────────────
        $nom     = trim($_POST['nom']     ?? '');
        $email   = trim($_POST['email']   ?? '');
        $sujet   = trim($_POST['sujet']   ?? '');
        $message = trim($_POST['message'] ?? '');

        // ── 4. Validation ─────────────────────────────────
        if (strlen($nom) < 2 || strlen($nom) > 60)
            $erreurs['nom'] = "Nom : 2 à 60 caractères";
        if (!filter_var($email, FILTER_VALIDATE_EMAIL))
            $erreurs['email'] = "Email invalide";
        if (strlen($sujet) < 3 || strlen($sujet) > 100)
            $erreurs['sujet'] = "Sujet : 3 à 100 caractères";
        if (strlen($message) < 20 || strlen($message) > 2000)
            $erreurs['message'] = "Message : 20 à 2000 caractères";

        if (empty($erreurs)) {
            $success = true;
            $donnees = compact('nom', 'email', 'sujet', 'message');
            // Régénérer le token après utilisation réussie
            $_SESSION['csrf_contact'] = bin2hex(random_bytes(32));
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Formulaire de contact</title>
  <style>
    *{margin:0;padding:0;box-sizing:border-box}
    body{background:#0a0e1a;color:#e6edf3;font-family:'Segoe UI',sans-serif;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:2rem 1rem}
    .form-card{background:rgba(22,27,34,.8);border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:2rem;width:100%;max-width:540px;backdrop-filter:blur(20px)}
    h1{font-size:1.4rem;font-weight:700;color:#79c0ff;margin-bottom:.3rem}
    .subtitle{color:#8b949e;font-size:.85rem;margin-bottom:1.5rem}
    .field{margin-bottom:1rem}
    label{display:block;font-size:.8rem;color:#8b949e;margin-bottom:.35rem;font-weight:600}
    input,textarea{width:100%;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.1);border-radius:8px;color:#e6edf3;padding:.6rem .9rem;font-size:.88rem;outline:none;transition:border-color .2s,box-shadow .2s;font-family:inherit}
    input:focus,textarea:focus{border-color:rgba(121,192,255,.5);box-shadow:0 0 0 3px rgba(121,192,255,.08)}
    input.error,textarea.error{border-color:#f85149}
    .error-msg{font-size:.76rem;color:#f85149;margin-top:.25rem}
    .honeypot{display:none}
    .btn{width:100%;padding:.75rem;background:#79c0ff;color:#0d1117;border:none;border-radius:8px;font-weight:700;font-size:.92rem;cursor:pointer;transition:opacity .2s;margin-top:.5rem}
    .btn:hover{opacity:.85}
    .success{background:rgba(63,185,80,.12);border:1px solid rgba(63,185,80,.3);border-radius:10px;padding:1.2rem;margin-bottom:1rem;color:#3fb950}
    .csrf-error{background:rgba(248,81,73,.1);border:1px solid rgba(248,81,73,.3);border-radius:10px;padding:.8rem 1rem;margin-bottom:1rem;color:#f85149;font-size:.85rem}
  </style>
</head>
<body>
<div class="form-card">
  <h1>📬 Formulaire de contact</h1>
  <p class="subtitle">Mini-projet 04 · PHP sécurisé</p>

  <?php if ($success): ?>
    <div class="success">
      ✅ Message envoyé avec succès !<br>
      <small>De : <?= htmlspecialchars($donnees['nom']) ?> &lt;<?= htmlspecialchars($donnees['email']) ?>&gt;</small><br>
      <small>Sujet : <?= htmlspecialchars($donnees['sujet']) ?></small>
    </div>
  <?php endif; ?>

  <?php if (!empty($erreurs['csrf'])): ?>
    <div class="csrf-error">⛔ <?= htmlspecialchars($erreurs['csrf']) ?></div>
  <?php endif; ?>

  <form method="POST" novalidate>
    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_contact'], ENT_QUOTES) ?>">

    <!-- Honeypot : un robot remplira ce champ caché, un humain ne le verra pas -->
    <div class="honeypot">
      <input type="text" name="website" tabindex="-1" autocomplete="off">
    </div>

    <div class="field">
      <label for="nom">Nom complet *</label>
      <input type="text" id="nom" name="nom" required minlength="2" maxlength="60"
             value="<?= htmlspecialchars($_POST['nom'] ?? '') ?>"
             class="<?= isset($erreurs['nom']) ? 'error' : '' ?>">
      <?php if (isset($erreurs['nom'])): ?>
        <div class="error-msg"><?= htmlspecialchars($erreurs['nom']) ?></div>
      <?php endif; ?>
    </div>

    <div class="field">
      <label for="email">Email *</label>
      <input type="email" id="email" name="email" required
             value="<?= htmlspecialchars($_POST['email'] ?? '') ?>"
             class="<?= isset($erreurs['email']) ? 'error' : '' ?>">
      <?php if (isset($erreurs['email'])): ?>
        <div class="error-msg"><?= htmlspecialchars($erreurs['email']) ?></div>
      <?php endif; ?>
    </div>

    <div class="field">
      <label for="sujet">Sujet *</label>
      <input type="text" id="sujet" name="sujet" required minlength="3" maxlength="100"
             value="<?= htmlspecialchars($_POST['sujet'] ?? '') ?>"
             class="<?= isset($erreurs['sujet']) ? 'error' : '' ?>">
      <?php if (isset($erreurs['sujet'])): ?>
        <div class="error-msg"><?= htmlspecialchars($erreurs['sujet']) ?></div>
      <?php endif; ?>
    </div>

    <div class="field">
      <label for="message">Message * (20-2000 caractères)</label>
      <textarea id="message" name="message" required minlength="20" maxlength="2000" rows="5"
                class="<?= isset($erreurs['message']) ? 'error' : '' ?>"><?= htmlspecialchars($_POST['message'] ?? '') ?></textarea>
      <?php if (isset($erreurs['message'])): ?>
        <div class="error-msg"><?= htmlspecialchars($erreurs['message']) ?></div>
      <?php endif; ?>
    </div>

    <button type="submit" class="btn">Envoyer le message →</button>
  </form>
</div>
</body>
</html>
