<?php
require_once 'config.php';

// Redirect logged-in users away from this page
if (is_logged_in()) {
    redirect('/dashboard');
}

// --- INITIALIZE VARIABLES FOR TEMPLATE (FIX) ---
// The auth_template requires $action and $email to be defined.
$action = 'forgot_password'; // Define a unique action for template logic if needed
$email = $_POST['email'] ?? ''; 
$page_title = 'Forgot Password';
$errors = $_SESSION['errors'] ?? [];
$success_message = $_SESSION['success_message'] ?? null;
unset($_SESSION['errors'], $_SESSION['success_message']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // 1. CSRF Token Validation
    if (!validate_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors['csrf'] = 'Invalid request token. Please refresh and try again.';
        goto render_form;
    }
    
    // 2. Rate Limit Check (Key: reset_request, Identifier: IP address)
    $client_ip = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
    if (!rate_limit('reset_request', $client_ip, 5, 3600)) { // Max 5 requests per hour (3.3)
        // Show generic success message to prevent timing attack
        $_SESSION['success_message'] = 'If your email is registered, a password reset link has been sent.';
        redirect('/forgot-password');
    }

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Please enter a valid email address.';
    }

    if (empty($errors)) {
        try {
            // 3. Find User
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND is_active = 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch();

            // IMPORTANT: Always show the same generic success message regardless of user existence
            if ($user) {
                $user_id = $user['id'];
                $token = generate_secure_token(32); // 64-char token (3.3)
                $expires_at = date('Y-m-d H:i:s', time() + 3600); // Expires in 1 hour
                $now = date('Y-m-d H:i:s');
                
                // 4. Invalidate old tokens and insert new token
                $pdo->prepare("DELETE FROM password_resets WHERE user_id = ? AND used_at IS NULL")->execute([$user_id]);

                $stmt = $pdo->prepare("INSERT INTO password_resets (user_id, token, expires_at, created_at, ip) 
                                       VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$user_id, $token, $expires_at, $now, $client_ip]);

                // 5. Send Email with Reset Link
                $reset_link = BASE_URL . '/reset-password?token=' . $token;
                $subject = APP_NAME . ': Password Reset Request';
                $body = "
                    <h2>Password Reset Request</h2>
                    <p>You requested a password reset for your " . APP_NAME . " account.</p>
                    <p>Click the link below to set a new password:</p>
                    <p><a href=\"" . $reset_link . "\" style='display: inline-block; padding: 10px 20px; background: #indigo-600; color: #ffffff; text-decoration: none; border-radius: 5px;'>Reset Password</a></p>
                    <p>This link will expire in 1 hour.</p>
                    <p>If you did not request this, please ignore this email.</p>
                ";
                send_email($email, $subject, $body);
            }

            $_SESSION['success_message'] = 'If your email is registered, a password reset link has been sent.';
            redirect('/forgot-password');

        } catch (PDOException $e) {
            error_log("Password Reset Request Error: " . $e->getMessage());
            $errors['database'] = 'A server error occurred. Please try again.';
        }
    }
}

render_form:
$csrf_token = generate_csrf_token();
// Include the HTML template
include 'templates/auth_template.php';
?>