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

    // Get all active trade IDs
    $trade_ids = [];
    $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()) {
            $trade_ids[] = (int)$row['trade_id'];
        }
    }

    if (empty($trade_ids)) {
        echo json_encode([
            "success" => true,
            "message" => "No trade accounts found",
            "live" => ["count" => 0, "total_lots" => 0, "total_profit" => 0],
            "closed" => ["count" => 0, "total_lots" => 0, "total_profit" => 0]
        ]);
        exit;
    }

    // Initialize totals
    $live_total_count = 0;
    $live_total_lots = 0.0;
    $live_total_profit = 0.0;

    $closed_total_count = 0;
    $closed_total_lots = 0.0;
    $closed_total_profit = 0.0;

    // Loop through each trade ID
    foreach ($trade_ids as $trade_id) {
        /** ---------------- LIVE TRADES ---------------- **/
        $total_live = 0;
        $ret = $mt5->PositionGetTotal($trade_id, $total_live);
        if ($ret == MTRetCode::MT_RET_OK && $total_live > 0) {
            $positions = [];
            $ret = $mt5->PositionGetPage($trade_id, 0, $total_live, $positions);
            if ($ret == MTRetCode::MT_RET_OK && is_array($positions)) {
                foreach ($positions as $pos) {
                    $lots = isset($pos->VolumeExt) && $pos->VolumeExt > 0 
                        ? round($pos->VolumeExt / 100000000, 4)
                        : round($pos->Volume / 100, 2);
                    $profit = round($pos->Profit ?? 0, 2);

                    $live_total_count++;
                    $live_total_lots += $lots;
                    $live_total_profit += $profit;
                }
            }
        }

        /** ---------------- CLOSED TRADES ---------------- **/
        $total_closed = 0;
        $ret = $mt5->DealGetTotal($trade_id, 0, 0, $total_closed);
        if ($ret == MTRetCode::MT_RET_OK && $total_closed > 0) {
            $deals = [];
            $ret = $mt5->DealGetPage($trade_id, 0, 0, 0, $total_closed, $deals);
            if ($ret == MTRetCode::MT_RET_OK && is_array($deals)) {
                foreach ($deals as $deal) {
                    if (($deal->Order ?? 0) != 0 && isset($deal->VolumeClosed) && $deal->VolumeClosed > 0) {
                        $lots = round(($deal->VolumeClosed ?? 0) * 0.0001, 2);
                        $profit = round($deal->Profit ?? 0, 2);

                        $closed_total_count++;
                        $closed_total_lots += $lots;
                        $closed_total_profit += $profit;
                    }
                }
            }
        }
    }

    $mt5->Disconnect();

    echo json_encode([
        "success" => true,
        "live" => [
            "count" => $live_total_count,
            "total_lots" => round($live_total_lots, 2),
            "total_profit" => round($live_total_profit, 2)
        ],
        "closed" => [
            "count" => $closed_total_count,
            "total_lots" => round($closed_total_lots, 2),
            "total_profit" => round($closed_total_profit, 2)
        ]
    ]);

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