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

$input = json_decode(file_get_contents("php://input"), true);
$emailInput = trim($input['email'] ?? '');
$tierLevel = isset($input['level']) ? intval($input['level']) : 1;

if ($emailInput === '') { echo json_encode(["status"=>"error","message"=>"Email is required"]); exit; }
if ($tierLevel < 1 || $tierLevel > 20) { echo json_encode(["status"=>"error","message"=>"Level must be between 1 and 20"]); exit; }

$ibColumn = "ib" . $tierLevel;

$stmt_acc = $conn->prepare("SELECT * FROM liveaccounts WHERE $ibColumn = ? AND account_type = 'PAMM'");
$stmt_acc->bind_param("s", $emailInput);
$stmt_acc->execute();
$res_acc = $stmt_acc->get_result();

$tradeIds = [];
$clientsData = [];
$uniqueEmails = [];

while ($acc = $res_acc->fetch_assoc()) {
    $trade_id = intval($acc['trade_id']);
    $tradeIds[] = $trade_id;
    $clientsData[$trade_id] = $acc;
    $uniqueEmails[$acc['email']] = true;
}
$stmt_acc->close();

if (empty($tradeIds)) {
    echo json_encode(["status"=>"error","message"=>"No PAMM clients found","data"=>[],"totals"=>[]]);
    exit;
}

$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(["status"=>"error","message"=>"MT5 connection failed"]); exit; }

$clients = [];
$totals = [
    "total_balance"=>0,
    "total_deposit"=>0,
    "total_withdraw"=>0,
    "total_volume"=>0,
    "total_pamm_ib_commission"=>0,
    "total_clients"=>0
];

foreach ($tradeIds as $trade_id) {
    $acc = $clientsData[$trade_id];
    $email = $acc['email'];

    $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;
    $deals = [];
    $ret_total = $mt5->DealGetTotal($trade_id, 0, 0, $totalDeals);
    if ($ret_total == MTRetCode::MT_RET_OK && $totalDeals > 0) {
        $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; }
        }
    }

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

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

    $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, $emailInput, $trade_id);
    $stmtPamm->execute();
    $totalCommission = floatval(($stmtPamm->get_result()->fetch_assoc()['totalCommission'] ?? 0));
    $stmtPamm->close();

    $clients[] = [
        "trade_id" => $trade_id,
        "email" => $email,
        "account_type" => $acc['account_type'],
        "balance" => round($balance, 2),
        "deposit" => round($totalDeposit, 2),
        "withdraw" => round($totalWithdraw, 2),
        "volume" => round($volume, 2),
        "pamm_ib_commission" => round($totalCommission, 8)
    ];

    $totals["total_balance"] += $balance;
    $totals["total_deposit"] += $totalDeposit;
    $totals["total_withdraw"] += $totalWithdraw;
    $totals["total_volume"] += $volume;
    $totals["total_pamm_ib_commission"] += $totalCommission;
    $totals["total_clients"]++;
}

$mt5->Disconnect();

echo json_encode(["status"=>"success","data"=>$clients,"totals"=>$totals]);
?>
