<?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 total commission
$stmt = $conn->prepare("SELECT SUM(commission) AS total_commission FROM ib_accounts WHERE ib_email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$total_commission = floatval($row['total_commission'] ?? 0);
$stmt->close();

echo json_encode([
    "success" => true,
    "ib_email" => $email,
    "total_commission" => round($total_commission, 2)
], JSON_PRETTY_PRINT);
?>
