<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['message'] = "Security check failed (CSRF). Please try again.";
    } else {
        $email = trim($_POST['email'] ?? '');
        
        if (empty($email)) {
            $response['message'] = "Please enter your email address.";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $response['message'] = "Invalid email format.";
        } else {
            // Rate limiting: max 1 reset request per 5 minutes per email (#3)
            $rate_key = 'reset_' . md5($email);
            if (isset($_SESSION[$rate_key]) && (time() - $_SESSION[$rate_key]) < 300) {
                $remaining = ceil((300 - (time() - $_SESSION[$rate_key])) / 60);
                $response['message'] = "Please wait $remaining minute(s) before requesting another password reset.";
                echo json_encode($response);
                exit();
            }
            $_SESSION[$rate_key] = time();

            try {
                $stmt = $pdo->prepare("SELECT id, username FROM users WHERE email = ?");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user) {
                    $token = bin2hex(random_bytes(32));
                    $stmt_update = $pdo->prepare("
                        UPDATE users 
                        SET reset_token = ?, reset_token_expires = CURRENT_TIMESTAMP + INTERVAL '1 hour' 
                        WHERE id = ?
                    ");
                    $stmt_update->execute([$token, $user['id']]);
                    
                    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
                    $base_dir = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
                    // Go up one level from /api/ to get root URL for reset_password.php
                    $root_dir = preg_replace('/\/api\/?$/i', '', $base_dir);
                    $reset_link = $protocol . "://" . $_SERVER['HTTP_HOST'] . $root_dir . "/reset_password?token=" . $token;
                    
                    require_once __DIR__ . '/../../includes/notification_helper.php';
                    sendMultichannelNotification($user['id'], 'password_reset', [
                        'username' => $user['username'],
                        'reset_link' => $reset_link
                    ]);
                    
                    $response['success'] = true;
                    $response['message'] = "A password reset link has been generated and sent to your registered notification channels.";
                } else {
                    $response['success'] = true;
                    $response['message'] = "If that email exists in our system, we have sent a reset link to it.";
                }
            } catch (PDOException $e) {
                error_log("Forgot password error: " . $e->getMessage());
                $response['message'] = "An unexpected error occurred. Please try again later.";
            }
        }
    }
} else {
    $response['message'] = "Invalid request method.";
}

echo json_encode($response);
