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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

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

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

$total_withdraw_done = 0;

// -------------------- From ib_withdraw --------------------
$stmt1 = $conn->prepare("SELECT COALESCE(SUM(withdraw_amount), 0) AS total_done 
                         FROM ib_withdraw 
                         WHERE email = ? AND Status = 1");
$stmt1->bind_param("s", $email);
$stmt1->execute();
$result1 = $stmt1->get_result();
$row1 = $result1->fetch_assoc();
$total_from_ib_withdraw = floatval($row1['total_done'] ?? 0);
$stmt1->close();

// -------------------- From ib_withdraw_request --------------------
$stmt2 = $conn->prepare("SELECT COALESCE(SUM(total_commission), 0) AS total_done 
                         FROM ib_withdraw_request 
                         WHERE email = ? AND status = 1");
$stmt2->bind_param("s", $email);
$stmt2->execute();
$result2 = $stmt2->get_result();
$row2 = $result2->fetch_assoc();
$total_from_ib_withdraw_request = floatval($row2['total_done'] ?? 0);
$stmt2->close();

// -------------------- Final Total --------------------
$total_withdraw_done = $total_from_ib_withdraw + $total_from_ib_withdraw_request;

echo json_encode([
    "success" => true,
    "email" => $email,
    "total_withdraw_done" => round($total_withdraw_done, 4),
    "from_ib_withdraw" => round($total_from_ib_withdraw, 4),
    "from_ib_withdraw_request" => round($total_from_ib_withdraw_request, 4)
], JSON_PRETTY_PRINT);

$conn->close();
?>
