<?php
// CORS headers - Put these at the VERY TOP of the file
$allowedOrigins = [
    'http://localhost:5173',
    'http://localhost:3000',
    // Add your production domains here
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (in_array($origin, $allowedOrigins)) {
    header("Access-Control-Allow-Origin: $origin");
} else {
    // For development, you might want to allow all origins temporarily
    header('Access-Control-Allow-Origin: *');
}

header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With, Authorization, X-CSRF-Token, Accept, Origin');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Content-Length: 0');
    http_response_code(200);
    exit();
}


// Load CORS configuration FIRST
require_once __DIR__ . '/includes/cors.php';
configureCors();

// Load environment variables
require_once __DIR__ . '/includes/config_loader.php';

// Load dependencies
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/auth_functions.php'; // Your existing auth functions
require_once __DIR__ . '/includes/sms_helper.php';
require_once __DIR__ . '/includes/email_helper.php'; // If you have separate email helper
require_once __DIR__ . '/auth/AuditLogger.php';
require_once __DIR__ . '/auth/JWTManager.php';


$response = ["status" => "error", "message" => "Unknown error"];
$smtpConfig = loadSmtpConfig();

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(["status" => "error", "message" => "Method not allowed"]);
        exit;
    }

    // Get JSON payload
    $data = json_decode(file_get_contents("php://input"), true);
    if (!$data || empty($data['email'])) {
        http_response_code(400);
        echo json_encode(["status" => "error", "message" => "Email is required"]);
        exit;
    }

    $email = filter_var($data['email'], FILTER_SANITIZE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(422);
        echo json_encode(["status" => "error", "message" => "Invalid email format"]);
        exit;
    }

    // Rate limiting based on email
    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM password_resets 
        WHERE email = ? AND created_at > NOW() - INTERVAL 1 HOUR
    ");
    $stmt->execute([$email]);
    if ($stmt->fetchColumn() > 3) {
        http_response_code(429);
        echo json_encode(["status" => "error", "message" => "Too many requests. Try again later."]);
        exit;
    }

    // Check if member exists in the database
    $stmt = $pdo->prepare("
        SELECT a.member_id, a.username, m.first_name, m.last_name, a.email
        FROM member_portal_accounts a
        JOIN members m ON m.id = a.member_id
        WHERE a.email = ?
    ");
    $stmt->execute([$email]);
    $member = $stmt->fetch();

    // Always return success to avoid account enumeration
    $genericMessage = "If this email is registered with our member portal, you will receive a reset link shortly.";

    if (!$member) {
        echo json_encode(["status" => "success", "message" => $genericMessage]);
        exit;
    }

    // Generate secure token
    $token = bin2hex(random_bytes(32));
    $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));

    // Insert password reset request with member_id and user_type
    $stmt = $pdo->prepare("
        INSERT INTO password_resets (email, token, expires_at, user_type, member_id) 
        VALUES (?, ?, ?, 'member', ?)
    ");
    $stmt->execute([$email, $token, $expiry, $member['member_id']]);

    // Clean up expired tokens
    $pdo->exec("DELETE FROM password_resets WHERE expires_at < NOW()");

    // Create reset link
    $resetLink = 'https://' . $_SERVER['HTTP_HOST'] . '/reset_password.php?token=' . urlencode($token);

    // Send password reset email
    if (sendPasswordResetEmail($email, $member['first_name'], $member['username'], $resetLink, $smtpConfig)) {
        // Log security event with member_id
        logSecurityEvent($member['member_id'], 'password_reset_requested', [
            'email' => $email,
            'token' => $token,
            'ip' => $_SERVER['REMOTE_ADDR'],
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
        ]);
        
        echo json_encode(["status" => "success", "message" => $genericMessage]);
    } else {
        // Delete the inserted token if email failed
        $stmt = $pdo->prepare("DELETE FROM password_resets WHERE token = ?");
        $stmt->execute([$token]);
        
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Failed to send reset email. Please try again."]);
    }
} catch (PDOException $e) {
    error_log("Database error in forgot password API: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database error. Please try again later."]);
} catch (Exception $e) {
    error_log("Forgot password API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Server error. Please try again later."]);
}