<?php
// File: forgot-password-handler.php (Final Version)
require_once 'db.php';
require_once 'email_helper.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

    // Find user by email
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Generate token and expiry
        $token = bin2hex(random_bytes(32));
        $expires_at = date("Y-m-d H:i:s", time() + 3600); // 1 hour expiry

        // Clear old tokens for this email and insert the new one
        $conn->query("DELETE FROM password_resets WHERE email = '$email'");
        $stmt_insert = $conn->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)");
        $stmt_insert->bind_param("sss", $email, $token, $expires_at);
        $stmt_insert->execute();

        // Prepare and send the email
        $reset_link = 'https://unitedculturalforum.com/reset-password.php?token=' . $token;
        $subject = "Password Reset Request for United Cultural Forum";
        $message = "
            <h2>Password Reset Request</h2>
            <p>Please click the link below to reset your password. This link is valid for one hour.</p>
            <p><a href='{$reset_link}'>{$reset_link}</a></p>
            <p>If you did not request this, please ignore this email.</p>
        ";
        
        sendEmail($email, $subject, $message);
    }

    // For security, always redirect to a success page to prevent user enumeration
    header("Location: forgot-password.php?status=success");
    exit();
}
?>

