<?php
require_once 'config.php';
require_once 'functions.php';

if (isLoggedIn()) redirect('dashboard.php');

$success = false;
$error   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $email = trim($_POST['email'] ?? '');

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Adresse email invalide.";
    } else {
        $stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user) {
            // Supprimer anciens tokens
            $pdo->prepare("DELETE FROM password_reset_tokens WHERE user_id = ?")->execute([$user['id']]);

            $token   = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
            $pdo->prepare("INSERT INTO password_reset_tokens (user_id, token, expires_at) VALUES (?, ?, ?)")
                ->execute([$user['id'], $token, $expires]);

            $link = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']
                  . dirname($_SERVER['REQUEST_URI']) . '/reset_password.php?token=' . $token;

            sendPasswordResetEmail($email, $user['name'], $link);
        }
        // Toujours afficher succès (sécurité anti-énumération)
        $success = true;
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mot de passe oublié - First Car</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php include 'header.php'; ?>
<main class="container">
  <div class="form-wrapper">
    <div style="text-align:center;margin-bottom:2rem;">
      <h1 style="font-family:'Cormorant Garamond',serif;font-size:2.2rem;font-weight:700;">Mot de passe oublié</h1>
      <p style="color:var(--light2);font-size:.88rem;margin-top:.5rem;font-weight:300;">Entrez votre email pour recevoir un lien de réinitialisation.</p>
    </div>

    <?php if ($success): ?>
      <div class="alert success" style="text-align:center;padding:2rem;">
        <div style="font-size:2.5rem;margin-bottom:.8rem;">📧</div>
        <strong>Email envoyé !</strong><br>
        Si cet email est associé à un compte, vous recevrez un lien de réinitialisation valable <strong>1 heure</strong>.
      </div>
      <div style="text-align:center;margin-top:1.5rem;">
        <a href="login.php" class="btn btn-outline">← Retour à la connexion</a>
      </div>
    <?php else: ?>
      <?php if ($error): ?>
      <div class="alert error"><?= sanitize($error) ?></div>
      <?php endif; ?>
      <div class="form">
        <form method="post">
          <?= csrf_field() ?>
          <div class="form-group">
            <label for="email">Adresse email</label>
            <input type="email" id="email" name="email" placeholder="vous@exemple.com" required autocomplete="email">
          </div>
          <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;padding:1rem;">
            Envoyer le lien de réinitialisation
          </button>
        </form>
      </div>
      <p class="text-center mt-2" style="color:var(--light2);font-size:.88rem;">
        <a href="login.php" style="color:var(--orange);">← Retour à la connexion</a>
      </p>
    <?php endif; ?>
  </div>
</main>
<?php include 'footer.php'; ?>
</body>
</html>
