<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once 'includes/db.php';
require_once 'includes/helpers.php'; // For the send_email function

$message = '';
$message_type = '';

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

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "Please enter a valid email address.";
        $message_type = 'danger';
    } else {
        // Generate a secure, random token
        $token = bin2hex(random_bytes(16));
        $token_hash = hash("sha256", $token);
        
        // Set an expiry time (e.g., 15 minutes from now)
        $expiry_time = date("Y-m-d H:i:s", time() + 60 * 15);

        // Store the hashed token and expiry in the user's record
        $stmt = $conn->prepare("UPDATE users SET reset_token_hash = ?, reset_token_expires_at = ? WHERE email = ?");
        $stmt->bind_param("sss", $token_hash, $expiry_time, $email);
        $stmt->execute();

        // IMPORTANT: We send the email only if a user record was actually updated.
        if ($stmt->affected_rows > 0) {
            // Construct the reset link with the PLAINTEXT token
            $reset_link = "https://" . $_SERVER["HTTP_HOST"] . "/reset-password.php?token=$token";
            
            // Prepare and send the email
            $subject = "Password Reset Request";
            $body = "<p>Hello,</p><p>Someone requested a password reset for your account. If this was you, please click the link below to reset your password. The link is valid for 15 minutes.</p>";
            $body .= '<p><a href="' . $reset_link . '">' . $reset_link . '</a></p>';
            $body .= "<p>If you did not request a password reset, you can safely ignore this email.</p>";

            send_email($email, $subject, $body);
        }
        $stmt->close();
        
        // Show a generic success message regardless of whether the email was found.
        // This is a security measure to prevent user enumeration.
        $message = "If an account with that email exists, a password reset link has been sent.";
        $message_type = 'success';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot 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">Reset Password</h1></div>
                <div class="card shadow-sm border-0">
                    <div class="card-body p-4 p-md-5">
                        <?php if ($message): ?>
                            <div class="alert alert-<?php echo $message_type; ?>"><?php echo $message; ?></div>
                        <?php endif; ?>
                        <p class="text-muted">Enter your email address and we'll send you a link to reset your password.</p>
                        <form method="POST">
                            <div class="mb-3">
                                <label for="email" class="form-label">Email address</label>
                                <input type="email" class="form-control" id="email" name="email" required>
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary btn-lg">Send Reset Link</button>
                            </div>
                        </form>
                    </div>
                </div>
                 <div class="text-center mt-4">
                    <p class="text-muted">Remember your password? <a href="login.php">Sign In</a></p>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
