<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

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

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

/* -------------------- BFS: collect all linked IB users -------------------- */
$allLinkedEmails = [];
$queue = [$email];

while (!empty($queue)) {
    $current = array_shift($queue);

    $ib_fields = [];
    for ($i = 1; $i <= 20; $i++) $ib_fields[] = "ib$i = ?";
    $ib_where = implode(" OR ", $ib_fields);

    $stmt = $conn->prepare("SELECT email FROM loginusers WHERE $ib_where");
    if (!$stmt) continue;

    $types = str_repeat("s", 20);
    $params = array_fill(0, 20, $current);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $childEmail = $row['email'];
        if (!in_array($childEmail, $allLinkedEmails, true)) {
            $allLinkedEmails[] = $childEmail;
            $queue[] = $childEmail;
        }
    }
}

/* -------------------- Fetch all live accounts for linked emails -------------------- */
$live_by_login = [];

$stmt = $conn->prepare("
    SELECT la.*, lu.first_name, lu.last_name 
    FROM liveaccounts la
    LEFT JOIN loginusers lu ON la.user_id = lu.id
    WHERE la.email = ?
");

foreach ($allLinkedEmails as $userEmail) {
    $stmt->bind_param("s", $userEmail);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        // Use trade_id if exists, otherwise fallback to unique key
        $loginKey = (string)($row['trade_id'] ?? '');
        if ($loginKey === '') {
            $loginKey = $row['email'] . '_' . $row['account_type'] . '_' . uniqid();
        }

        if (!isset($live_by_login[$loginKey])) {
            $live_by_login[$loginKey] = $row;
        }
    }
}

$total_live_accounts = count($live_by_login);

/* -------------------- Fetch deposit and withdraw from DB -------------------- */
$mt5_data = [];
$total_volume = 0.0;
$total_commission = 0.0;
$total_rebate = 0.0;
$total_rebate_paid = 0.0;
$total_rebate_unpaid = 0.0;
$total_deposits = 0.0;
$total_withdrawals = 0.0;

foreach ($live_by_login as $row) {
    $login = (string)($row["trade_id"] ?? '');
    $userEmail = $row["email"];
    $userFullName = trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
    $userFullName = $userFullName ?: ($row["account_name"] ?? '');

    // Fetch deposit total
    $stmtDeposit = $conn->prepare("SELECT SUM(deposit_amount) as totalDeposit FROM wallet_deposit WHERE email=? AND Status=1");
    $stmtDeposit->bind_param("s", $userEmail);
    $stmtDeposit->execute();
    $resDeposit = $stmtDeposit->get_result();
    $depositRow = $resDeposit->fetch_assoc();
    $account_deposit = (float)($depositRow['totalDeposit'] ?? 0);

    // Fetch withdraw total
    $stmtWithdraw = $conn->prepare("SELECT SUM(withdraw_amount) as totalWithdraw FROM wallet_withdraw WHERE email=? AND Status=1");
    $stmtWithdraw->bind_param("s", $userEmail);
    $stmtWithdraw->execute();
    $resWithdraw = $stmtWithdraw->get_result();
    $withdrawRow = $resWithdraw->fetch_assoc();
    $account_withdraw = (float)($withdrawRow['totalWithdraw'] ?? 0);

    $total_deposits += $account_deposit;
    $total_withdrawals += $account_withdraw;

    $mt5_data[] = [
        "login"        => $login,
        "name"         => $userFullName,
        "account_type" => $row["account_type"] ?? '',
        "email"        => $userEmail,
        "deposit"      => round($account_deposit, 2),
        "withdraw"     => round($account_withdraw, 2)
    ];
}

/* -------------------- Response -------------------- */
echo json_encode([
    "success" => true,
    "message" => "All linked IB accounts fetched successfully",
    "data" => [
        "email"               => $email,
        "all_linked_emails"   => array_values($allLinkedEmails),
        "total_live_accounts" => $total_live_accounts,
        "total_deposits"      => round($total_deposits, 2),
        "total_withdrawals"   => round($total_withdrawals, 2),
        "total_volume"        => round($total_volume, 4),
        "total_commission"    => round($total_commission, 2),
        "total_rebate"        => round($total_rebate, 2),
        "total_rebate_paid"   => round($total_rebate_paid, 2),
        "total_rebate_unpaid" => round($total_rebate_unpaid, 2),
        "mt5_accounts"        => array_values($mt5_data)
    ]
]);
exit;
?>
