<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, 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";

// Read JSON input
$input = json_decode(file_get_contents("php://input"), true);

// Defaults
$type  = $input['type'] ?? "live";   // live / closed
$page  = isset($input['page']) ? (int)$input['page'] : 1;
$limit = isset($input['limit']) ? (int)$input['limit'] : 10;

$offset = ($page - 1) * $limit;

function roundVal($val, $dec = 2) {
    return $val !== null ? round((float)$val, $dec) : 0;
}

try {
    $api = new MTWebAPI("WebAPITesterLocal", "./logs", true);
    $ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 10, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);

    if ($ret != MTRetCode::MT_RET_OK) {
        throw new Exception("Failed to connect to MT5");
    }

    $accounts = [];
    $res = $conn->query("SELECT l.trade_id, l.account_name, u.fullname 
                         FROM liveaccounts l 
                         LEFT JOIN loginusers u ON l.email = u.email
                         WHERE l.trade_id IS NOT NULL AND l.trade_id != ''");

    while ($row = $res->fetch_assoc()) {
        $accounts[] = $row;
    }

    if (empty($accounts)) {
        echo json_encode(["success" => true, "trades" => []]);
        exit;
    }

    $trades = [];

    foreach ($accounts as $acc) {
        $trade_id = (int)$acc['trade_id'];
        $name = $acc['fullname'] ?? $acc['account_name'] ?? 'Unknown';

        // ========== LIVE TRADES ==========
        if ($type === "live") {
            $total = 0;

            if ($api->PositionGetTotal($trade_id, $total) == MTRetCode::MT_RET_OK && $total > 0) {

                $pageData = [];
$api->PositionGetPage($trade_id, $offset, $limit, $pageData);

if (!is_array($pageData)) {
    $pageData = [];
}

                foreach ($pageData as $pos) {
                    $trades[] = [
                        "name" => $name,
                        "account" => $trade_id,
                        "ticket" => $pos->Position,
                        "symbol" => $pos->Symbol,
                        "lots" => round(($pos->Volume ?? 0) * 0.0001, 2),
                        "openPrice" => roundVal($pos->PriceOpen, 5),
                        "profit" => roundVal($pos->Profit),
                        "time" => gmdate("Y-m-d H:i:s", $pos->TimeCreate),
                        "type" => ($pos->Action ?? 0) == 1 ? "Sell" : "Buy"
                    ];
                }
            }
        }

        // ========== CLOSED TRADES ==========
        if ($type === "close") {
            $totalDeals = 0;

            if ($api->DealGetTotal($trade_id, 0, 0, $totalDeals) == MTRetCode::MT_RET_OK && $totalDeals > 0) {

                $pageData = [];
$api->DealGetPage($trade_id, 0, 0, $offset, $limit, $pageData);

if (!is_array($pageData)) {
    $pageData = [];
}


                foreach ($pageData as $deal) {
                    $trades[] = [
    "name" => $name,
    "account" => $trade_id,
    "ticket" => $deal->Order ?? 0,
    "symbol" => $deal->Symbol ?? "",
    "lots" => round(($deal->VolumeClosed ?? 0) * 0.0001, 2),
    "openPrice" => roundVal($deal->PricePosition ?? 0, 5),
    "closePrice" => roundVal($deal->Price ?? 0, 5),
    "profit" => roundVal($deal->Profit ?? 0),
    "openTime" => isset($deal->TimePosition)
        ? gmdate("Y-m-d H:i:s", $deal->TimePosition)
        : null, // or set to closeTime
    "closeTime" => gmdate("Y-m-d H:i:s", $deal->Time ?? 0),
    "type" => ($deal->Action ?? 0) == 1 ? "Sell" : "Buy"
];

                }
            }
        }
    }

    $api->Disconnect();

    echo json_encode([
        "success" => true,
        "page" => $page,
        "limit" => $limit,
        "count" => count($trades),
        "trades" => $trades
    ]);

} catch (Exception $ex) {
    echo json_encode([
        "success" => false,
        "message" => $ex->getMessage()
    ]);
}
?>
