<?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" => "IB email is required"]);
    exit;
}

// Fetch available commission
$stmt = $conn->prepare("SELECT total_commission, available_commission, updated_at FROM ib_total_commission WHERE ib_email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_assoc();
$stmt->close();

// Fetch total profit commission
$stmt_profit = $conn->prepare("SELECT total_profit_commission, available_profit_commission, updated_at FROM ib_total_profit_commission WHERE ib_email = ?");
$stmt_profit->bind_param("s", $email);
$stmt_profit->execute();
$result_profit = $stmt_profit->get_result();
$data_profit = $result_profit->fetch_assoc();
$stmt_profit->close();


// ✅ NEW LOGIC: Calculate total withdrawn profit commission
$total_profit_commission = floatval($data_profit['total_profit_commission'] ?? 0);
$available_profit_commission = floatval($data_profit['available_profit_commission'] ?? 0);
$total_withdraw_done = $total_profit_commission - $available_profit_commission;


// -------------------- Final Response --------------------
if ($data) {
    echo json_encode([
        "success" => true,
        "ib_email" => $email,
        "total_commission" => floatval($data['total_commission']),
        "available_commission" => floatval($data['available_commission']),
        "total_profit_commission" => $total_profit_commission,
        "available_profit_commission" => $available_profit_commission,
        "total_withdraw_done" => round($total_withdraw_done, 4),
        "last_updated" => $data['updated_at']
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode([
        "success" => false,
        "message" => "No commission record found for this IB"
    ]);
}

$conn->close();
?>
