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

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

// Read JSON input
$input = file_get_contents("php://input");
$data = json_decode($input, true);
$trade_id = $data['trade_id'] ?? null;

if (!$trade_id) {
    echo json_encode(["success" => false, "message" => "Trade ID is required"]);
    exit;
}

// Connect to MT5
$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) {
    echo json_encode([
        "success" => false,
        "message" => "Failed to connect to MT5",
        "error_code" => $ret
    ]);
    exit;
}

// Validate user in MT5
$userMT5 = new MTUser();
$ret = $api->UserGet((int)$trade_id, $userMT5);
if ($ret != MTRetCode::MT_RET_OK) {
    $api->Disconnect();
    echo json_encode([
        "success" => false,
        "message" => "User not found in MT5",
        "error_code" => $ret
    ]);
    exit;
}

// Fetch open positions
$total = 0;
$positions_data = [];

if (($ret = $api->PositionGetTotal($userMT5->Login, $total)) == MTRetCode::MT_RET_OK && $total > 0) {
    $positions = [];
    $ret = $api->PositionGetPage($userMT5->Login, 0, $total, $positions);

    if ($ret == MTRetCode::MT_RET_OK && !empty($positions)) {
        foreach ($positions as $pos) {
            // Debug: log what MT5 API actually returns
            error_log("MT5 Position Object: " . print_r($pos, true));

            $positions_data[] = [
                "Symbol"       => $pos->Symbol ?? null,
                "PriceOpen"    => $pos->PriceOpen ?? null,
                "PriceCurrent" => $pos->PriceCurrent ?? null,
                "PriceSL"      => $pos->PriceSL ?? null,
                "PriceTP"      => $pos->PriceTP ?? null,
                "Volume"       => isset($pos->Volume) ? round($pos->Volume * 0.0001, 2) : null,
                "Action"       => (isset($pos->Action) && $pos->Action == 1) ? "Sell" : "Buy",
                "Profit"       => $pos->Profit ?? null,
                "Storage"      => $pos->Storage ?? null,
                "TimeCreate"   => isset($pos->TimeCreate) ? gmdate("Y-m-d H:i:s", $pos->TimeCreate) : null
            ];
        }
    }
}

$api->Disconnect();

// Response
echo json_encode([
    "success" => true,
    "trade_id" => $trade_id,
    "total_positions" => $total,
    "positions" => $positions_data
]);
exit;
