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

$input = json_decode(file_get_contents("php://input"), true);
$email = trim($input['email'] ?? '');
if (!$email) {
    echo json_encode(["success" => false, "message" => "Email is required"]);
    exit;
}

// Connect MT5 API
$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(["success" => false, "message" => "MT5 connection failed"]);
    exit;
}

// Fetch IB users
$query = "SELECT * FROM loginusers WHERE ? IN (ib1,ib2,ib3,ib4,ib5,ib6,ib7,ib8,ib9,ib10,
                                               ib11,ib12,ib13,ib14,ib15,ib16,ib17,ib18,ib19,ib20)";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$ib_users = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

if (!$ib_users) {
    echo json_encode([
        "success" => true,
        "total_users" => 0,
        "total_liveaccounts" => 0,
        "total_equity" => 0,
        "total_commission" => 0,
        "total_volume" => 0,
        "users" => []
    ], JSON_PRETTY_PRINT);
    exit;
}

// Fetch all account types
$accountTypesResult = $conn->query("SELECT * FROM account_types");
$accountTypes = [];
while ($row = $accountTypesResult->fetch_assoc()) {
    $accountTypes[$row['ac_name']] = $row;
}

// Fetch all live accounts for these users
$user_ids = array_column($ib_users, 'id');
$user_ids_placeholder = implode(',', array_fill(0, count($user_ids), '?'));
$types = str_repeat('i', count($user_ids));

$liveQuery = "SELECT * FROM liveaccounts WHERE user_id IN ($user_ids_placeholder) AND status='active'";
$liveStmt = $conn->prepare($liveQuery);
$liveStmt->bind_param($types, ...$user_ids);
$liveStmt->execute();
$liveResult = $liveStmt->get_result();
$all_live_accounts = $liveResult->fetch_all(MYSQLI_ASSOC);
$liveStmt->close();

// Map live accounts by user
$live_accounts_by_user = [];
foreach ($all_live_accounts as $acct) {
    $live_accounts_by_user[$acct['user_id']][] = $acct;
}

$users = [];
$total_liveaccounts = 0;
$total_equity_all = 0;
$total_commission_all = 0;
$total_volume_all = 0;

foreach ($ib_users as $row) {
    $user_id = $row['id'];
    $liveAccounts = [];
    $user_total_equity = 0;
    $user_total_commission = 0;

    if (isset($live_accounts_by_user[$user_id])) {
        foreach ($live_accounts_by_user[$user_id] as $liveRow) {
            $trade_id = intval($liveRow['trade_id']);

            // --- 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;
                    }
                }
            }
            $volume = round($volume, 2);
            $total_volume_all += $volume;

            // Update liveaccounts 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 balance & equity
            $userMT5 = new MTUser();
            $mt5->UserGet($trade_id, $userMT5);
            $balance = floatval($userMT5->Balance ?? 0);
            $equity = floatval($userMT5->Equity ?? 0);

            $user_total_equity += $equity;
            $total_equity_all += $equity;

            // --- Calculate commission ---
            $rebate = 0;
            $ac_name = $liveRow['account_type']; // Match ac_name in account_types
            if (isset($accountTypes[$ac_name])) {
                $acctTypeRow = $accountTypes[$ac_name];
                // Determine IB level for this user
                for ($i = 1; $i <= 20; $i++) {
                    $ib_field = "ib$i";
                    if ($row[$ib_field] == $email) {
                        $commission_raw = $acctTypeRow["ib_commission$i"] ?? "0";
                        $commission_clean = floatval(preg_replace('/[^0-9.]/', '', $commission_raw));
                        $rebate = $volume * $commission_clean;
                        break;
                    }
                }
            }

            $user_total_commission += $rebate;
            $total_commission_all += $rebate;

            $liveAccounts[] = [
                "trade_id" => $trade_id,
                "server" => $liveRow['server'],
                "balance" => $balance,
                "equity" => $equity,
                "status" => $liveRow['status'],
                "account_type" => $ac_name,
                "leverage" => $liveRow['leverage'],
                "volume" => $volume,
                "commission" => $rebate
            ];
            $total_liveaccounts++;
        }
    }

    if (!empty($liveAccounts)) {
        $users[] = [
            "id" => $user_id,
            "first_name" => $row['first_name'],
            "last_name" => $row['last_name'],
            "email" => $row['email'],
            "total_equity" => round($user_total_equity, 2),
            "total_commission" => round($user_total_commission, 2),
            "liveaccounts" => $liveAccounts
        ];
    }
}

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

// Response
echo json_encode([
    "success" => true,
    "total_users" => count($users),
    "total_liveaccounts" => $total_liveaccounts,
    "total_equity" => round($total_equity_all, 2),
    "total_commission" => round($total_commission_all, 2),
    "total_volume" => round($total_volume_all, 2),
    "users" => $users
], JSON_PRETTY_PRINT);
?>
