<?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__ . "/mt5_api/mt5_api.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; }

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

$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 = ? AND la.account_type = 'PAMM'");
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; }
    }
}

$mt5_data = [];
$total_volume = 0.0;
$total_pamm_ib_commission = 0.0;
$total_deposits = 0.0;
$total_withdrawals = 0.0;

// Use the connection helper from connection.php
$mt5conn = new MT5Connection();
if (!$mt5conn->connect()) {
    // Debug: include last error code for MT5 if needed
    $lastErr = $mt5conn->lastError();
    echo json_encode(["success" => false, "message" => "MT5 connection failed", "mt5_error" => $lastErr]);
    exit;
}
$mt5 = $mt5conn->api; // now use $mt5 for subsequent calls


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();
    $account_deposit = floatval(($stmtDeposit->get_result()->fetch_assoc()['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();
    $account_withdraw = floatval(($stmtWithdraw->get_result()->fetch_assoc()['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); }

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

    $pamm_ib_commission = 0.0;
    if ($tierLevel > 0) {
        $stmtPamm = $conn->prepare("SELECT IFNULL(SUM(amount),0) AS totalCommission FROM pamm_profit_distribution WHERE entity_type='ib' AND level = ? AND email = ? AND trade_id = ?");
        $stmtPamm->bind_param("isi", $tierLevel, $email, $trade_id);
        $stmtPamm->execute();
        $pamm_ib_commission = floatval(($stmtPamm->get_result()->fetch_assoc()['totalCommission'] ?? 0));
        $stmtPamm->close();
    }

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

    $total_volume += $volume;
    $total_pamm_ib_commission += $pamm_ib_commission;
}

$mt5->Disconnect();

echo json_encode([
    "success" => true,
    "message" => "PAMM IB dashboard fetched successfully",
    "data" => [
        "email" => $email,
        "total_live_accounts" => count($live_by_login),
        "total_deposits" => round($total_deposits, 2),
        "total_withdrawals" => round($total_withdrawals, 2),
        "total_volume" => round($total_volume, 4),
        "total_pamm_ib_commission" => round($total_pamm_ib_commission, 8),
        "mt5_accounts" => array_values($mt5_data)
    ]
]);
?>
