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

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

include_once __DIR__ . "/config.php";

// Read JSON
$data = json_decode(file_get_contents("php://input"), true);

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

$ib_email = $data['email'];

// STEP 1: Validate IB email exists
$ibQuery = $conn->prepare("SELECT id FROM loginusers WHERE email = ?");
$ibQuery->bind_param("s", $ib_email);
$ibQuery->execute();
$ibResult = $ibQuery->get_result();

if ($ibResult->num_rows === 0) {
    echo json_encode(["status" => false, "message" => "Invalid IB email"]);
    exit;
}

// STEP 2: Fetch all trade accounts under this IB (check ALL ib1–ib20 columns)
$tradeSql = $conn->prepare("
    SELECT trade_id, 
        ib1, ib2, ib3, ib4, ib5,
        ib6, ib7, ib8, ib9, ib10,
        ib11, ib12, ib13, ib14, ib15,
        ib16, ib17, ib18, ib19, ib20
    FROM liveaccounts
    WHERE 
        ib1 = ? OR ib2 = ? OR ib3 = ? OR ib4 = ? OR ib5 = ? OR
        ib6 = ? OR ib7 = ? OR ib8 = ? OR ib9 = ? OR ib10 = ? OR
        ib11 = ? OR ib12 = ? OR ib13 = ? OR ib14 = ? OR ib15 = ? OR
        ib16 = ? OR ib17 = ? OR ib18 = ? OR ib19 = ? OR ib20 = ?
");

$tradeSql->bind_param(
    "ssssssssssssssssssss",
    $ib_email, $ib_email, $ib_email, $ib_email, $ib_email,
    $ib_email, $ib_email, $ib_email, $ib_email, $ib_email,
    $ib_email, $ib_email, $ib_email, $ib_email, $ib_email,
    $ib_email, $ib_email, $ib_email, $ib_email, $ib_email
);

$tradeSql->execute();
$tradeResult = $tradeSql->get_result();

$tradeInfo = []; // key = trade_id, value = level
$tradeIds = [];

while ($row = $tradeResult->fetch_assoc()) {

    $tradeId = $row['trade_id'];
    $tradeIds[] = $tradeId;

    // detect IB level
    $level = null;
    for ($i = 1; $i <= 20; $i++) {
        $col = "ib" . $i;
        if ($row[$col] === $ib_email) {
            $level = $i; // found exact level
            break;
        }
    }
    $tradeInfo[$tradeId] = $level;
}

if (empty($tradeIds)) {
    echo json_encode([
        "status" => true,
        "message" => "No IB accounts found",
        "deposits" => [],
        "withdrawals" => []
    ]);
    exit;
}

$tradeIdsComma = "'" . implode("','", $tradeIds) . "'";

// ==========================================================
// FETCH ONLY wallet_deposit
// ==========================================================
$depositQuery = "
    SELECT 
        trade_id,
        deposit_amount AS amount,
        deposit_type AS type,
        Status AS status,
        deposed_date AS created_at
    FROM wallet_deposit
    WHERE trade_id IN ($tradeIdsComma)
";

$depositResult = $conn->query($depositQuery);

$deposits = [];
$totalDeposit = 0;

while ($row = $depositResult->fetch_assoc()) {
    $tradeId = $row['trade_id'];
    $row['level'] = $tradeInfo[$tradeId];  // add IB level

    $totalDeposit += floatval($row['amount']);

    $deposits[] = $row;
}

// ==========================================================
// FETCH ONLY wallet_withdraw
// ==========================================================
$withdrawQuery = "
    SELECT 
        trade_id,
        withdraw_amount AS amount,
        withdraw_type AS type,
        Status AS status,
        withdraw_date AS created_at
    FROM wallet_withdraw
    WHERE trade_id IN ($tradeIdsComma)
";

$withdrawResult = $conn->query($withdrawQuery);

$withdrawals = [];
$totalWithdraw = 0;

while ($row = $withdrawResult->fetch_assoc()) {
    $tradeId = $row['trade_id'];
    $row['level'] = $tradeInfo[$tradeId];  // add IB level

    $totalWithdraw += floatval($row['amount']);

    $withdrawals[] = $row;
}

// ==========================================================
// FINAL OUTPUT
// ==========================================================
echo json_encode([
    "status" => true,
    "ib_email" => $ib_email,
    "total_ib_accounts" => count($tradeIds),
    "trade_ids" => $tradeIds,
    "total_deposit" => $totalDeposit,
    "total_withdraw" => $totalWithdraw,
    "deposits" => $deposits,
    "withdrawals" => $withdrawals
]);

?>
