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

    // 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 = $acc['account_type'] ?? '';
    $account_group = '';
    $commission_field_type = '';
    $rank_commission = 0;

    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']; // mapped to valid type (basic, standard, etc.)
            $account_group = $typeRow['ac_group'];
            $isValidAccount = true;

            // build the commission column based on tier and account type
            $commission_type = strtolower($account_type_name); // must match column suffix
            $commission_field_type = "level_{$tierLevel}_{$commission_type}_commission";

            // fetch commission from ranks table
            $rank_commission = isset($rankData[$commission_field_type]) 
                                ? floatval($rankData[$commission_field_type]) 
                                : floatval($rankData["level_{$tierLevel}_basic_commission"] ?? 1);
        }
        $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);
?>
