<?php
session_start();
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// ini_set('html_errors', 1);
// ini_set('log_errors', 1);
// error_reporting(E_ALL);

// echo "✅ DASHBOARD BOOT OK<br>";
//flush();
// =======================================================
//  FX-HUNTER PORTAL — NEON DASHBOARD FINAL POLISHED VERSION
// =======================================================

define("FXH_PORTAL", true);
$pageTitle = "Dashboard";
require_once __DIR__ . '/../config.php';
// =======================================================
// SAFE AUTO-SYNC ON DASHBOARD LOAD
// =======================================================

//ignore_user_abort(true);
//set_time_limit(2);

//@file_get_contents("https://api.fxhunterai.com/webhook/sync_lmfwc_licenses.php");
//@file_get_contents("https://api.fxhunterai.com/webhook/manage_signal_files.php");


//if (file_exists($sync1)) {
//     require $sync1;
// }

// if (file_exists($sync2)) {
//     require $sync2;
//}
// ✅ AUTO-SYNC SIGNAL FILES WHEN DASHBOARD LOADS
ob_start();
//require_once __DIR__ . '/../../webhook/sync_lmfwc_licenses.php';
require_once __DIR__ . '/../../webhook/manage_signal_files.php';ob_end_clean();

require_once __DIR__ . '/../middleware/user_auth.php';

// Layout includes
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';

// -------------------------------------------------------
// AUTO-CLEAN STALE ACTIVATIONS (LIVE HOUSEKEEPING)
// -------------------------------------------------------
$conn->query("
    DELETE FROM fxh_license_activations
    WHERE last_seen < NOW() - INTERVAL 60 SECOND
");

// -------------------------------------------------------
//  Logged-in user
// -------------------------------------------------------
$userEmail = $_SESSION['email'] ?? "";

// Build map: encrypted license_key => decrypted license number
$decMap = [];
if (!empty($_SESSION['licenses']) && is_array($_SESSION['licenses'])) {
    foreach ($_SESSION['licenses'] as $lic) {
        if (!empty($lic['license_key']) && !empty($lic['decrypted'])) {
            $decMap[$lic['license_key']] = $lic['decrypted'];
        }
    }
}

// Load all licenses for this user
$licenses = [];
if ($userEmail !== "") {
    $sql = "
        SELECT 
            l.id,
            l.license_key,
            l.plan,
            l.mt5_account,
            l.active,
            l.created_at,
            l.expires_at,
            a.last_seen
        FROM fxh_licenses l
    
        LEFT JOIN fxh_license_activations a
            ON a.license_key = l.license_key
    
        WHERE l.user_email = ?
    
        ORDER BY (a.last_seen IS NOT NULL) DESC, l.id ASC
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $userEmail);
    $stmt->execute();
    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {
        $encKey = $row['license_key'];
        $row['decrypted'] = $decMap[$encKey] ?? $encKey;
        $licenses[] = $row;
    }
}

// -------------------------------------------------------
//  GET LIVE ACCOUNT METRICS FROM SNAPSHOT TABLE
//  fxh_account_logs
// -------------------------------------------------------
function fxh_get_account_metrics(mysqli $conn, string $licensePlain, string $mt5_account): ?array
{
    $sql = "
        SELECT balance, equity, profit, margin, free_margin, margin_level
        FROM fxh_account_logs
        WHERE license_key = ?
        AND mt5_account = ?
        ORDER BY id DESC
        LIMIT 1
    ";

    $st = $conn->prepare($sql);
    $st->bind_param("ss", $licensePlain, $mt5_account);
    $st->execute();
    $res = $st->get_result();

    return $res->fetch_assoc() ?: null;
}

?>

<style>
/* ==========================================================
   FX-HUNTER — PREMIUM NEON DASHBOARD THEME
   Cleaned, optimized, NO duplicate selectors
   ========================================================== */

/* =============== SECTION TITLES & DIVIDERS =============== */

.fxh-section-title {
    font-size: 24px;
    font-weight: 800;
    margin: 30px 0 10px 0;
    background: linear-gradient(90deg, #00eaff, #7a35ff);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: 0.6px;
}

.fxh-divider {
    width: 100%;
    height: 2px;
    border-radius: 50px;
    margin: 10px 0 25px 0;
    background: linear-gradient(90deg, transparent, #00ffa6, transparent);
    animation: fxhDividerGlow 2.5s ease-in-out infinite;
}

@keyframes fxhDividerGlow {
    0%   { opacity: 0.4; box-shadow: 0 0 6px #00ffa650; }
    50%  { opacity: 1;   box-shadow: 0 0 16px #00ffa6aa; }
    100% { opacity: 0.4; box-shadow: 0 0 6px #00ffa650; }
}

/* ==================== GRID LAYOUT ==================== */

.fxh-main .fxh-dash-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
    gap: 28px;
    margin-top: 10px;
    overflow: visible;
}

/* ================== ACCOUNT CARD ===================== */

.fxh-dash-card {
    position: relative;
    background: rgba(10, 14, 22, 0.92);
    border-radius: 20px;
    padding: 24px;
    border: 1px solid rgba(0, 255, 255, 0.15);
    box-shadow: 0 0 18px rgba(0, 255, 255, 0.12);
    transition: 0.25s ease;
    overflow: visible;
}

.fxh-dash-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 0 22px rgba(0,255,255,0.35);
}

/* Active glowing card */
.fxh-dash-card.active {
    border-color: #00ffa6;
    animation: fxhGlowPulse 2.4s ease-in-out infinite;
    z-index: 2;
}

@keyframes fxhGlowPulse {
    0% {
        box-shadow: 0 0 20px #00ffa650, 0 0 40px #00ffa620;
    }
    50% {
        box-shadow: 0 0 32px #00ffa6aa, 0 0 60px #00ffa655;
    }
    100% {
        box-shadow: 0 0 20px #00ffa650, 0 0 40px #00ffa620;
    }
}

/* Inactive card slightly faded */
.fxh-dash-card.inactive {
    opacity: 0.45;
}

/* ================== CARD HEADER ====================== */

.fxh-dash-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.fxh-plan-tag {
    padding: 6px 12px;
    background: #6c2cff;
    color: #fff;
    border-radius: 10px;
    font-size: 13px;
    font-weight: 700;
}

.fxh-license-id {
    font-size: 20px;
    font-weight: 700;
    color: #00eaff;
}

/* ================== CARD SUB INFO ===================== */

.fxh-dash-sub {
    margin-top: 10px;
    font-size: 15px;
    color: #cfd6ff;
}

.fxh-dash-sub small {
    color: #8fa0c8;
}

.copy-icon{
    color: #00eaff;
    position: relative;
    margin-left: 6px;
    cursor: pointer;
    transition: 0.2s ease;
}

.copy-icon:hover {
    color: #7cf8ff;
    transform: translateY(-1px);
}

/* Floating label */
.copied-label{
    position: absolute;
    right: -52px;
    top: 50%;
    transform: translateY(-50%);
    color: #00ff9d;
    font-size: 12px;
    font-weight: 600;
    white-space: nowrap;
    pointer-events: none;
    opacity: 0;
    animation: showCopied 1.5s ease forwards;
}

@keyframes showCopied {
    0%   { opacity: 0; transform: translate(5px,-50%); }
    15%  { opacity: 1; transform: translate(0,-50%); }
    80%  { opacity: 1; }
    100% { opacity: 0; }
}


/* =============== ACCOUNT STATUS BADGE ================ */

.fxh-dash-status {
    margin-top: 10px;
    display: inline-flex;
}

.fxh-dash-status span {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    letter-spacing: 0.4px;
}

.fxh-dash-status-active span {
    background: rgba(0,255,150,0.14);
    color: #00ff9d;
}

.fxh-dash-status-inactive span {
    background: rgba(255,255,255,0.07);
    color: #777;
}

/* ================== MAIN METRICS ===================== */

.fxh-dash-label {
    font-size: 14px;
    color: #9aa3c2;
    margin-top: 12px;
}

.fxh-dash-value {
    font-size: 32px;
    font-weight: 800;
    color: #ffffff;
}

.fxh-dash-pnl-green {
    color: #00ff9d;
}

.fxh-dash-pnl-red {
    color: #ff4d4d;
}

/* ============= MINI METRIC (Margin Block) ============ */

.fx-mini-metrics {
    margin-top: 14px;
    background: rgba(255,255,255,0.03);
    border-radius: 12px;
    padding: 12px 15px;
    backdrop-filter: blur(6px);
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.fx-mini-metrics div {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.mm-label {
    font-size: 13px;
    color: #9aa3c2;
    font-weight: 500;
}

.mm-value {
    font-size: 16px;
    font-weight: 700;
    color: #ffffff;
}

/* ================= NEON BUTTON ======================= */

.neon-btn {
    display: inline-block;
    margin-top: 16px;
    padding: 10px 24px;
    border-radius: 14px;
    background: linear-gradient(45deg, #7a35ff, #00eaff);
    color: #fff;
    font-weight: 700;
    font-size: 14px;
    text-decoration: none;
    box-shadow: 0 0 16px #00eaff55;
    transition: 0.25s ease;
}

.neon-btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 0 22px #00eaffcc;
}

/* ============ TABLES (Last Signals / Trades) ========= */

.fx-table-wrap {
    width: 100%;
    background: rgba(20,25,35,0.85);
    border-radius: 20px;
    margin-top: 16px;
    box-shadow: 0 0 20px rgba(0,255,255,0.12);
    overflow: hidden;
}

.fx-table {
    width: 100%;
    border-collapse: collapse;
}

.fx-table thead th {
    padding: 12px;
    background: rgba(0,200,255,0.12);
    color: #cfeaff;
    font-size: 14px;
    font-weight: 700;
    border-bottom: 1px solid rgba(255,255,255,0.06);
}

.fx-table tbody td {
    padding: 12px;
    font-size: 14px;
    color: #d7eaff;
    border-bottom: 1px solid rgba(255,255,255,0.04);
}

.fx-table tbody tr:hover {
    background: rgba(0,255,255,0.05);
    transition: 0.25s ease;
}

/* Profit colors in tables */
.pnl-green {
    color: #00ff9d;
    font-weight: 700;
}
.pnl-red {
    color: #ff4d4d;
    font-weight: 700;
}

/* ================= RESPONSIVE ======================== */

@media (max-width: 992px) {
    .fxh-main .fxh-dash-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 576px) {
    .fxh-dash-card {
        padding: 18px;
    }
    .fxh-dash-value {
        font-size: 26px;
    }
    .fx-mini-metrics {
        padding: 10px 12px;
    }
}

/* ===========================================================
   NEON TABLE WRAPPER — MATCH MAIN SIGNAL/HISTORY THEME
   =========================================================== */

.fx-table-wrap {
    width: 100%;
    background: rgba(12, 18, 30, 0.88);
    border-radius: 18px;
    overflow: hidden;
    margin-top: 14px;
    padding: 0;
    border: 1px solid rgba(0,255,255,0.12);
    box-shadow: 0 0 20px rgba(0,255,255,0.15);
    animation: fxhTableGlowPulse 3.5s ease-in-out infinite;
}

/* Smooth outer pulse */
@keyframes fxhTableGlowPulse {
    0%   { box-shadow: 0 0 18px rgba(0,255,255,0.18); }
    50%  { box-shadow: 0 0 32px rgba(0,255,255,0.35); }
    100% { box-shadow: 0 0 18px rgba(0,255,255,0.18); }
}

/* ===========================================================
   TABLE INSIDE
   =========================================================== */

.fx-table {
    width: 100%;
    border-collapse: collapse;
    animation: fxhFadeIn 0.6s ease;
}

@keyframes fxhFadeIn {
    from { opacity: 0; transform: translateY(8px); }
    to   { opacity: 1; transform: translateY(0); }
}

/* HEADER */
.fx-table thead th {
    background: rgba(0,200,255,0.12);
    color: #cfeaff;
    padding: 14px;
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 0.4px;
    border-bottom: 1px solid rgba(255,255,255,0.06);
    text-transform: uppercase;
}

/* ROWS */
.fx-table tbody tr {
    transition: 0.25s ease;
}

/* HOVER - Neon glow row */
.fx-table tbody tr:hover {
    background: rgba(0,255,255,0.05);
    box-shadow: inset 0 0 22px rgba(0,255,255,0.18);
    cursor: pointer;
}

/* TD */
.fx-table tbody td {
    padding: 12px 14px;
    color: #d7eaff;
    border-bottom: 1px solid rgba(255,255,255,0.04);
    font-size: 14px;
}

/* Profit colors */
.pnl-green { color: #00ff9d; font-weight: 700; }
.pnl-red   { color: #ff4d4d; font-weight: 700; }

/* ============================
   HERO ROTATING TITLE (SAFE)
   ============================ */

.fxh-main .fx-rotator-title {
    width: 100%;
    text-align: center;
    font-size: 58px;              /* BIG TITLE */
    font-weight: 900;
    margin: 10px 0 30px 0;
    color: #ffffff;
    line-height: 1.05;
}

.fxh-main .fx-rotator-title span {
    background: linear-gradient(90deg, #4ecbff, #a06bff);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-weight: 900;
    display: inline-block;
}

/* Fade animation */
@keyframes fxFadeRotate {
    0% { opacity: 0; transform: translateY(10px); }
    100% { opacity: 1; transform: translateY(0); }
}

#fx-rotating-word {
    animation: fxFadeRotate .5s ease;
}
/* =============================
   NEON TICKER TAPE WRAPPER
   ============================= */

.fx-tv-ticker-wrap {
    width: 100%;
    background: rgba(10, 14, 22, 0.85);
    border: 1px solid rgba(0,255,230,0.25);
    border-radius: 18px;
    box-shadow: 0 0 18px rgba(0,255,230,0.15);
    padding: 12px 18px;
    margin: 30px 0 25px 0;
    overflow: hidden;
    backdrop-filter: blur(4px);
}

.fx-tv-ticker-wrap:hover {
    box-shadow: 0 0 28px rgba(0,255,230,0.25);
    transition: .25s;
}

/* Remove TradingView white background */
.tradingview-widget-container {
    background: transparent !important;
}


</style>

<style>
/* Remove TradingView Branding — ALL METHODS */
.tradingview-widget-copyright,
a[href*="tradingview"],
iframe + div,
iframe ~ div {
    display: none !important;
    opacity: 0 !important;
    visibility: hidden !important;
    height: 0 !important;
    pointer-events: none !important;
}

/* Force-hide inside shadow DOM using iframe overlay */
.fx-tv-cleaner {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: transparent;
    pointer-events: none;
    z-index: 9999;
}

.copy-bubble {
    position: absolute;
    background: #000;
    color: #fff;
    padding: 4px 10px;
    border-radius: 6px;
    font-size: 13px;
    opacity: 0;
    transition: opacity 0.25s ease;
    z-index: 999999;
    pointer-events: none;
    white-space: nowrap;
}

/* ======================================================
   TOOLBAR – FINAL BULLETPROOF LAYOUT
====================================================== */

/* Sidebar width variables */
:root{
    --fxh-sidebar-full: 280px;     /* FULL SIDEBAR */
    --fxh-sidebar-mini: 80px;      /* COLLAPSED SIDEBAR */
    --fxh-sidebar-current: var(--fxh-sidebar-full);
}

/* MAIN BAR */
.fxh-download-wrap{
    position: sticky;
    top: 14px;

    display: grid;
    grid-template-columns: auto 1fr auto;
    align-items: center;
    gap: 18px;

    padding: 0 24px 16px calc(var(--fxh-sidebar-current) + 24px);

    margin-bottom: 18px;
    z-index: 900;

    background: linear-gradient(to bottom,
        rgba(5,10,18,0.96) 0%,
        rgba(5,10,18,0.90) 75%,
        rgba(5,10,18,0) 100%
    );
}

/* TOTAL FLOAT PANEL */
#fxh-total-panel{
    background:#0b1220;
    border-radius:14px;
    padding:10px 18px;
    border:1px solid rgba(0,255,180,.35);
    box-shadow:0 0 15px rgba(0,255,180,.35);
    text-align:center;
    min-width:180px;
}

/* DOWNLOAD BUTTON */
.fxh-download-btn{
    justify-self: end;
    display: inline-flex;
    align-items: center;
    gap: 10px;

    padding: 12px 24px;

    background: linear-gradient(90deg,#00eaff,#7a35ff);
    color:#fff;
    font-weight:700;
    font-size:15px;
    border-radius:14px;
    text-decoration:none;

    box-shadow:0 0 14px rgba(0,255,255,.35);
    transition:.25s ease;
}

.fxh-download-btn:hover{
    transform:translateY(-3px);
    box-shadow:0 0 22px rgba(0,255,255,.55);
}

/* STICKY DIVIDER */
.fxh-toolbar-divider{
    display:none;
}

/* sticky glowing line attached under the toolbar */
.fxh-download-wrap::after{
    content:"";
    position:absolute;
    left:0;
    right:0;
    bottom:0;
    height:2px;

    background:linear-gradient(
        90deg,
        transparent,
        rgba(0,255,190,.9),
        transparent
    );
    box-shadow:0 0 14px rgba(0,255,180,.7);
}

/* MOBILE MODE */
@media (max-width:900px){

    :root{
        --fxh-sidebar-current: 0px;
    }

    .fxh-download-wrap{
        padding-left:16px;
        padding-right:16px;
        grid-template-columns: 1fr;
    }

    #fxh-total-panel,
    .fxh-download-btn{
        width:100%;
        justify-content:center;
        text-align:center;
    }

    .fxh-toolbar-divider{
        margin-left:0;
    }
}



.trade-status-msg{
    margin-left:10px;
    color:#00ff9c;
    font-size:12px;
    font-weight:600;
    opacity:0;
    transition:opacity .25s ease;
    text-shadow:0 0 6px rgba(0,255,156,0.7);
}

.trade-status-msg.show{
    opacity:1;
}


</style>


<script>
function copyToClipboard(text, el) {

    navigator.clipboard.writeText(text);

    // prevent stacking labels
    if(el.querySelector(".copied-label")) return;

    const label = document.createElement("span");
    label.className = "copied-label";
    label.innerText = "Copied";

    el.appendChild(label);

    // auto remove after animation
    setTimeout(() => {
        if(label) label.remove();
    }, 1500);

}
</script>

<div class="fxh-download-wrap">

    <div id="fxh-total-panel">
        <div style="font-size:13px;color:#8ff;">TOTAL FLOATING</div>

        <div id="fxh-total-floating"
             style="font-size:22px;font-weight:900;color:#00ff9c">
            +0.00
        </div>

        <button id="fxh-book-all"
                class="neon-btn"
                style="margin-top:6px;padding:6px 16px;font-size:12px;">
            BOOK ALL
        </button>
        <span id="fxh-book-all-status" class="trade-status-msg"></span>
    </div>

    <div></div>

    <a class="fxh-download-btn"
       href="https://api.fxhunterai.com/FX-HUNTER BRIDGE CONNECTOR AI INTEGRATED.ex5">
        <i class="fa-solid fa-download"></i>
        DOWNLOAD EA
    </a>

</div>

<div class="fxh-toolbar-divider"></div>


<div class="fxh-main">
    <h3 class="fx-rotator-title">
    Automate Your <span id="fx-rotating-word">Strategies</span>
</h3>

    

<div class="fx-tv-wrapper" style="position: relative;">

    <!-- Invisible cleaner layer -->
    <div class="fx-tv-cleaner"></div>

    <!-- TradingView Widget BEGIN -->
    <div class="tradingview-widget-container">
      <div class="tradingview-widget-container__widget"></div>

      <!-- Remove footer -->
      <div style="display:none !important;"></div>

      <script type="text/javascript"
              src="https://s3.tradingview.com/external-embedding/embed-widget-ticker-tape.js" async>
      {
        "symbols": [
          {"proName": "FOREXCOM:SPXUSD", "title": "S&P 500"},
          {"proName": "FOREXCOM:NSXUSD", "title": "NAS100"},
          {"proName": "FX_IDC:EURUSD", "title": "EUR/USD"},
          {"proName": "BITSTAMP:BTCUSD", "title": "Bitcoin"},
          {"proName": "BITSTAMP:ETHUSD", "title": "Ethereum"},
          {"proName": "BLUEBERRY:XAUUSD", "title": "Gold"},
          {"proName": "BLUEBERRY:XAGUSD", "title": "Silver"},
          {"proName": "BLUEBERRY:DJ30", "title": "US30"}
        ],
        "colorTheme": "dark",
        "locale": "en",
        "isTransparent": true,
        "displayMode": "adaptive",
        "showSymbolLogo": true
      }
      </script>
    </div>
    <!-- TradingView Widget END -->

</div>
    <div class="fxh-divider"></div>

    <div class="fxh-dash-grid">

<?php
foreach ($licenses as $L):

    $plan   = strtoupper($L['plan']);
    $decKey = $L['decrypted'];
    $mt5Acc = (int)$L['mt5_account'];

    $lastSeen = $L['last_seen'] ?? null;

    $isActive =
    (
        $L['mt5_account'] !== null &&
        $lastSeen !== null &&
        strtotime($lastSeen) >= (time() - 75)
    );
    $cardClass = $isActive ? 'fxh-dash-card active' : 'fxh-dash-card inactive';

    // ==============================
    // SAFE METRICS LOAD
    // ==============================
    $M = fxh_get_account_metrics($conn, $decKey, $mt5Acc);

    $balance      = isset($M['balance'])      ? (float)$M['balance']      : 0.0;
    $equity       = isset($M['equity'])       ? (float)$M['equity']       : 0.0;
    $profit       = isset($M['profit'])       ? (float)$M['profit']       : 0.0;
    $margin       = isset($M['margin'])       ? (float)$M['margin']       : 0.0;
    $free_margin  = isset($M['free_margin'])  ? (float)$M['free_margin']  : 0.0;
    $margin_level = isset($M['margin_level']) ? (float)$M['margin_level'] : 0.0;

    // formatting
    $balance_f     = number_format($balance, 2);
    $equity_f      = number_format($equity, 2);
    $margin_f      = number_format($margin, 2);
    $free_margin_f = number_format($free_margin, 2);
    $margin_lvl_f  = number_format($margin_level, 2);

    $pnlText  = ($profit >= 0 ? "+" : "") . number_format($profit, 2);
    $pnlClass = $profit >= 0 ? "fxh-dash-pnl-green" : "fxh-dash-pnl-red";
?>

<div class="<?= $cardClass ?>"
     data-license="<?= htmlspecialchars($decKey) ?>"
     data-mt5="<?= $mt5Acc ?>"
>
    <div class="fxh-dash-header-row">
        <div class="fxh-plan-tag">MT5</div>
        <div class="fxh-plan-tag">BLUEBERRY INSTANT FUNDED</div>
        <div class="fxh-license-id">#<?= $mt5Acc ?></div>
    </div>

    <div class="fxh-dash-sub">
        <?= $plan ?> ACCOUNT<br>
        <small>
            License: <?= $decKey ?>
            <span class="copy-icon" onclick="copyToClipboard('<?= $decKey ?>', this)">
                <i class="fa-regular fa-copy"></i>
            </span>
        </small><br>
        <small>Start: <?= substr($L['created_at'], 0, 10) ?></small><br>
        <small>Expire: <?= substr($L['expires_at'], 0, 10) ?></small>
    </div>

    <div class="fxh-dash-status <?= $isActive ? 'fxh-dash-status-active' : 'fxh-dash-status-inactive' ?>">
        <span><?= $isActive ? 'ACTIVE' : 'INACTIVE' ?></span>
    </div>

    <div class="fxh-dash-label">Balance</div>
    <div class="fxh-dash-value">$<?= $balance_f ?></div>

    <div class="fxh-dash-label">Equity</div>
    <div class="fxh-dash-value">$<?= $equity_f ?></div>

    <div class="fx-mini-metrics">
        <div>
            <span class="mm-label">Margin</span>
            <span class="mm-value">$<?= $margin_f ?></span>
        </div>

        <div>
            <span class="mm-label">Free Margin</span>
            <span class="mm-value">$<?= $free_margin_f ?></span>
        </div>

        <div>
            <span class="mm-label">Margin Level</span>
            <span class="mm-value"><?= $margin_lvl_f ?>%</span>
        </div>
    </div>

    <div class="fxh-dash-label">Today's Total Profit</div>
    <div
        id="fxh_pnl_<?= $mt5Acc ?>"
        class="fxh-dash-value fxh-realtime-pnl <?= $pnlClass ?>"
    >
        <?= $pnlText ?>
    </div>
    <div style="margin-top:8px;">
    <button
        class="neon-btn"
        style="padding:6px 14px;font-size:13px;"
        onclick="bookProfit('<?= $decKey ?>','<?= $mt5Acc ?>', this)">
        BOOK PROFIT
    </button>

    <span class="trade-status-msg"></span>
</div>
    <!-- DAILY CLOSED -->
    <div class="fxh-dash-label">Today's Closed Profit</div>
    <div id="fxh_daily_pnl_<?= $mt5Acc ?>"
         class="fxh-dash-value fxh-realtime-daily fxh-dash-pnl-green">
        +0.00
    </div>

    <a class="neon-btn" href="metrics.php?license=<?= $L['id'] ?>">
        Go to metrics →
    </a>
</div>

<?php endforeach; ?>
</div>

<!-- ======================================
     TRADE CONTROL PANEL (DASHBOARD EMBED)
======================================= -->

<div class="fxh-section-title">TRADE PANEL</div>
<div class="fxh-divider"></div>

<div class="fx-table-wrap" style="padding:18px">

    <!-- LICENSE SELECTOR -->
    <div style="margin-bottom:14px;">
        <strong style="color:#8ff;">Select Licenses:</strong><br>

        <?php foreach ($licenses as $L): ?>
            <label style="margin-right:14px;font-size:13px;">
                <input type="checkbox"
                       class="fxh-trade-license"
                       value="<?= htmlspecialchars($L['decrypted']) ?>">
                <?= htmlspecialchars($L['decrypted']) ?>
            </label>
        <?php endforeach; ?>
    </div>

    <!-- SYMBOL + PARAMS -->
    <div style="display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-bottom:14px;">
        <input id="fxh_tp_symbol" placeholder="symbol (nas100 / xauusd)"
               style="padding:10px 12px;border-radius:12px;border:1px solid rgba(0,255,255,0.25);background:#0b1220;color:#d7eaff;min-width:220px;">
        <input id="fxh_tp_risk" placeholder="risk (0.10)" value="0.10"
               style="padding:10px 12px;border-radius:12px;border:1px solid rgba(0,255,255,0.25);background:#0b1220;color:#d7eaff;width:140px;">
        <input id="fxh_tp_sl" placeholder="sl (1000)" value="1000"
               style="padding:10px 12px;border-radius:12px;border:1px solid rgba(0,255,255,0.25);background:#0b1220;color:#d7eaff;width:140px;">
        <input id="fxh_tp_tp" placeholder="tp (3000)" value="3000"
               style="padding:10px 12px;border-radius:12px;border:1px solid rgba(0,255,255,0.25);background:#0b1220;color:#d7eaff;width:140px;">
        <input id="fxh_tp_comment" placeholder="comment (1M)" value="1M"
               style="padding:10px 12px;border-radius:12px;border:1px solid rgba(0,255,255,0.25);background:#0b1220;color:#d7eaff;width:140px;">
    </div>

    <!-- GLOBAL ACTIONS -->
    <div style="margin-bottom:18px;display:flex;flex-wrap:wrap;gap:10px;align-items:center;">
        <button class="neon-btn" onclick="fxhTP_Send('buy')">BUY</button>
        <button class="neon-btn" onclick="fxhTP_Send('sell')">SELL</button>
        <button class="neon-btn" onclick="fxhTP_Send('close_all_long')">CLOSE ALL LONG</button>
        <button class="neon-btn" onclick="fxhTP_Send('close_all_short')">CLOSE ALL SHORT</button>

        <span id="fxh-trade-status" class="trade-status-msg"></span>
    </div>

    <!-- OPEN TRADES TABLE (reads from fxh_positions_live) -->
    <table class="fx-table">
        <thead>
        <tr>
            <th>Symbol</th>
            <th>Type</th>
            <th>Ticket</th>
            <th>Volume</th>
            <th>Entry</th>
            <th>SL</th>
            <th>Profit</th>
            <th>Actions</th>
        </tr>
        </thead>
        <tbody id="fxh-open-trades">
            <tr>
                <td colspan="8" style="text-align:center;color:#777;">Loading…</td>
            </tr>
        </tbody>
    </table>

</div>


<!-- ======================================
     LAST SIGNALS SECTION
======================================= -->

<div class="fxh-section-title">LAST SIGNALS</div>
<div class="fxh-divider"></div>

<div class="fx-table-wrap">
<table class="fx-table">
<thead>
<tr>
    <th>Symbol</th>
    <th>Action</th>
    <th>Timeframe</th>
    <th>Date</th>
</tr>
</thead>

<tbody>
<?php
$q = $conn->query("
    SELECT symbol, action, timeframe, created_at
    FROM fxh_signal_logs
    ORDER BY id DESC
    LIMIT 10
");

while ($r = $q->fetch_assoc()):
?>
<tr>
    <td><?= $r['symbol'] ?></td>
    <td><?= strtoupper($r['action']) ?></td>
    <td><?= $r['timeframe'] ?></td>
    <td><?= $r['created_at'] ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>

<a class="neon-btn" href="/portal/user/signals.php">View All →</a>


<!-- ======================================
     LAST CLOSED TRADES
======================================= -->

<div class="fxh-section-title">LAST CLOSED TRADES</div>
<div class="fxh-divider"></div>

<div class="fx-table-wrap">
<table class="fx-table">
<thead>
<tr>
    <th>Symbol</th>
    <th>Type</th>
    <th>Volume</th>
    <th>Profit</th>
    <th>Close Time</th>
</tr>
</thead>

<tbody>
<?php
$q2 = $conn->query("
    SELECT symbol, type, volume, profit, close_time
    FROM fxh_trade_logs
    WHERE close_time IS NOT NULL
    ORDER BY id DESC
    LIMIT 10
");

while ($r = $q2->fetch_assoc()):
    $p = (float)$r['profit'];
    $pClass = $p >= 0 ? 'pnl-green' : 'pnl-red';
?>
<tr>
    <td><?= $r['symbol'] ?></td>
    <td><?= strtoupper($r['type']) ?></td>
    <td><?= $r['volume'] ?></td>
    <td class="<?= $pClass ?>"><?= number_format($p, 2) ?></td>
    <td><?= $r['close_time'] ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>

<script>
const words = ["Strategies", "Bots", "Alerts"];
let i = 0;

const el = document.getElementById("fx-rotating-word");

setInterval(() => {
    i = (i + 1) % words.length;
    el.style.animation = "none";
    el.offsetHeight; // reset animation
    el.textContent = words[i];
    el.style.animation = "fadeSlideIn 0.6s ease";
}, 2000);
</script>



<a class="neon-btn" href="/portal/user/history.php">View All →</a>


<script>
function refreshDailyPnL(){

    const nodes = document.querySelectorAll(".fxh-realtime-pnl");

    if(nodes.length === 0) return;

    nodes.forEach( pnlEl => {

        const card = pnlEl.closest(".fxh-dash-card");
        if(!card) return;

        const license = card.dataset.license;
        const mt5     = card.dataset.mt5;

        if(!license || !mt5) return;

        fetch(`/portal/api/get_account_live.php?license_key=${encodeURIComponent(license)}&mt5_account=${encodeURIComponent(mt5)}&_=${Date.now()}`)
            .then(res => res.json())
            .then(data => {

                if(!data || data.status !== "OK") return;

                let pnl = parseFloat(data.pnl);
                if(isNaN(pnl)) pnl = 0;

                pnlEl.textContent = (pnl >= 0 ? "+" : "") + pnl.toFixed(2);

                pnlEl.classList.remove("fxh-dash-pnl-green","fxh-dash-pnl-red");
                pnlEl.classList.add(
                    pnl >= 0 ? "fxh-dash-pnl-green" : "fxh-dash-pnl-red"
                );

            })
            .catch(console.error);
    });
}

// 🚀 initial fetch
refreshDailyPnL();

// 🔁 poll every 50 ms
setInterval(refreshDailyPnL, 2000);
</script>

<script>
function refreshDailyClosedProfit(){

    document.querySelectorAll(".fxh-realtime-daily").forEach(pnlEl => {

        const card = pnlEl.closest(".fxh-dash-card");
        if(!card) return;

        const mt5 = card.dataset.mt5;
        if(!mt5) return;

        fetch(`/portal/api/get_daily_closed_profit.php?mt5_account=${encodeURIComponent(mt5)}&_=${Date.now()}`)
            .then(res => res.json())
            .then(data => {

                if(!data || data.status !== "OK") return;

                let pnl = parseFloat(data.daily_profit);
                if(isNaN(pnl)) pnl = 0;

                pnlEl.textContent = (pnl >= 0 ? "+" : "") + pnl.toFixed(2);

                pnlEl.classList.remove("fxh-dash-pnl-green","fxh-dash-pnl-red");
                pnlEl.classList.add(
                    pnl >= 0 ? "fxh-dash-pnl-green" : "fxh-dash-pnl-red"
                );
            })
            .catch(console.error);

    });
}


// 🚀 initial daily profit fetch
refreshDailyClosedProfit();

// 🔁 every 1 second just like floating pnl
setInterval(refreshDailyClosedProfit, 1000);
</script>
<script>
window.bookProfit = function(license, mt5, btn)
{
    btn.disabled = true;

    fetch("/portal/api/book_profit.php",{
        method: "POST",
        headers: {
            "Content-Type":"application/x-www-form-urlencoded"
        },
        body:
            "license="+encodeURIComponent(license)+
            "&mt5="+encodeURIComponent(mt5)
    })
    .then(r => r.text())
    .then(resp => {

        console.log("BOOK PROFIT RESPONSE:", resp);

        let label = btn.nextElementSibling;

        if(resp.trim() === "OK"){
            label.innerText = "TRADE CLOSED";
            label.style.color = "#00ff9c";
        } else {
            label.innerText = "FAILED";
            label.style.color = "#ff4b4b";
        }

        label.classList.add("show");

        setTimeout(()=>{
            label.classList.remove("show");
            label.innerText = "";
            btn.disabled = false;
        }, 2000);
    })
    .catch(err => {
        console.error(err);

        let label = btn.nextElementSibling;
        label.innerText = "NETWORK ERROR";
        label.style.color = "#ff4b4b";
        label.classList.add("show");

        setTimeout(()=>{
            label.classList.remove("show");
            label.innerText = "";
            btn.disabled = false;
        }, 3000);
    });
}
</script>

<script>
/* =======================================================
   GLOBAL FLOATING PNL — DOM-BASED AGGREGATE
   Uses the same values already shown in the cards
======================================================= */

function refreshGlobalProfit()
{
    let total = 0;

    // read current PNL from each card that is ACTIVE
    document.querySelectorAll(".fxh-dash-card.active .fxh-realtime-pnl").forEach(el => {

        if (!el) return;

        // Example text: "+12.34", "-5.60", "+0.00"
        const raw = (el.textContent || "").trim();

        // strip everything except digits, dot, sign
        const cleaned = raw.replace(/[^0-9\.\-\+]/g, "");

        const v = parseFloat(cleaned);
        if (!isNaN(v)) {
            total += v;
        }
    });

    const totalEl = document.getElementById("fxh-total-floating");
    if (!totalEl) return;

    totalEl.textContent = (total >= 0 ? "+" : "") + total.toFixed(2);
    totalEl.style.color = total >= 0 ? "#00ff9d" : "#ff4d4d";
}

/* initial sync */
refreshGlobalProfit();

/* refresh every 2 sec */
setInterval(refreshGlobalProfit, 2000);


/* =======================================================
   BOOK PROFIT — ALL ACCOUNTS (INSTANT + DE-RACE)
======================================================= */

document.getElementById("fxh-book-all").addEventListener("click", async function(){

    const btn   = this;
    const label = document.getElementById("fxh-book-all-status");

    if(btn.disabled) return;   // HARD DE-RACE

    btn.disabled = true;
    btn.textContent = "SENDING...";

    let requests = [];

    document.querySelectorAll(".fxh-dash-card.active").forEach(card => {

        const license = card.dataset.license;
        const mt5     = card.dataset.mt5;

        if(!license || !mt5) return;

        requests.push(
            fetch("/portal/api/book_profit.php",{
                method: "POST",
                headers: {"Content-Type":"application/x-www-form-urlencoded"},
                body:
                    "license="+encodeURIComponent(license)+
                    "&mt5="+encodeURIComponent(mt5)
            })
            .catch(()=>{})
        );
    });

    /* ✅ WAIT UNTIL ALL CLOSE COMMANDS FIRED */
    await Promise.allSettled(requests);

    /* ✅ SHOW INLINE STATUS */
    if(requests.length){
        label.textContent = "TRADES CLOSED";
        label.style.color = "#00ff9c";
    } else {
        label.textContent = "NO ACTIVE ACCOUNTS";
        label.style.color = "#ffaa00";
    }

    label.classList.add("show");

    /* ✅ FORCE IMMEDIATE PNL REFRESH — NO DELAY */
    refreshDailyPnL();
    refreshGlobalProfit();

    /* ✅ RESET AFTER SHORT VISUAL FEEDBACK */
    setTimeout(()=>{
        label.classList.remove("show");
        label.textContent = "";
        btn.textContent = "BOOK ALL";
        btn.disabled = false;
    }, 1200);

});
</script>


<script>
function fxhSyncSidebarWidth(){

    const sidebar = document.querySelector('.fxh-sidebar');

    if(!sidebar) return;

    const width = sidebar.getBoundingClientRect().width;

    document.documentElement.style
        .setProperty('--fxh-sidebar-current', width + "px");
}

/* Initial sync */
fxhSyncSidebarWidth();

/* Re-sync on resize */
window.addEventListener("resize", fxhSyncSidebarWidth);

/* If sidebar has a toggle button */
document.addEventListener("click", e=>{
    if(e.target.closest(".sidebar-toggle")){
        setTimeout(fxhSyncSidebarWidth, 300);
    }
});
</script>

<script>
/* =======================================================
   FX-HUNTER — TRADE PANEL (DASHBOARD EMBED)
   Uses:
   - INSERT fxh_trade_commands
   - Your exact command syntax
======================================================= */

function fxhTP_SelectedLicenses(){
  return [...document.querySelectorAll(".fxh-trade-license:checked")]
    .map(x => x.value);
}

function fxhTP_Read(id, fallback=""){
  const el = document.getElementById(id);
  if(!el) return fallback;
  return (el.value || fallback).toString().trim();
}

function fxhTP_Status(msg, ok=true){
  const el = document.getElementById("fxh-trade-status");
  if(!el) return;
  el.textContent = msg;
  el.style.color = ok ? "#00ff9c" : "#ff4b4b";
  el.classList.add("show");
  setTimeout(()=>{ el.classList.remove("show"); el.textContent=""; }, 1800);
}

function fxhTP_Send(action, symbolOverride=""){
  const licenses = fxhTP_SelectedLicenses();
  if(!licenses.length){
    alert("Select at least one license");
    return;
  }

  const symbol  = (symbolOverride || fxhTP_Read("fxh_tp_symbol","")).toLowerCase();
  const risk    = fxhTP_Read("fxh_tp_risk","0.10");
  const sl      = fxhTP_Read("fxh_tp_sl","1000");
  const tp      = fxhTP_Read("fxh_tp_tp","3000");
  const comment = fxhTP_Read("fxh_tp_comment","1M");

  // symbol required for symbol actions
  const needsSymbol = ["buy","sell","close","close_50","be","sl_up","sl_down"].includes(action);
  if(needsSymbol && !symbol){
    alert("Enter symbol (e.g. nas100 / xauusd)");
    return;
  }

  fxhTP_Status("SENDING...", true);

  fetch("/portal/api/trade_panel_execute.php",{
    method:"POST",
    headers:{"Content-Type":"application/json"},
    body: JSON.stringify({
      licenses, action, symbol,
      risk, sl, tp,
      strategy_id: "FXH_CORE",
      comment
    })
  })
  .then(r=>r.json())
  .then(resp=>{
    if(resp && resp.status === "OK"){
      fxhTP_Status("COMMAND SENT", true);
      fxhTP_LoadOpenTrades(); // refresh immediately
    } else {
      fxhTP_Status("FAILED", false);
    }
  })
  .catch(()=> fxhTP_Status("NETWORK ERROR", false));
}

/* =======================================================
   OPEN TRADES: reads fxh_positions_live
   Filter by selected licenses (optional)
======================================================= */
function fxhTP_LoadOpenTrades(){
  const selected = fxhTP_SelectedLicenses();

  fetch("/portal/api/trade_panel_open_trades.php?_="+Date.now())
    .then(r=>r.json())
    .then(rows=>{
      const tbody = document.getElementById("fxh-open-trades");
      if(!tbody) return;

      if(!Array.isArray(rows)) rows = [];

      // If user selected licenses, only show those
      if(selected.length){
        rows = rows.filter(x => selected.includes((x.license_key||"").toString()));
      }

      if(!rows.length){
        tbody.innerHTML = `<tr><td colspan="8" style="text-align:center;color:#777;">No open trades</td></tr>`;
        return;
      }

      tbody.innerHTML = rows.map(t=>{
        const profitNum = parseFloat(t.profit);
        const pnlClass = (!isNaN(profitNum) && profitNum >= 0) ? "pnl-green" : "pnl-red";
        return `
          <tr>
            <td>${t.symbol}</td>
            <td>${t.type}</td>
            <td>${t.ticket}</td>
            <td>${t.volume}</td>
            <td>${t.entry_price}</td>
            <td>${t.sl}</td>
            <td class="${pnlClass}">${t.profit}</td>
            <td>
              <button onclick="fxhTP_Send('be','${t.symbol}')">BE</button>
              <button onclick="fxhTP_Send('sl_up','${t.symbol}')">SL ↑</button>
              <button onclick="fxhTP_Send('sl_down','${t.symbol}')">SL ↓</button>
              <button onclick="fxhTP_Send('close_50','${t.symbol}')">50%</button>
              <button onclick="fxhTP_Send('close','${t.symbol}')">CLOSE</button>
            </td>
          </tr>
        `;
      }).join("");
    })
    .catch(()=>{});
}

setInterval(fxhTP_LoadOpenTrades, 3000);
fxhTP_LoadOpenTrades();
</script>




<?php require_once __DIR__ . '/includes/footer.php'; ?>