<?php
require_once __DIR__ . '/../config.php';

$license = $_GET['license_key'] ?? '';
$mt5     = $_GET['mt5_account'] ?? '';

if (!$license || !$mt5) {
    echo json_encode(["status"=>"ERROR","msg"=>"INVALID_PARAMS"]);
    exit;
}

/* =========================================
   CLEAN STALE POSITIONS FIRST ✅
========================================= */
$conn->query("
    DELETE FROM fxh_positions_live 
    WHERE updated_at < NOW() - INTERVAL 30 SECOND
");

/* =========================================
   ACCOUNT SNAPSHOT
========================================= */
$q = $conn->prepare("
    SELECT balance, equity, margin, free_margin, margin_level
    FROM fxh_account_logs
    WHERE license_key = ?
      AND mt5_account = ?
    ORDER BY id DESC
    LIMIT 1
");
$q->bind_param("ss", $license, $mt5);
$q->execute();
$row = $q->get_result()->fetch_assoc();

if (!$row){
    echo json_encode(["status"=>"ERROR","msg"=>"NO_DATA"]);
    exit;
}

/* =========================================
   TRUE FLOATING PNL FROM LIVE TABLE
========================================= */
$p = $conn->prepare("
    SELECT COALESCE(SUM(profit),0)
    FROM fxh_positions_live
    WHERE mt5_account = ?
");
$p->bind_param("s",$mt5);
$p->execute();
$pnl = $p->get_result()->fetch_row()[0] ?? 0;

echo json_encode([
    "status"        => "OK",
    "balance"       => (float)$row['balance'],
    "equity"        => (float)$row['equity'],
    "margin"        => (float)$row['margin'],
    "free_margin"   => (float)$row['free_margin'],
    "margin_level"  => (float)$row['margin_level'],
    "pnl"           => (float)$pnl
], JSON_NUMERIC_CHECK);
