<?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");

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

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

// Get input JSON
$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 commission info from ib_total_commission
$stmt = $conn->prepare("
    SELECT 
        COALESCE(total_commission, 0) AS total_commission,
        COALESCE(available_commission, 0) AS available_commission,
        COALESCE(updated_at, '') AS 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();

if ($data) {
    // Calculate total withdrawn
    $total_commission = floatval($data['total_commission']);
    $available_commission = floatval($data['available_commission']);
    $total_withdraw_done = $total_commission - $available_commission;

    // Send JSON response
    echo json_encode([
        "success" => true,
        "ib_email" => $email,
        "total_commission" => $total_commission,
        "available_commission" => $available_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();
?>
