<?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 = [];

while ($acc = $res_acc->fetch_assoc()) {
    $trade_id = intval($acc['trade_id']);
    $tradeIds[] = $trade_id;
    $clientsData[$trade_id] = $acc; 
}
$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;
}

// --- 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 using email AND trade_id ---
    $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 using email AND trade_id ---
    $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();

    // --- Account type ---
    $account_type_name = $acc['account_type'] ?? 'Unknown';
    if (empty($account_type_name)) {
        $stmt_type = $conn->prepare("SELECT ac_name FROM account_types WHERE ac_group = ?");
        $stmt_type->bind_param("s", $acc['account_type']);
        $stmt_type->execute();
        $res_type = $stmt_type->get_result();
        if ($typeRow = $res_type->fetch_assoc()) {
            $account_type_name = $typeRow['ac_name'] ?? 'Unknown';
        }
        $stmt_type->close();
    }

    // --- Fetch rebate ---
    $rebate = 0;
    $commission_value_raw = null;
    $commission_value_clean = 0;
    if ($tierLevel <= 10) {
        $stmt_comm = $conn->prepare("SELECT * FROM account_types WHERE ac_name = ?");
        $stmt_comm->bind_param("s", $account_type_name);
        $stmt_comm->execute();
        $res_comm = $stmt_comm->get_result();
        if ($comm_row = $res_comm->fetch_assoc()) {
            $commission_field = 'ib_commission' . $tierLevel;
            $commission_value_raw = $comm_row[$commission_field] ?? null;
            if (!empty($commission_value_raw)) {
                $commission_value_clean = floatval(preg_replace('/[^0-9.]/', '', $commission_value_raw));
                $rebate = $commission_value_clean * $volume;
            }
        }
        $stmt_comm->close();
    }

    // --- 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,
        "deposit" => round($totalDeposit, 2),
        "withdraw" => round($totalWithdraw, 2),
        "volume" => round($volume, 2),
        "rebate" => round($rebate, 2),
        "commission_field" => $commission_field ?? null,
        "commission_value_raw" => $commission_value_raw,
        "commission_value_clean" => $commission_value_clean,
        "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
];

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

echo json_encode($response, JSON_PRETTY_PRINT);
?>
