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

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

$token = trim($_GET['token'] ?? '');
$error = '';
$done  = false;

// Valider le token
$stmt = $pdo->prepare("SELECT prt.*, u.name, u.email FROM password_reset_tokens prt
                        JOIN users u ON prt.user_id = u.id
                        WHERE prt.token = ? AND prt.used = 0 AND prt.expires_at > NOW()");
$stmt->execute([$token]);
$resetRow = $stmt->fetch();

if (!$resetRow && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $error = "Ce lien est invalide ou expiré. <a href='forgot_password.php' style='color:var(--orange);'>Demander un nouveau lien</a>";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $newPassword = $_POST['password'] ?? '';
    $confirm     = $_POST['confirm_password'] ?? '';
    $postToken   = $_POST['token'] ?? '';

    // Re-valider token depuis POST
    $stmt2 = $pdo->prepare("SELECT * FROM password_reset_tokens WHERE token = ? AND used = 0 AND expires_at > NOW()");
    $stmt2->execute([$postToken]);
    $resetRow2 = $stmt2->fetch();

    if (!$resetRow2) {
        $error = "Lien expiré. Veuillez refaire une demande.";
    } elseif (strlen($newPassword) < 8) {
        $error = "Le mot de passe doit faire au moins 8 caractères.";
    } elseif ($newPassword !== $confirm) {
        $error = "Les mots de passe ne correspondent pas.";
    } else {
        $hash = password_hash($newPassword, PASSWORD_BCRYPT, ['cost' => 12]);
        $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$hash, $resetRow2['user_id']]);
        $pdo->prepare("UPDATE password_reset_tokens SET used = 1 WHERE token = ?")->execute([$postToken]);
        $done = true;
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nouveau mot de passe - 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;">Nouveau mot de passe</h1>
    </div>

    <?php if ($done): ?>
      <div class="alert success" style="text-align:center;padding:2rem;">
        <div style="font-size:2.5rem;margin-bottom:.8rem;">✅</div>
        <strong>Mot de passe mis à jour !</strong><br>
        Vous pouvez maintenant vous connecter avec votre nouveau mot de passe.
      </div>
      <div style="text-align:center;margin-top:1.5rem;">
        <a href="login.php" class="btn btn-primary">Se connecter</a>
      </div>
    <?php elseif ($error && !$resetRow): ?>
      <div class="alert error"><?= $error ?></div>
    <?php else: ?>
      <?php if ($error): ?>
      <div class="alert error"><?= sanitize($error) ?></div>
      <?php endif; ?>
      <div class="form">
        <form method="post">
          <?= csrf_field() ?>
          <input type="hidden" name="token" value="<?= sanitize($token) ?>">
          <div class="form-group">
            <label for="password">Nouveau mot de passe * <span style="font-weight:300;text-transform:none;">(min. 8 car.)</span></label>
            <input type="password" id="password" name="password" placeholder="••••••••" required autocomplete="new-password">
          </div>
          <div class="form-group">
            <label for="confirm_password">Confirmer le mot de passe *</label>
            <input type="password" id="confirm_password" name="confirm_password" placeholder="••••••••" required autocomplete="new-password">
          </div>
          <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;padding:1rem;">
            Enregistrer le nouveau mot de passe
          </button>
        </form>
      </div>
    <?php endif; ?>
  </div>
</main>
<?php include 'footer.php'; ?>
</body>
</html>
