<?php
require 'includes/db.php';

$token = $_GET['token'] ?? '';
$message = '';
$error = '';

if (!$token) {
    $error = "⚠️ No reset token found in the link. Please use the correct link sent to your email.";
} else {
    // Check token in DB
    $stmt = $pdo->prepare("SELECT id FROM users WHERE password_reset_token = ?");
    $stmt->execute([$token]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        $error = "⚠️ Invalid or expired reset link.";
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $user) {
        $password = $_POST['password'];
        $passwordConfirm = $_POST['password_confirm'];

        if ($password !== $passwordConfirm) {
            $message = "⚠️ Passwords do not match.";
        } elseif (strlen($password) < 6) {
            $message = "⚠️ Password must be at least 6 characters.";
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ?, password_reset_token = NULL WHERE id = ?");
            $stmt->execute([$hash, $user['id']]);

            $message = "✅ Password reset successful. You can now <a href='login.php'>log in</a>.";
            $token = ''; // Hide form
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Reset Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4 container">
    <h2>Reset Password</h2>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <p><a href="forgot_password.php" class="btn btn-secondary">Request New Link</a></p>
    <?php elseif ($message): ?>
        <div class="alert alert-info"><?= $message ?></div>
    <?php elseif ($token): ?>
        <form method="POST" class="card p-4 shadow-sm">
            <div class="mb-3">
                <label class="form-label">New Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Confirm Password</label>
                <input type="password" name="password_confirm" class="form-control" required>
            </div>
            <button class="btn btn-primary">Reset Password</button>
        </form>
    <?php endif; ?>
</body>
</html>
