<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . '/config.php'; // Make sure $conn is defined in config.php

// Read email from request body
$data = json_decode(file_get_contents("php://input"), true);
$email = trim($data['email'] ?? '');

if (!$email) {
    echo json_encode([
        "success" => false,
        "message" => "Email is required",
        "recentWithdrawals" => []
    ]);
    exit;
}

try {
    $recentWithdrawals = [];

    // Fetch all withdrawals including pending
    $withdrawQuery = "
        SELECT 
            wr.id,
            wr.user_id,
            wr.trade_id,
            wr.amount,
            wr.type,
            wr.comment,
            wr.withdrawal_method,
            wr.status,
            wr.admin_comment,
            wr.created_at AS date,
            wr.email,
            la.account_name
        FROM withdrawal_requests wr
        LEFT JOIN liveaccounts la ON la.trade_id = wr.trade_id
        WHERE wr.email = ?
        ORDER BY wr.created_at DESC
    ";

    $stmt = $conn->prepare($withdrawQuery);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $recentWithdrawals[] = $row;
    }

    // Return JSON
    echo json_encode([
        "success" => true,
        "recentWithdrawals" => $recentWithdrawals
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error fetching withdrawals: " . $e->getMessage(),
        "recentWithdrawals" => []
    ]);
}
?>
