<?php
define("FXH_PORTAL", true);

// 1️⃣ Load config FIRST (session_start happens only here)
require_once __DIR__ . '/../config.php';

// 2️⃣ Load authentication SECOND
require_once __DIR__ . '/../middleware/user_auth.php';

// ❗ No header.php, no sidebar.php, no HTML before output

$user_id = $_SESSION['user_id'] ?? 0;

/* 1) GET LICENSE KEYS FOR THIS USER */
$licenses = [];
$stmt = $conn->prepare("
    SELECT license_key 
    FROM fxhai_lmfwc_licenses 
    WHERE user_id = ?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

while ($row = $res->fetch_assoc()) {
    $raw   = trim($row['license_key']);
    $plain = $raw;

    if (strpos($raw, 'def5020') === 0) {
        $plain = fxh_decrypt_license($raw);
    }

    if ($plain === "" || $plain === "[decrypt error]") {
        continue;
    }

    $licenses[] = "'" . $conn->real_escape_string($plain) . "'";
}

if (empty($licenses)) {
    echo "<tr><td colspan='12' class='text-center text-muted'>No licenses found</td></tr>";
    exit;
}

$license_filter = implode(",", $licenses);

/* 2) FETCH LIVE POSITIONS */
$q = "
    SELECT * 
    FROM fxh_positions_live 
    WHERE license_key IN ($license_filter)
    ORDER BY ticket ASC
";

$rows = $conn->query($q);

if (!$rows || $rows->num_rows == 0) {
    echo "<tr><td colspan='12' class='text-center text-muted'>No open trades</td></tr>";
    exit;
}

/* 3) RENDER ROWS */
while ($p = $rows->fetch_assoc()) {

    // --- TYPE MAPPING (0/1 or buy/sell) ---
    $rawType = strtolower(trim((string)$p['type']));
    if ($rawType === '0' || $rawType === 'buy') {
        $typeLabel = 'BUY';
        $typeColor = '#3ddc91';
    } elseif ($rawType === '1' || $rawType === 'sell') {
        $typeLabel = 'SELL';
        $typeColor = '#ff6767';
    } else {
        $typeLabel = strtoupper($rawType);
        $typeColor = '#cfeaff';
    }

    // --- NUMBER FORMATTING (2 decimals) ---
    $vol    = number_format((float)$p['volume'],      2);
    $entry  = number_format((float)$p['open_price'],  2);
    $sl     = number_format((float)$p['sl'],          2);
    $tp     = number_format((float)$p['tp'],          2);
    $profit = number_format((float)$p['profit'],      2);
    $swap   = number_format((float)$p['swap'],        2);
    $comm   = number_format((float)$p['commission'],  2);

    $profitColor = ((float)$p['profit'] >= 0 ? '#3ddc91' : '#ff6767');

    echo "
    <tr class='fx-row'>
        <td>{$p['ticket']}</td>
        <td>{$p['symbol']}</td>
        <td style='color:{$typeColor};font-weight:600;'>{$typeLabel}</td>
        <td>{$vol}</td>
        <td>{$entry}</td>
        <td>{$sl}</td>
        <td>{$tp}</td>
        <td style='color:{$profitColor};font-weight:600;'>{$profit}</td>
        <td>{$swap}</td>
        <td>{$comm}</td>
        <td>{$p['open_time']}</td>

        <td style='text-align:center;white-space:nowrap;'>
            <button class='fx-btn fx-btn-close' data-ticket='{$p['ticket']}'>Close</button>
            <button class='fx-btn fx-btn-partial' data-ticket='{$p['ticket']}'>Partial</button>
        </td>
    </tr>
    ";
}
