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

// --- Increase execution time & memory like tiers API ---
ini_set('max_execution_time', 600); // 10 minutes
ini_set('memory_limit', '1G');  

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

include_once __DIR__ . '/config.php';
include_once __DIR__ . '/connection.php';
include_once __DIR__ . '/mt5_api/mt5_api.php'; // MT5 API

$conn->query("SET SESSION wait_timeout=28800"); 
$conn->query("SET SESSION interactive_timeout=28800");

$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()) {
        $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);

/* -------------------- Initialize totals -------------------- */
$mt5_data = [];
$total_volume = 0.0;
$total_rebate = 0.0;
$total_deposits = 0.0;
$total_withdrawals = 0.0;

/* -------------------- Connect MT5 -------------------- */
$mt5 = new MTWebAPI("WebAPITesterLocal", "./logs", true);
$ret = $mt5->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
if ($ret != MTRetCode::MT_RET_OK) {
    echo json_encode(["success" => false, "message" => "MT5 connection failed"]);
    exit;
}

/* -------------------- Process each live account -------------------- */
foreach ($live_by_login as $row) {
    $login = (string)($row["trade_id"] ?? '');
    $userEmail = $row["email"];
    $trade_id = intval($row['trade_id'] ?? 0);
    $userFullName = trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
    $userFullName = $userFullName ?: ($row["account_name"] ?? '');
    $account_type_name = $row['account_type'] ?? 'Unknown';

    $tierLevel = 0;
    for ($i = 1; $i <= 20; $i++) {
        if (($row["ib$i"] ?? '') === $email) {
            $tierLevel = $i;
            break;
        }
    }

    $stmtDeposit = $conn->prepare("SELECT SUM(deposit_amount) as totalDeposit FROM wallet_deposit WHERE email=? AND trade_id=? AND Status=1");
    $stmtDeposit->bind_param("si", $userEmail, $trade_id);
    $stmtDeposit->execute();
    $depositRow = $stmtDeposit->get_result()->fetch_assoc();
    $account_deposit = floatval($depositRow['totalDeposit'] ?? 0);
    $stmtDeposit->close();

    $stmtWithdraw = $conn->prepare("SELECT SUM(withdraw_amount) as totalWithdraw FROM wallet_withdraw WHERE email=? AND trade_id=? AND Status=1");
    $stmtWithdraw->bind_param("si", $userEmail, $trade_id);
    $stmtWithdraw->execute();
    $withdrawRow = $stmtWithdraw->get_result()->fetch_assoc();
    $account_withdraw = floatval($withdrawRow['totalWithdraw'] ?? 0);
    $stmtWithdraw->close();

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

    $balance = 0;
    $account_info = null;
    if ($mt5->UserAccountGet($trade_id, $account_info) == MTRetCode::MT_RET_OK) {
        $balance = floatval($account_info->Balance ?? 0);
    }

    /* -------------------- Fixed Volume Calculation -------------------- */
    $stmtVol = $conn->prepare("SELECT last_deal_id, total_volume FROM ib_volume WHERE trade_id=?");
    $stmtVol->bind_param("i", $trade_id);
    $stmtVol->execute();
    $volRow = $stmtVol->get_result()->fetch_assoc();
    $stmtVol->close();

    $lastStoredDeal = intval($volRow['last_deal_id'] ?? 0);
    $storedVolume   = floatval($volRow['total_volume'] ?? 0);

    $totalDeals = 0;
    $mt5->DealGetTotal($trade_id, 0, 0, $totalDeals);

    if ($lastStoredDeal >= $totalDeals && $storedVolume > 0) {
        $volume = round($storedVolume, 4);
    } else {
        $volumeIncrement = 0;
        $maxDealId = $lastStoredDeal;
        $pageSize = 500;
        $offset = 0;

        while ($offset < $totalDeals) {
            $deals = [];
            $ret_page = $mt5->DealGetPage($trade_id, 0, 0, $offset, $pageSize, $deals);
            if ($ret_page != MTRetCode::MT_RET_OK || empty($deals)) break;

            foreach ($deals as $deal) {
                if ($deal->Deal <= $lastStoredDeal) continue;

                // Only BUY/SELL trades
                if (!in_array($deal->Action, [0,1])) continue;

                // Skip non-trade deals: balance(2), credit(3), commission(4), swap(5)
                if (in_array($deal->Entry, [2,3,4,5])) continue;

                // Accurate lot volume
                $lotVolume = floatval($deal->VolumeExt) / 10000; 
                $volumeIncrement += $lotVolume;

                if ($deal->Deal > $maxDealId) $maxDealId = $deal->Deal;
            }

            $offset += count($deals);
        }

        $newTotalVolume = $storedVolume + $volumeIncrement;

        // Divide total volume by 10000 before storing
// $storedVolumeToDb = $newTotalVolume / 10000;

// First divide by 10000 for all accounts
$storedVolumeToDb = $newTotalVolume / 10000;

// If Cent account, further divide by 100
if ($account_type_name === "Cent") {
    $storedVolumeToDb = $storedVolumeToDb / 100;
}

if ($volRow) {
    $stmtUpdate = $conn->prepare("UPDATE ib_volume SET last_deal_id=?, total_volume=? WHERE trade_id=?");
    $stmtUpdate->bind_param("idi", $maxDealId, $storedVolumeToDb, $trade_id);
    $stmtUpdate->execute();
    $stmtUpdate->close();
} else {
    $stmtInsert = $conn->prepare("INSERT INTO ib_volume (trade_id, last_deal_id, total_volume) VALUES (?, ?, ?)");
    $stmtInsert->bind_param("iid", $trade_id, $maxDealId, $storedVolumeToDb);
    $stmtInsert->execute();
    $stmtInsert->close();
}


        // $volume = round($newTotalVolume, 4);
        
           $volume = round($storedVolumeToDb, 4);

    }

    /* -------------------- Calculate rebate like tiers code -------------------- */
    $rebate = 0;
    $rank_commission = 0;
    $isValidAccount = false;
    $account_group = '';
    if (!empty($account_type_name)) {
        $stmt_type = $conn->prepare("SELECT ac_name, ac_group FROM account_types WHERE ac_name = ?");
        $stmt_type->bind_param("s", $account_type_name);
        $stmt_type->execute();
        $res_type = $stmt_type->get_result();
        if ($typeRow = $res_type->fetch_assoc()) {
            $account_type_name = $typeRow['ac_name'];
            $account_group = $typeRow['ac_group'];
            $isValidAccount = true;
        }
        $stmt_type->close();
    }

    $tierClients = [];
    $stmt_tier = $conn->prepare("SELECT email FROM liveaccounts WHERE ib$tierLevel = ?");
    $stmt_tier->bind_param("s", $email);
    $stmt_tier->execute();
    $res_tier = $stmt_tier->get_result();
    while ($r = $res_tier->fetch_assoc()) $tierClients[] = $r['email'];
    $stmt_tier->close();

    $activeClientsForTier = count(array_unique($tierClients));
    //using ranks table
    $rankNumberTier = 1;
    $rankDataTier = [];
    $stmt_rank = $conn->prepare("SELECT * FROM ranks WHERE min_active_clients <= ? ORDER BY rank_number DESC LIMIT 1");
    $stmt_rank->bind_param("i", $activeClientsForTier);
    $stmt_rank->execute();
    $res_rank = $stmt_rank->get_result();
    if ($row_rank = $res_rank->fetch_assoc()) {
        $rankNumberTier = intval($row_rank['rank_number']);
        $rankDataTier = $row_rank;
    }
    $stmt_rank->close();

    if ($isValidAccount && $volume > 0) {
        $commission_type = strtolower($account_type_name);
        $commission_field_type = "level_{$tierLevel}_{$commission_type}_commission";
        $rank_commission = isset($rankDataTier[$commission_field_type])
            ? floatval($rankDataTier[$commission_field_type])
            : floatval($rankDataTier["level_{$tierLevel}_basic_commission"] ?? 0);

        $rebate = $volume * $rank_commission;
    }
    
    

    $mt5_data[] = [
        "login"        => $login,
        "name"         => $userFullName,
        "account_type" => $account_type_name,
        "account_group"=> $account_group,
        "email"        => $userEmail,
        "tier"         => $tierLevel,
        "balance"      => round($balance, 2),
        "deposit"      => round($account_deposit, 2),
        "withdraw"     => round($account_withdraw, 2),
        "volume"       => round($volume, 4),
        "rebate"       => round($rebate, 2),
        "rank_commission" => $rank_commission
    ];

    $total_volume += $volume;
    $total_rebate += $rebate;
}

$mt5->Disconnect();

$rankNumber = $rankNumber ?? 1;
$rankName = $rankName ?? "Rank 1";
$totalActiveClients = $totalActiveClients ?? count($allLinkedEmails);

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_rebate"        => round($total_rebate, 2),
        "rank"                => [
            "rank_number" => $rankNumber,
            "rank_name" => $rankName,
            "active_clients" => $totalActiveClients
        ],
        "mt5_accounts"        => array_values($mt5_data)
    ]
], JSON_PRETTY_PRINT);

exit;
?>
