<?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__ . "/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, $ms = null) {
    if ($sec === null) return null;
    if ($ms !== null) {
        $dt = (new DateTime('@'.floor($ms/1000)))->setTimezone(new DateTimeZone("Asia/Kolkata"));
        $msOnly = $ms % 1000;
        return $dt->format("Y-m-d H:i:s") . "." . $msOnly;
    }
    return (new DateTime('@'.$sec))->setTimezone(new DateTimeZone("Asia/Kolkata"))->format("Y-m-d H:i:s");
}

$input = json_decode(file_get_contents("php://input"), true);
$trade_id = $input['trade_id'] ?? null;
if (!$trade_id) { 
    echo json_encode(["success"=>false,"message"=>"trade_id is required"]); 
    exit; 
}

$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 MT5","error_code"=>$ret]); 
    exit; 
}

$total = 0;
$closed_positions = [];

// ✅ fetch all history (0,0), not just last 30 days
if (($err = $api->DealGetTotal((int)$trade_id, 0, 0, $total)) == MTRetCode::MT_RET_OK && $total > 0) {
    $deals = [];
    if (($err = $api->DealGetPage((int)$trade_id, 0, 0, 0, $total, $deals)) == MTRetCode::MT_RET_OK && is_array($deals)) {
        foreach ($deals as $deal) {
            if (($deal->Order ?? 0) != 0 && lot($deal->VolumeClosed ?? 0) > 0) {
                $closed_positions[] = [
                    "OpenTime"   => ts_kolkata($deal->Time ?? null),
                    "Ticket"     => $deal->Order ?? null,
                    "Action"     => (($deal->Action ?? 0) == 1 ? "Sell" : "Buy"),
                    "Volume"     => lot($deal->VolumeClosed ?? 0),
                    "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"     => r($deal->Profit ?? 0, 2)
                ];
            }
        }
    }
}

$api->Disconnect();

echo json_encode([
    "success" => true,
    "trade_id" => $trade_id,
    "total_closed_positions" => count($closed_positions),
    "closed_positions" => $closed_positions
]);
