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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

if (empty($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;

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

// --- Fetch all clients under this IB tier ---
$stmt_acc = $conn->prepare("SELECT * FROM liveaccounts WHERE $ibColumn = ?");
$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; // track unique emails
}
$stmt_acc->close();

if (empty($tradeIds)) {
    echo json_encode([
        "status" => "error",
        "message" => "No clients found for this email in this level.",
        "data" => [],
        "totals" => $totals
    ]);
    exit;
}

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

// --- Determine Rank based on number of unique emails (clients) ---
$totalActiveClients = count($uniqueEmails);
$rankNumber = 1;
$rankName = "Rank 1";

$stmt_rank = $conn->prepare("SELECT * FROM ranks WHERE min_active_clients <= ? ORDER BY rank_number DESC LIMIT 1");
$stmt_rank->bind_param("i", $totalActiveClients);
$stmt_rank->execute();
$res_rank = $stmt_rank->get_result();
$rankData = [];
if ($row_rank = $res_rank->fetch_assoc()) {
    $rankNumber = intval($row_rank['rank_number']);
    $rankName = $row_rank['rank_name'];
    $rankData = $row_rank; // contains all level commissions
}
$stmt_rank->close();

// --- Process each client ---
$clients = [];
foreach ($tradeIds as $trade_id) {
    $acc = $clientsData[$trade_id];
    $email = $acc['email'];

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

    // // --- 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;
    //         }
    //     }
    // }
    
//     // --- Fetch volume from MT5 with paging ---
// $volume = 0;
// $from = 0;
// $to = 0;

// $totalDeals = 0;
// $ret_total = $mt5->DealGetTotal($trade_id, $from, $to, $totalDeals);

// if ($ret_total == MTRetCode::MT_RET_OK && $totalDeals > 0) {

//     $pageSize = 500;
//     $offset = 0;

//     while ($offset < $totalDeals) {
//         $deals = [];
//         $ret_page = $mt5->DealGetPage($trade_id, $from, $to, $offset, $pageSize, $deals);

//         if ($ret_page != MTRetCode::MT_RET_OK || empty($deals)) break;

//         foreach ($deals as $deal) {
//             if (isset($deal->VolumeClosed) && $deal->VolumeClosed > 0) {
//                 $volume += $deal->VolumeClosed * 0.0001;
//             }
//         }

//         $offset += count($deals);
//     }
// }

// $volume = round($volume, 2);
// --- Fetch saved volume from DB (fast) ---
$stmtVol = $conn->prepare("SELECT total_volume FROM ib_volume WHERE trade_id = ? LIMIT 1");
$stmtVol->bind_param("i", $trade_id);
$stmtVol->execute();
$resVol = $stmtVol->get_result();
$volumeRow = $resVol->fetch_assoc();
$volume = floatval($volumeRow['total_volume'] ?? 0);
$stmtVol->close();


    // // Optional: Update liveaccounts table with latest volume
    // $update_stmt = $conn->prepare("UPDATE liveaccounts SET volume=? WHERE trade_id=?");
    // $update_stmt->bind_param("di", $volume, $trade_id);
    // $update_stmt->execute();
    // $update_stmt->close();

    // --- Fetch deposits ---
    $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();
    $resDep = $stmtDep->get_result();
    $totalDeposit = floatval($resDep->fetch_assoc()['totalDeposit'] ?? 0);
    $stmtDep->close();

    // --- Fetch withdrawals ---
    $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();
    $resWith = $stmtWith->get_result();
    $totalWithdraw = floatval($resWith->fetch_assoc()['totalWithdraw'] ?? 0);
    $stmtWith->close();

    // --- Validate account type against account_types table and determine commission ---
$isValidAccount = false;
$account_type_name = trim($acc['account_type'] ?? '');
$account_group = '';
$commission_field_type = "ib_commission{$tierLevel}";
$rank_commission = 0;

if (!empty($account_type_name)) {

    $account_type_clean = strtolower(trim($account_type_name));

    // SELECT * so commission columns are included!
    $stmt_type = $conn->prepare("
        SELECT * 
        FROM account_types 
        WHERE LOWER(TRIM(ac_name)) = ?
    ");
    $stmt_type->bind_param("s", $account_type_clean);
    $stmt_type->execute();
    $res_type = $stmt_type->get_result();

    if ($typeRow = $res_type->fetch_assoc()) {
        $isValidAccount = true;
        $account_type_name = $typeRow['ac_name'];
        $account_group = $typeRow['ac_group'];

        // Get tier-based commission correctly
        $rank_commission = floatval($typeRow[$commission_field_type] ?? 0);
    }

    $stmt_type->close();
}


    // --- Calculate rebate ---
    $rebate = 0;
    if ($isValidAccount && $volume > 0) {
        $rebate = $volume * $rank_commission;
    }

    // --- Fetch user name ---
    $name = '';
    $reg_date = $acc['Registered_Date'];
    $status = $acc['status'] ?? 'inactive';
    $stmt_user = $conn->prepare("SELECT first_name, last_name, reg_date, status FROM loginusers WHERE email = ?");
    $stmt_user->bind_param("s", $email);
    $stmt_user->execute();
    $res_user = $stmt_user->get_result();
    if ($userRow = $res_user->fetch_assoc()) {
        $name = trim(($userRow['first_name'] ?? '') . ' ' . ($userRow['last_name'] ?? ''));
        $reg_date = $userRow['reg_date'] ?? $reg_date;
        $status = isset($userRow['status']) ? ($userRow['status'] == 1 ? 'active' : 'inactive') : $status;
    }
    $stmt_user->close();

    $clients[] = [
        "trade_id" => $trade_id,
        "name" => $name,
        "email" => $email,
        "balance" => round($balance, 2),
        "account_type" => $account_type_name,
        "account_group" => $account_group,
        "deposit" => round($totalDeposit, 2),
        "withdraw" => round($totalWithdraw, 2),
        "volume" => round($volume, 2),
        "rebate" => round($rebate, 2),
        "rank_commission" => $rank_commission,
        "commission_field" => $commission_field_type,
        "reg_date" => $reg_date,
        "status" => $status
    ];

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

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

$response = [
    "status" => count($clients) > 0 ? "success" : "error",
    "data" => $clients,
    "totals" => $totals,
    "rank" => [
        "rank_number" => $rankNumber,
        "rank_name" => $rankName,
        "active_clients" => $totalActiveClients
    ]
];

if (count($clients) == 0) {
    $response["message"] = "No clients found for this email in this level.";
}

echo json_encode($response, JSON_PRETTY_PRINT);
?>
