<?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_position.php";

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

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

    // Fetch active trade accounts
    $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,
            "message" => "No active accounts found",
            "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_live = 0;
        $ret = $mt5->PositionGetTotal($login, $total_live);

        if ($ret == MTRetCode::MT_RET_OK && $total_live > 0) {
            $positions = [];
            $ret = $mt5->PositionGetPage($login, 0, $total_live, $positions);

            if ($ret == MTRetCode::MT_RET_OK && is_array($positions)) {
                foreach ($positions as $pos) {
                    $lots = isset($pos->VolumeExt)
                        ? round($pos->VolumeExt / 100000000, 4)
                        : round($pos->Volume / 100, 2);

                    $profit = round($pos->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 live trades",
        "error" => $e->getMessage()
    ]);
}
?>
