<?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";
include_once __DIR__ . "/mt5_api/mt5_api.php"; // MT5 API

$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;
}

/* -------------------- FETCH IB COMMISSION SUMMARY -------------------- */
// $stmtCom = $conn->prepare("SELECT total_profit_commission, available_profit_commission FROM ib_total_profit_commission WHERE ib_email = ?");

$stmtCom = $conn->prepare("SELECT total_commission, available_commission FROM ib_total_commission WHERE ib_email = ?");

if ($stmtCom) {
    $stmtCom->bind_param("s", $email);
    $stmtCom->execute();
    $resCom = $stmtCom->get_result();
    $commissionData = $resCom->fetch_assoc();
    $stmtCom->close();
} else {
    // If prepare failed, set defaults
    $commissionData = null;
}

// $total_profit_commission = 0.0;
// $available_profit_commission = 0.0;
$total_commission = 0.0;
$available_commission = 0.0;

// if ($commissionData) {
//     $total_profit_commission = floatval($commissionData['total_profit_commission'] ?? 0);
//     $available_profit_commission = floatval($commissionData['available_profit_commission'] ?? 0);
// }
if ($commissionData) {
    $total_commission = floatval($commissionData['total_commission'] ?? 0);
    $available_commission = floatval($commissionData['available_commission'] ?? 0);
}


/* -------------------- 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;
        }
    }

    $stmt->close();
}

/* -------------------- 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;
        }
    }
}

if ($stmt) $stmt->close();

$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;
$total_commission = 0.0;
$total_balance = 0.0; // <-- Add this new line



/* -------------------- 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';

    // --- Determine tier/level for this account ---
    $tierLevel = 0;
    for ($i = 1; $i <= 20; $i++) {
        if (($row["ib$i"] ?? '') === $email) {
            $tierLevel = $i;
            break;
        }
    }

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

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

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

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


    // --- Fetch volume from MT5 ---
    $volume = 0;
    $totalDeals = 0;
    $ret_total = $mt5->DealGetTotal($trade_id, 0, 0, $totalDeals);
    if ($ret_total == MTRetCode::MT_RET_OK && $totalDeals > 0) {
        $deals = [];
        $ret_page = $mt5->DealGetPage($trade_id, 0, 0, 0, $totalDeals, $deals);
        if ($ret_page == MTRetCode::MT_RET_OK) {
            foreach ($deals as $deal) {
                $volume += isset($deal->VolumeClosed) ? $deal->VolumeClosed * 0.0001 : 0;
            }
        }
    }
    
        // --- PROFIT COMMISSION: compute closed-trades sumProfit and IB commission for this tier ---
    $sumProfit = 0.0;

    // If $deals is available from the volume fetch, reuse it to sum profits; otherwise fetch deals again
    if (isset($deals) && is_array($deals) && count($deals) > 0) {
        foreach ($deals as $d) {
            $order_id = $d->Order ?? 0;
            $vol_closed = floatval($d->VolumeClosed ?? 0) * 0.0001;
            if ($order_id != 0 && $vol_closed > 0) {
                $sumProfit += floatval($d->Profit ?? 0);
            }
        }
    } else {
        // fallback: fetch deals specifically for profit calculation
        $totalDealsProfit = 0;
        $ret_total_profit = $mt5->DealGetTotal($trade_id, 0, 0, $totalDealsProfit);
        if ($ret_total_profit == MTRetCode::MT_RET_OK && $totalDealsProfit > 0) {
            $dealsProfit = [];
            $ret_page_profit = $mt5->DealGetPage($trade_id, 0, 0, 0, $totalDealsProfit, $dealsProfit);
            if ($ret_page_profit == MTRetCode::MT_RET_OK && is_array($dealsProfit)) {
                foreach ($dealsProfit as $dp) {
                    $order_id = $dp->Order ?? 0;
                    $vol_closed = floatval($dp->VolumeClosed ?? 0) * 0.0001;
                    if ($order_id != 0 && $vol_closed > 0) {
                        $sumProfit += floatval($dp->Profit ?? 0);
                    }
                }
            }
        }
    }

    // default profit_commission per-account
    $profit_commission = 0.0;

    // Grab IB commission percentage for this tier from account_types table (field: ib_commission{tier})
    if (!empty($account_type_name)) {
        $stmt_type_pc = $conn->prepare("SELECT * FROM account_types WHERE ac_name = ?");
        if ($stmt_type_pc) {
            $stmt_type_pc->bind_param("s", $account_type_name);
            $stmt_type_pc->execute();
            $res_type_pc = $stmt_type_pc->get_result();
            if ($typeRowPC = $res_type_pc->fetch_assoc()) {
                $ib_comm_field = "ib_commission" . $tierLevel;
                $ib_percent = isset($typeRowPC[$ib_comm_field]) ? floatval($typeRowPC[$ib_comm_field]) : 0;
                if ($ib_percent > 0 && $sumProfit > 0) {
                    $profit_commission = ($sumProfit * $ib_percent) / 100.0;
                }
            }
            $stmt_type_pc->close();
        }
    }

    // accumulate optional global total
    $total_commission += $profit_commission;


    /* -------------------- Calculate rebate like tiers code -------------------- */
    $rebate = 0;
    $rank_commission = 0;

    // Determine valid account type from account_types table
    $isValidAccount = false;
    $account_group = '';
    if (!empty($account_type_name)) {
        $stmt_type = $conn->prepare("SELECT ac_name, ac_group FROM account_types WHERE ac_name = ?");
        if ($stmt_type) {
            $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();
        }
    }

    // --- Tier-specific rank calculation ---
    $tierClients = [];
    $stmt_tier = $conn->prepare("SELECT email FROM liveaccounts WHERE ib$tierLevel = ?");
    if ($stmt_tier) {
        $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));

    $rankNumberTier = 1;
    $rankDataTier = [];
    $stmt_rank = $conn->prepare("SELECT * FROM ranks WHERE min_active_clients <= ? ORDER BY rank_number DESC LIMIT 1");
    if ($stmt_rank) {
        $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();
    }

    // --- Get commission for this tier ---
    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;
    }

    // --- Collect account data ---
    $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,
         "profit_commission" => round($profit_commission, 2)
    ];

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

/* -------------------- Disconnect MT5 -------------------- */
$mt5->Disconnect();

/* -------------------- Ensure default rank variables to remove warnings -------------------- */
$rankNumber = $rankNumber ?? 1;
$rankName = $rankName ?? "Rank 1";
$totalActiveClients = $totalActiveClients ?? count($allLinkedEmails);

/* -------------------- 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_balance" => round($total_balance, 2),
        "total_volume"        => round($total_volume, 4),
        "total_rebate"        => round($total_rebate, 2),
        "total_commission" => round($total_commission, 4),
        "available_commission" => round($available_commission, 4),
        "rank"                => [
            "rank_number" => $rankNumber,
            "rank_name" => $rankName,
            "active_clients" => $totalActiveClients
        ],
        "mt5_accounts"        => array_values($mt5_data),
    ]
], JSON_PRETTY_PRINT);

exit;
?>
