<?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("Failed to connect to MT5 server. Ret code: $connect_code");
    }

    // Fetch all trade IDs
    $all_logins = [];
    $sql = "SELECT trade_id FROM liveaccounts WHERE trade_id IS NOT NULL AND trade_id != ''";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $all_logins[] = $row['trade_id'];
        }
    }

    if (empty($all_logins)) {
        echo json_encode([
            "success" => true,
            "total_trades" => 0,
            "trades" => [],
            "totals" => ["total_pl"=>0, "total_pips"=>0, "total_volume"=>0, "total_swaps"=>0]
        ]);
        exit;
    }

    $positions_result = [];
    $total_pl = 0.0;
    $total_pips = 0.0;
    $total_volume = 0.0;
    $total_swaps = 0.0;

    foreach ($all_logins as $login) {
        $totalPositions = 0;
        $ret = $mt5->PositionGetTotal($login, $totalPositions);
        if ($ret !== MTRetCode::MT_RET_OK || $totalPositions == 0) continue;

        $positions = [];
        $ret = $mt5->PositionGetPage($login, 0, $totalPositions, $positions);
        if ($ret !== MTRetCode::MT_RET_OK) continue;

        foreach ($positions as $pos) {
            // Convert MT5 volume to decimal lots
            // MT5 unit: 1 lot = 10000 units, normal accounts 100 units = 0.01 lots
            if (isset($pos->VolumeExt) && $pos->VolumeExt > 0) {
                $volume_in_lots = round($pos->VolumeExt / 100000000, 4); 
            } else {
                $volume_in_lots = round($pos->Volume / 100, 2);
            }

            // Pips calculation
            $pip_factor = 10000;
            $price_diff = ($pos->Action == 0) ? $pos->PriceCurrent - $pos->PriceOpen : $pos->PriceOpen - $pos->PriceCurrent;
            $pips = round($price_diff * $pip_factor, 2);

            $positions_result[] = [
                "login" => $pos->Login,
                "symbol" => $pos->Symbol,
                "action" => $pos->Action == 0 ? "BUY" : "SELL",
                "price_open" => round($pos->PriceOpen, 5),
                "price_current" => round($pos->PriceCurrent, 5),
                "volume" => $volume_in_lots,
                "profit" => round($pos->Profit, 2),
                "sl" => round($pos->PriceSL, 5),
                "tp" => round($pos->PriceTP, 5),
                "swap" => round($pos->Swap ?? 0, 2),
                "pips" => $pips,
                "time_create" => date("Y-m-d H:i:s", $pos->TimeCreate),
                "time_update" => date("Y-m-d H:i:s", $pos->TimeUpdate),
                "comment" => $pos->Comment
            ];

            // Update totals
            $total_volume += $volume_in_lots;
            $total_pl += $pos->Profit ?? 0;
            $total_swaps += $pos->Swap ?? 0;
            $total_pips += $pips;
        }
    }

    $mt5->Disconnect();

    echo json_encode([
        "success" => true,
        "total_trades" => count($positions_result),
        "trades" => $positions_result,
        "totals" => [
            "total_pl" => round($total_pl, 2),
            "total_pips" => round($total_pips, 2),
            "total_volume" => round($total_volume, 2),
            "total_swaps" => round($total_swaps, 2)
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "MT5 connection or position fetch error",
        "error" => $e->getMessage()
    ]);
    exit;
}
?>
