<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

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

// Créer table si absente
try { $pdo->exec("CREATE TABLE IF NOT EXISTS password_resets (
    id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL,
    token VARCHAR(64) NOT NULL, expires_at DATETIME NOT NULL,
    used TINYINT(1) DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_token (token)
)"); } catch(Exception $e){}

// Valider le token
$resetRow = null;
if ($token) {
    $stmt = $pdo->prepare("SELECT r.*, u.username FROM password_resets r JOIN users u ON u.id=r.user_id WHERE r.token=? AND r.used=0 AND r.expires_at > NOW() LIMIT 1");
    $stmt->execute([$token]);
    $resetRow = $stmt->fetch();
    if ($resetRow) $valid = true;
}

if ($valid && $_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['do_reset'])) {
    $pw1 = $_POST['password'] ?? '';
    $pw2 = $_POST['password2'] ?? '';
    if (strlen($pw1) < 8) {
        $error = "Le mot de passe doit contenir au moins 8 caractères.";
    } elseif ($pw1 !== $pw2) {
        $error = "Les deux mots de passe ne correspondent pas.";
    } else {
        $hash = password_hash($pw1, PASSWORD_BCRYPT);
        $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([$hash, $resetRow['user_id']]);
        $pdo->prepare("UPDATE password_resets SET used=1 WHERE token=?")->execute([$token]);
        // Connecter l'user directement
        $_SESSION['user_id'] = $resetRow['user_id'];
        $_SESSION['logged_in'] = true;
        $msg = "Mot de passe changé avec succès !";
        header("Location: index.php?reset=ok"); exit;
    }
}

include 'header.php';
?>
<div class="container" style="max-width:440px;margin:60px auto;">
    <div class="card bg-dark border-info shadow">
        <div class="card-header py-2 text-info fw-bold" style="background:#050520;letter-spacing:1px;font-size:0.8rem;">
            <i class="fa-solid fa-key me-2"></i>NOUVEAU MOT DE PASSE
        </div>
        <div class="card-body p-4">
            <?php if (!$token || !$valid): ?>
            <div class="alert alert-danger py-2 small">
                <i class="fa-solid fa-triangle-exclamation me-1"></i>
                Ce lien est invalide ou a expiré. <a href="forgot_password.php" class="alert-link">Faire une nouvelle demande</a>.
            </div>
            <?php else: ?>
            <?php if ($error): ?><div class="alert alert-danger py-2 small"><?= htmlspecialchars($error) ?></div><?php endif; ?>
            <p class="text-muted small mb-3">Bonjour <strong class="text-white"><?= htmlspecialchars($resetRow['username']) ?></strong>, choisissez un nouveau mot de passe.</p>
            <form method="POST">
                <div class="mb-3">
                    <label class="small fw-bold text-muted mb-1" style="font-size:0.65rem;">NOUVEAU MOT DE PASSE</label>
                    <input type="password" name="password" class="form-control bg-dark text-white border-secondary"
                           placeholder="Minimum 8 caractères" required minlength="8" autofocus>
                </div>
                <div class="mb-3">
                    <label class="small fw-bold text-muted mb-1" style="font-size:0.65rem;">CONFIRMER LE MOT DE PASSE</label>
                    <input type="password" name="password2" class="form-control bg-dark text-white border-secondary"
                           placeholder="Répétez le mot de passe" required minlength="8">
                </div>
                <button type="submit" name="do_reset" class="btn btn-info w-100 fw-bold">
                    <i class="fa-solid fa-shield-check me-1"></i>Changer le mot de passe
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
