<?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";
include_once __DIR__ . "/mt5_api/mt5_api.php";

const PRICE_DEC = 3;
const VOL_DEC   = 2;

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

// Faster timestamp formatter
function ts_kolkata($ts) {
    if (!$ts) return null;
    return gmdate("Y-m-d H:i:s", $ts + 19800); // +5.5 hours offset
}

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

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

// -------------------
// Fetch all trade accounts
// -------------------
$stmt = $conn->prepare("SELECT trade_id FROM liveaccounts WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

$accounts = [];
while ($row = $result->fetch_assoc()) {
    $accounts[] = (int)$row['trade_id'];
}
$stmt->close();

if (empty($accounts)) {
    echo json_encode(["success" => false, "message" => "No MT5 accounts found for this email"]);
    exit;
}

// -------------------
// Connect to MT5
// -------------------
$api = new MTWebAPI("WebAPITesterLocal", "./logs", false); // disable debug → faster
$ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, 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;
}

// -------------------
// Initialize totals
// -------------------
$total_equity = 0.0;
$total_volume = 0.0;
$total_profit_loss = 0.0;
$total_closed_positions = 0;

$closed_positions = [];

// -------------------
// Loop through each MT5 account
// -------------------
foreach ($accounts as $trade_id) {

    // Fetch account balance/equity
    $acc = null;
    if ($api->UserAccountGet($trade_id, $acc) == MTRetCode::MT_RET_OK && $acc) {
        $total_equity += (float)($acc->Equity ?? 0);
    }

    // Fetch closed deals count
    $total_deals = 0;
    if ($api->DealGetTotal($trade_id, 0, 0, $total_deals) != MTRetCode::MT_RET_OK || $total_deals === 0) {
        continue;
    }

    // Fetch closed deals page
    $deals = null;
    if ($api->DealGetPage($trade_id, 0, 0, 0, $total_deals, $deals) != MTRetCode::MT_RET_OK) {
        continue;
    }

    // Loop fast: no expensive operations inside
    foreach ($deals as $d) {

        $vol = lot($d->VolumeClosed ?? 0);
        if ($vol <= 0) continue; // skip invalid / non-closing

        $profit = (float)($d->Profit ?? 0);

        $total_volume += $vol;
        $total_profit_loss += $profit;
        $total_closed_positions++;

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

// Disconnect MT5
$api->Disconnect();

// -------------------
// Output
// -------------------
echo json_encode([
    "success" => true,
    "email" => $email,
    "total_accounts" => count($accounts),
    "total_equity" => r($total_equity, 2),
    "total_volume" => r($total_volume, 2),
    "total_profit_loss" => r($total_profit_loss, 2),
    "total_closed_positions" => $total_closed_positions,
    "closed_positions" => $closed_positions
], JSON_PRETTY_PRINT);

?>
