<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

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

try {
    $mt5 = new MTWebAPI();
    $code = $mt5->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, MT5_TIMEOUT, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);

    if ($code !== MTRetCode::MT_RET_OK) {
        throw new Exception("MT5 connection failed: $code");
    }

    // Fetch accounts with trade IDs
    $trade_ids = [];
    $qry = $conn->query("SELECT trade_id FROM liveaccounts WHERE trade_id IS NOT NULL AND trade_id!=''");
    while ($row = $qry->fetch_assoc()) {
        $trade_ids[] = (int)$row['trade_id'];
    }

    if (empty($trade_ids)) {
        echo json_encode([
            "success" => true,
            "count" => 0,
            "total_lots" => 0,
            "total_profit" => 0
        ]);
        exit;
    }

    $total_count = 0;
    $total_lots = 0.0;
    $total_profit = 0.0;

    foreach ($trade_ids as $login) {

        $total_closed = 0;
        $ret = $mt5->DealGetTotal($login, 0, 0, $total_closed);

        if ($ret == MTRetCode::MT_RET_OK && $total_closed > 0) {

            // For speed → Limit max closed trades per user
            $limit = min($total_closed, 200);

            $deals = [];
            $ret = $mt5->DealGetPage($login, 0, 0, 0, $limit, $deals);

            if ($ret == MTRetCode::MT_RET_OK && is_array($deals)) {
                foreach ($deals as $deal) {

                    if (empty($deal->VolumeClosed) || empty($deal->Order)) continue;

                    $lots = round(($deal->VolumeClosed ?? 0) * 0.0001, 2);
                    $profit = round($deal->Profit ?? 0, 2);

                    $total_count++;
                    $total_lots += $lots;
                    $total_profit += $profit;
                }
            }
        }
    }

    $mt5->Disconnect();

    echo json_encode([
        "success" => true,
        "count" => $total_count,
        "total_lots" => round($total_lots, 2),
        "total_profit" => round($total_profit, 2)
    ]);

} catch (Exception $e) {

    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "Error fetching closed trades",
        "error" => $e->getMessage()
    ]);
}
?>
