<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once 'includes/db.php';

$token = $_GET["token"] ?? '';
$token_hash = hash("sha256", $token);

// 1. Find the user by the hashed token
$stmt = $conn->prepare("SELECT * FROM users WHERE reset_token_hash = ?");
$stmt->bind_param("s", $token_hash);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 2. Check if token is valid and not expired
$is_token_valid = true;
if ($user === null) {
    $is_token_valid = false;
} elseif (strtotime($user["reset_token_expires_at"]) <= time()) {
    $is_token_valid = false;
}

$errors = [];
// 3. Handle form submission to update the password
if ($_SERVER["REQUEST_METHOD"] === "POST" && $is_token_valid) {
    $password = $_POST["password"];
    $password_confirm = $_POST["password_confirm"];

    if (strlen($password) < 8) { $errors[] = "Password must be at least 8 characters."; }
    if ($password !== $password_confirm) { $errors[] = "Passwords do not match."; }

    if (empty($errors)) {
        $password_hash = password_hash($password, PASSWORD_DEFAULT);
        
        // Update password and clear the reset token
        $stmt_update = $conn->prepare("UPDATE users SET password = ?, reset_token_hash = NULL, reset_token_expires_at = NULL WHERE id = ?");
        $stmt_update->bind_param("si", $password_hash, $user["id"]);
        $stmt_update->execute();
        
        $_SESSION['success_message'] = "Password has been reset. You can now log in.";
        header("Location: login.php");
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Your Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <style> body { background-color: var(--bs-light-gray); } </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center align-items-center vh-100">
            <div class="col-md-8 col-lg-6 col-xl-5">
                <div class="text-center mb-4"><h1 class="h2">Set New Password</h1></div>
                <div class="card shadow-sm border-0">
                    <div class="card-body p-4 p-md-5">
                        
                        <?php if (!$is_token_valid): ?>
                            <div class="alert alert-danger">Invalid or expired link. Please request a new one.</div>
                            <div class="d-grid"><a href="forgot-password.php" class="btn btn-primary">Request New Link</a></div>
                        <?php else: ?>
                            <?php if (!empty($errors)): ?>
                                <div class="alert alert-danger">
                                    <?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            <form method="POST">
                                <div class="mb-3">
                                    <label for="password" class="form-label">New Password</label>
                                    <input type="password" class="form-control" id="password" name="password" required>
                                </div>
                                <div class="mb-3">
                                    <label for="password_confirm" class="form-label">Confirm New Password</label>
                                    <input type="password" class="form-control" id="password_confirm" name="password_confirm" required>
                                </div>
                                <div class="d-grid">
                                    <button type="submit" class="btn btn-primary btn-lg">Reset Password</button>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
