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

// Speed Improvements
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('memory_limit', '512M');
set_time_limit(20);

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

const PRICE_DEC = 3;
const VOL_DEC   = 2;

function r($n, $dec = 2) {
    return $n === null ? null : round((float)$n, $dec);
}

function lot($raw) {
    return r(((float)$raw) * 0.0001, VOL_DEC);
}

function ts_kolkata($sec) {
    if ($sec === null) return null;
    return (new DateTime('@' . $sec))
        ->setTimezone(new DateTimeZone("Asia/Kolkata"))
        ->format("Y-m-d H:i:s");
}

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

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

// Faster API instance (disable verbose log)
$api = new MTWebAPI("WebAPITesterLocal", "./logs", false);
$ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);

// Fail fast
if ($ret !== MTRetCode::MT_RET_OK) {
    echo json_encode(["success" => false, "message" => "Failed to connect MT5", "error_code" => $ret]);
    exit;
}

/* =======================================================
   FETCH LIVE ACCOUNT EQUITY (FAST)
======================================================= */
$total_equity = 0;
$account_info = null;

// Primary account fetch
$acc_err = $api->UserAccountGet((int)$trade_id, $account_info);

if ($acc_err === MTRetCode::MT_RET_OK && $account_info) {
    $total_equity = r($account_info->Equity ?? 0, 2);
} else {
    // Fallback – but lightweight
    $acc_err2 = $api->UserGet((int)$trade_id, $account_info);
    if ($acc_err2 === MTRetCode::MT_RET_OK && $account_info) {
        $total_equity = r($account_info->Equity ?? 0, 2);
    }
}

/* =======================================================
   FETCH CLOSED DEALS (MAJOR SPEED OPTIMIZATION)
======================================================= */

$total = 0;
$closed_positions = [];
$total_volume = 0;
$total_profit_loss = 0;

// Get total
$err = $api->DealGetTotal((int)$trade_id, 0, 0, $total);

if ($err === MTRetCode::MT_RET_OK && $total > 0) {

    // Fetch all deals in SINGLE call (fast)
    $deals = [];
    $err = $api->DealGetPage((int)$trade_id, 0, 0, 0, $total, $deals);

    if ($err === MTRetCode::MT_RET_OK && !empty($deals)) {

        foreach ($deals as $deal) {

            // Skip empty deals quickly
            if (empty($deal->Order)) continue;

            $volume = lot($deal->VolumeClosed ?? 0);
            if ($volume <= 0) continue;

            $profit = r($deal->Profit ?? 0, 2);

            // Accumulate totals
            $total_volume += $volume;
            $total_profit_loss += $profit;

            // Append cleaned response
            $closed_positions[] = [
                "OpenTime"   => ts_kolkata($deal->Time ?? null),
                "Ticket"     => $deal->Order ?? null,
                "Action"     => (($deal->Action ?? 0) == 1 ? "Sell" : "Buy"),
                "Volume"     => $volume,
                "Symbol"     => $deal->Symbol ?? null,
                "OpenPrice"  => r($deal->PricePosition ?? null, PRICE_DEC),
                "ClosePrice" => r($deal->Price ?? null, PRICE_DEC),
                "CloseTime"  => ts_kolkata($deal->Time ?? null),
                "Commission" => r($deal->Commission ?? 0, 2),
                "Swap"       => r($deal->Storage ?? 0, 2),
                "Profit"     => $profit
            ];
        }
    }
}

$api->Disconnect();

/* =======================================================
   FINAL RESPONSE (FAST JSON ENCODE)
======================================================= */

echo json_encode([
    "success" => true,
    "trade_id" => $trade_id,
    "total_equity" => $total_equity,
    "total_volume" => r($total_volume, 2),
    "total_profit_loss" => r($total_profit_loss, 2),
    "total_closed_positions" => count($closed_positions),
    "closed_positions" => $closed_positions
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

exit;
?>
