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

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('memory_limit', '512M');
set_time_limit(20);

include_once __DIR__ . "/mt5_api/mt5_api.php";
include_once __DIR__ . "/connection.php";
include_once __DIR__ . "/config.php";

// Fast input decode
$input = json_decode(file_get_contents("php://input"), true, 512, JSON_INVALID_UTF8_IGNORE);
$email = $input['email'] ?? null;

if (!$email) {
    echo json_encode(["success" => false, "message" => "Email is required"]);
    exit;
}

/* ============================================================
   🔍 FETCH ALL TRADE IDs (FAST DB QUERY)
============================================================ */
$stmt = $conn->prepare("SELECT trade_id FROM liveaccounts WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "No trading accounts found for this email"]);
    exit;
}

$trade_ids = [];
while ($row = $res->fetch_assoc()) {
    $trade_ids[] = (int)$row['trade_id'];
}

/* ============================================================
   🔥 INITIALIZE TOTALS
============================================================ */
$total_equity = 0;
$total_volume = 0;
$total_profit_loss = 0;
$total_positions = 0;
$all_positions = [];

/* ============================================================
   ⚡ CONNECT TO MT5 ONCE (NO RECONNECT LOOP)
============================================================ */
$api = new MTWebAPI("WebAPITesterLocal", "./logs", false);
$ret = $api->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" => "Failed to connect MT5",
        "error_code" => $ret
    ]);
    exit;
}

/* ============================================================
   ⚡ LOOP THROUGH TRADE IDs — OPTIMIZED
============================================================ */
foreach ($trade_ids as $trade_id) {

    // Fetch user
    $userMT5 = new MTUser();
    if ($api->UserGet($trade_id, $userMT5) !== MTRetCode::MT_RET_OK || empty($userMT5->Login)) {
        continue;
    }

    /* ------------------------------------------------------------
       🔥 Fetch Equity - FAST
    ------------------------------------------------------------ */
    $account = null;
    if ($api->UserAccountGet($userMT5->Login, $account) === MTRetCode::MT_RET_OK && $account) {
        $total_equity += (float)($account->Equity ?? $account->Balance ?? 0);
    }

    /* ------------------------------------------------------------
       🔥 Fetch Positions (High-Speed)
    ------------------------------------------------------------ */
    $posCount = 0;
    if ($api->PositionGetTotal($userMT5->Login, $posCount) !== MTRetCode::MT_RET_OK || $posCount <= 0) {
        continue;
    }

    $positions = [];
    if ($api->PositionGetPage($userMT5->Login, 0, $posCount, $positions) !== MTRetCode::MT_RET_OK) {
        continue;
    }

    foreach ($positions as $pos) {
        if (empty($pos->Volume)) continue;

        $volume = round($pos->Volume * 0.0001, 2);
        if ($volume <= 0) continue;

        $profit = (float)($pos->Profit ?? 0);

        // accumulate totals
        $total_volume += $volume;
        $total_profit_loss += $profit;
        $total_positions++;

        // collect all positions
        $all_positions[] = [
            "trade_id"     => $trade_id,
            "Symbol"       => $pos->Symbol ?? null,
            "PriceOpen"    => $pos->PriceOpen ?? null,
            "PriceCurrent" => $pos->PriceCurrent ?? null,
            "PriceSL"      => $pos->PriceSL ?? null,
            "PriceTP"      => $pos->PriceTP ?? null,
            "Volume"       => $volume,
            "Action"       => (($pos->Action ?? 0) == 1 ? "Sell" : "Buy"),
            "Profit"       => $profit,
            "Storage"      => $pos->Storage ?? null,
            "TimeCreate"   => isset($pos->TimeCreate) 
                                ? gmdate("Y-m-d H:i:s", $pos->TimeCreate) 
                                : null
        ];
    }
}

$api->Disconnect();

/* ============================================================
   🚀 FINAL OUTPUT (FAST JSON ENCODER)
============================================================ */
echo json_encode([
    "success" => true,
    "email" => $email,
    "total_accounts" => count($trade_ids),
    "total_positions" => $total_positions,
    "total_equity" => round($total_equity, 2),
    "total_volume" => round($total_volume, 2),
    "total_profit_loss" => round($total_profit_loss, 2),
    "positions" => $all_positions
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

exit;
?>
