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

// Faster helpers
function r($n, $dec = 2) {
    return $n === null ? null : round((float)$n, $dec);
}
function lot($raw) {
    return round(((float)$raw) * 0.0001, VOL_DEC);
}

//PRELOAD timezone object ONCE (previously created *100s* of times)
$TZ_KOLKATA = new DateTimeZone("Asia/Kolkata");

// Much faster timestamp func
function ts_kolkata_fast($sec, $ms = null) {
    global $TZ_KOLKATA;
    if (!$sec && !$ms) return null;

    if ($ms !== null) {
        $dt = new DateTime('@'.floor($ms/1000));
        $dt->setTimezone($TZ_KOLKATA);
        return $dt->format("Y-m-d H:i:s") . "." . ($ms % 1000);
    }

    $dt = new DateTime('@'.$sec);
    $dt->setTimezone($TZ_KOLKATA);
    return $dt->format("Y-m-d H:i:s");
}

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

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

try {
    // ⭐ FASTER MYSQL CONNECTION
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    if ($conn->connect_error) {
        throw new Exception("DB Connection failed: " . $conn->connect_error);
    }

    // ⭐ Single row fetch only — fast
    $stmt = $conn->prepare("SELECT email, trade_id, leverage FROM liveaccounts WHERE email = ? AND trade_id = ?");
    $stmt->bind_param("ss", $email, $trade_id);
    $stmt->execute();
    $account = $stmt->get_result()->fetch_assoc();

    if (!$account) throw new Exception("Account not found");

    // ⭐ MT5 CONNECT (optimized)
    $api = new MTWebAPI("WebAPITesterLocal", "./logs", false);
    $ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);

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

    // ⭐ Fetch user info
    $account_info = new MTUser();
    if ($api->UserAccountGet((int)$trade_id, $account_info) != MTRetCode::MT_RET_OK) {
        throw new Exception("Unable to fetch MT5 account details");
    }

    // =============================
    // 🔵 OPEN POSITIONS (FAST)
    // =============================
    $open_positions = [];
    $total_open_lots = 0;
    $total_open_profit = 0;

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

        $positions = [];
        if ($api->PositionGetPage((int)$trade_id, 0, $total_positions, $positions) == MTRetCode::MT_RET_OK) {

            foreach ($positions as $p) {
                $vol = lot($p->Volume);
                $profit = r($p->Profit, 2);

                $total_open_lots += $vol;
                $total_open_profit += $profit;

                $open_positions[] = [
                    "Ticket" => $p->Position,
                    "Symbol" => $p->Symbol,
                    "Action" => ($p->Action == 1 ? "Sell" : "Buy"),
                    "Volume" => $vol,
                    "PriceOpen" => r($p->PriceOpen, PRICE_DEC),
                    "PriceCurrent" => r($p->PriceCurrent, PRICE_DEC),
                    "Profit" => $profit,
                    "Swap" => r($p->Storage, 2),
                    "Commission" => r($p->Commission, 2),
                    "OpenTime" => ts_kolkata_fast($p->TimeCreate)
                ];
            }
        }
    }

    // =============================
    // 🔴 CLOSED POSITIONS (FAST)
    // =============================
    $closed_positions = [];
    $total_closed_lots = 0;
    $total_closed_profit = 0;

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

        $deals = [];
        if ($api->DealGetPage((int)$trade_id, 0, 0, 0, $total_deals, $deals) == MTRetCode::MT_RET_OK) {

            foreach ($deals as $d) {
                $volClosed = lot($d->VolumeClosed);

                if ($d->Order && $volClosed > 0) {

                    $profit = r($d->Profit, 2);

                    $total_closed_lots += $volClosed;
                    $total_closed_profit += $profit;

                    $closed_positions[] = [
                        "OpenTime" => ts_kolkata_fast($d->Time),
                        "Ticket" => $d->Order,
                        "Action" => ($d->Action == 1 ? "Sell" : "Buy"),
                        "Volume" => $volClosed,
                        "Symbol" => $d->Symbol,
                        "OpenPrice" => r($d->PricePosition, PRICE_DEC),
                        "ClosePrice" => r($d->Price, PRICE_DEC),
                        "CloseTime" => ts_kolkata_fast($d->Time),
                        "Commission" => r($d->Commission, 2),
                        "Swap" => r($d->Storage, 2),
                        "Profit" => $profit
                    ];
                }
            }
        }
    }

    $api->Disconnect();

    // ⭐ Summary
    $grand_lots = $total_open_lots + $total_closed_lots;
    $grand_profit = $total_open_profit + $total_closed_profit;

    echo json_encode([
        "success" => true,
        "account" => [
            "email" => $account['email'],
            "trade_id" => $account['trade_id'],
            "leverage" => !empty($account['leverage']) ? intval($account['leverage']) : $account_info->Leverage,
            "balance" => $account_info->Balance,
            "equity" => $account_info->Equity,
            "margin_free" => $account_info->MarginFree,
            "currency" => $account_info->Currency
        ],
        "open_trades" => [
            "total" => count($open_positions),
            "total_lots" => r($total_open_lots, 2),
            "total_profit" => r($total_open_profit, 2),
            "positions" => $open_positions
        ],
        "closed_trades" => [
            "total" => count($closed_positions),
            "total_lots" => r($total_closed_lots, 2),
            "total_profit" => r($total_closed_profit, 2),
            "positions" => $closed_positions
        ],
        "overall_summary" => [
            "total_lots" => r($grand_lots, 2),
            "total_profit_loss" => r($grand_profit, 2)
        ]
    ]);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "error" => $e->getMessage(),
        "line" => $e->getLine(),
        "file" => basename($e->getFile())
    ]);
}
?>
