<?php
/**
 * SmartForex Platform - Ultra Premium Custom Multi-Tab Trading Environment
 * Location: public_html/dashboard.php
 */
require_once __DIR__ . '/includes/functions.php';
check_user_auth(); 

$stmt = $pdo->prepare("SELECT id, username, balance, profit_loss, kyc_status FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$userData = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Trading Panel - Bits Exchange</title>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Rajdhani:wght@500;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>
    <style>
        :root {
            --darker: #020916; --card: #0b1528; --dark: #060e1d;
            --primary: #00d4ff; --text: #c8d8e8; --green: #00ff88; --red: #ff3366; --border: rgba(0,212,255,0.12);
        }
        
        body { 
            font-family: 'Rajdhani', sans-serif; 
            background: var(--darker); 
            color: var(--text); 
            margin: 0; 
            padding-bottom: 75px;
            box-sizing: border-box;
            overflow-x: hidden;
            width: 100vw;
        }
        
        .top-navbar { display: flex; justify-content: space-between; align-items: center; background: var(--card); padding: 15px 20px; border-bottom: 1px solid var(--border); position: relative; }
        .nav-logo { font-family: 'Orbitron', sans-serif; font-size: 20px; color: var(--primary); font-weight: bold; }
        .menu-container { position: relative; display: inline-block; }
        .three-dots-btn { background: none; border: none; color: var(--text); font-size: 24px; cursor: pointer; padding: 5px 10px; outline: none; }
        .dropdown-menu { display: none; position: absolute; right: 0; top: 35px; background: var(--card); border: 1px solid var(--border); border-radius: 6px; min-width: 180px; z-index: 10000; box-shadow: 0 5px 15px rgba(0,0,0,0.5); }
        .dropdown-menu div { color: var(--text); padding: 10px 15px; text-decoration: none; display: block; font-size: 14px; font-weight: bold; cursor: pointer; }
        .dropdown-menu div:hover { background: rgba(0,212,255,0.1); color: var(--primary); }
        .dropdown-menu a { color: var(--red); padding: 10px 15px; text-decoration: none; display: block; font-size: 14px; font-weight: bold; }

        .app-container { padding: 12px; max-width: 100%; margin: 0 auto; box-sizing: border-box; }
        .tab-content { display: none; width: 100%; }
        .tab-content.active { display: block; }

        .promo-banner { 
            background: linear-gradient(to right, rgba(2, 9, 22, 0.85), rgba(0, 212, 255, 0.2)), url('uploads/home.jpg') no-repeat center center; 
            background-size: cover; 
            border: 1px solid var(--border); 
            border-radius: 12px; 
            padding: 95px 20px; 
            margin-bottom: 15px; 
            box-shadow: 0 4px 20px rgba(0,0,0,0.4);
        }
        .promo-banner h2 { font-family: 'Orbitron', sans-serif; margin: 0 0 8px 0; color: white; font-size: 22px; }
        .promo-banner p { margin: 0; font-size: 14px; color: #a4b8cc; }

        .marquee-wrapper-line { width: 100%; overflow: hidden; background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 12px 0; margin-bottom: 15px; white-space: nowrap; box-sizing: border-box; }
        .marquee-inner-track { display: inline-block; padding-left: 100%; animation: shiftTickerLine 25s linear infinite; }
        .marquee-inner-track:hover { animation-play-state: paused; }
        .ticker-node { display: inline-block; margin-right: 40px; font-family: 'Orbitron', sans-serif; font-size: 14px; font-weight: bold; }
        .ticker-node span { margin-left: 8px; color: var(--green); }
        @keyframes shiftTickerLine { 0% { transform: translate3d(0, 0, 0); } 100% { transform: translate3d(-100%, 0, 0); } }

        .action-row-grid-v2 { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; margin-bottom: 20px; width: 100%; box-sizing: border-box; }
        @media (min-width: 768px) { .action-row-grid-v2 { grid-template-columns: repeat(4, 1fr); } }
        .action-card { background: linear-gradient(45deg, var(--card), #0f2444); border: 1px solid var(--border); padding: 15px; border-radius: 8px; font-size: 15px; font-weight: bold; cursor: pointer; }
        .action-card span { display: block; font-size: 11px; color: #7e9bb8; margin-top: 4px; }

        .tf-slider-container {
            display: flex; gap: 6px; overflow-x: auto; padding: 4px 0;
            white-space: nowrap; -webkit-overflow-scrolling: touch; width: 100%;
        }
        .tf-slider-container::-webkit-scrollbar { display: none; }

        .control-bar { 
            display: flex; flex-direction: column; gap: 10px; margin-bottom: 15px; width: 100%; 
        }
        @media (min-width: 480px) {
            .control-bar { flex-direction: row; justify-content: space-between; align-items: center; }
        }

        .trading-mesh { display: flex; flex-direction: column; gap: 15px; width: 100%; }
        .chart-block { width: 100%; background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 10px; box-sizing: border-box; overflow: hidden; }
        #chart-container { width: 100%; height: 340px; position: relative; overflow: hidden; }
        
        .order-block {
            width: 100%; background: rgba(11, 21, 40, 0.8) radial-gradient(circle at top right, rgba(0, 212, 255, 0.15), transparent 70%);
            border: 1px solid var(--primary); border-radius: 12px; padding: 15px; box-sizing: border-box;
        }

        .pair-select { background: var(--dark); color: var(--text); border: 1px solid var(--border); padding: 8px 12px; font-family: 'Orbitron', sans-serif; border-radius: 4px; font-size: 13px; }
        .tf-btn { background: var(--dark); border: 1px solid rgba(200,216,232,0.1); color: var(--text); padding: 6px 12px; font-family: 'Orbitron', sans-serif; border-radius: 4px; cursor: pointer; }
        .tf-btn.active { background: var(--primary); color: var(--darker); font-weight: bold; }
        .input-group { margin-bottom: 12px; width: 100%; }
        .input-group label { display: block; margin-bottom: 5px; font-size: 13px; font-weight: bold; }
        input { width: 100%; padding: 10px; background: var(--dark); border: 1px solid rgba(200,216,232,0.2); color: var(--text); border-radius: 4px; box-sizing: border-box; font-family: 'Orbitron', sans-serif; }
        .trade-btn { width: 100%; padding: 12px; border: none; font-family: 'Orbitron', sans-serif; font-weight: bold; font-size: 14px; border-radius: 4px; cursor: pointer; margin-top: 8px; }
        .btn-buy { background: var(--green); color: var(--darker); }
        .btn-sell { background: var(--red); color: white; }

        .data-card { 
            background: linear-gradient(135deg, rgba(11, 21, 40, 0.9) 0%, rgba(6, 14, 29, 0.95) 100%);
            border: 1px solid var(--border); border-radius: 12px; padding: 15px; margin-top: 15px; 
            max-width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch;
        }
        .data-card h3 { font-family: 'Orbitron', sans-serif; color: var(--primary); margin: 0 0 12px 0; font-size: 16px; }
        table { width: 100%; border-collapse: collapse; text-align: left; white-space: nowrap; }
        th, td { padding: 10px 8px; border-bottom: 1px solid rgba(200,216,232,0.05); font-size: 14px; }
        th { font-family: 'Orbitron', sans-serif; color: var(--primary); font-size: 12px; }
        
        .coin-logo-frame { width: 22px; height: 22px; border-radius: 50%; vertical-align: middle; margin-right: 10px; display: inline-block; }
        .asset-name-align { display: flex; align-items: center; font-family: 'Orbitron', sans-serif; font-weight: bold; }
        .close-action-btn { background: var(--red); border: none; color: white; padding: 6px 12px; font-family: 'Rajdhani', sans-serif; font-weight: bold; border-radius: 4px; cursor: pointer; }

        .modal-mask { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(2,9,22,0.85); backdrop-filter: blur(5px); z-index: 99999; justify-content: center; align-items: center; padding: 15px; box-sizing: border-box; }
        .stylish-modal-box { background: var(--card); border: 1px solid var(--primary); border-radius: 12px; width: 100%; max-width: 420px; padding: 20px; box-shadow: 0 0 25px rgba(0,212,255,0.25); text-align: center; box-sizing: border-box; }
        .modal-title { font-family: 'Orbitron', sans-serif; color: var(--primary); font-size: 16px; margin-bottom: 12px; text-transform: uppercase; }
        .modal-body-text { font-size: 14px; margin-bottom: 15px; line-height: 1.4; color: #a4b8cc; }
        .modal-btn-grid { display: flex; gap: 10px; justify-content: center; }
        .modal-act-btn { padding: 10px 20px; font-family: 'Orbitron', sans-serif; font-weight: bold; border: none; cursor: pointer; border-radius: 4px; font-size: 13px; }

        .fixed-bottom-bar { position: fixed; bottom: 0; left: 0; right: 0; height: 60px; background: var(--card); border-top: 1px solid var(--border); display: flex; justify-content: space-around; align-items: center; z-index: 999; width: 100vw; }
        .bottom-nav-item { display: flex; flex-direction: column; align-items: center; justify-content: center; color: #7e9bb8; text-decoration: none; cursor: pointer; font-family: 'Orbitron', sans-serif; font-size: 12px; font-weight: bold; flex: 1; height: 100%; }
        .bottom-nav-item.active { color: var(--primary); }

        .chat-msg-log { height: 260px; overflow-y: auto; padding: 10px; background: #060e1d; border-radius: 6px; border: 1px solid rgba(255,255,255,0.05); margin-bottom: 10px; display: flex; flex-direction: column; gap: 8px; }
        .chat-bubble { max-width: 80%; padding: 8px 12px; border-radius: 8px; font-size: 14px; word-break: break-all; }
        .chat-bubble.user-side { background: var(--primary); color: #020916; align-self: flex-end; font-weight: bold; }
        .chat-bubble.admin-side { background: rgba(255,255,255,0.1); color: #fff; align-self: flex-start; }
        .help-collapse-btn { width:100%; text-align:left; background:#060e1d; color:#fff; border:1px solid var(--border); padding:10px; border-radius:6px; margin-bottom:5px; font-family:'Orbitron'; font-weight:bold; cursor:pointer; font-size:13px; }
        .help-collapse-body { display:none; padding:10px; background:rgba(255,255,255,0.02); border-left:2px solid var(--primary); margin-bottom:10px; font-size:14px; line-height:1.4; color:#a4b8cc; }

        @media(min-width: 768px) {
            .trading-mesh { flex-direction: row; }
            .chart-block { flex: 3; }
            .order-block { flex: 1; }
        }
    </style>
</head>
<body>

<div class="top-navbar" style="height: 55px; padding-top: 5px; padding-bottom: 5px;">
    <div class="nav-logo" style="display: flex; align-items: center; position: relative; width: 275px; height: 42px;">
        <img src="uploads/logo.png" alt="Bits Exchange" style="position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 255px; height: auto; max-height: none !important; max-width: none !important; display: block; object-fit: fill;">
    </div>
    <div class="menu-container">
        <button class="three-dots-btn" onclick="toggleDropdown()">&#8942;</button>
        <div class="dropdown-menu" id="nav-dropdown">
            <div onclick="switchView('assets')">&#128188; Profit / Portfolio</div>
            <div onclick="openPasswordModalWindow()">&#128274; Change Password</div>
             <div onclick="openKYCModal()">&#127380; KYC Verification</div>
            <a href="logout.php">&#128721; Logout Platform</a>
        </div>
    </div>
</div>

<div class="app-container">

    <div id="view-home" class="tab-content active">
        <div class="promo-banner">
            <h2>Buy & Sell Crypto on Bits</h2>
            <p>Save worry, convenient, high efficiency structural margin environment.</p>
        </div>

        <div class="marquee-wrapper-line">
            <div class="marquee-inner-track" id="dynamic-marquee-track">
                <div class="ticker-node">BITS/USDT: <span style="color:var(--green)">5.0337</span></div>
                <div class="ticker-node">BTC/USDT: <span id="marquee-btc">Loading...</span></div>
                <div class="ticker-node">ETH/USDT: <span id="marquee-eth">Loading...</span></div>
                <div class="ticker-node">BNB/USDT: <span id="marquee-bnb">Loading...</span></div>
                <div class="ticker-node">SOL/USDT: <span id="marquee-sol">Loading...</span></div>
                <div class="ticker-node">XRP/USDT: <span id="marquee-xrp">Loading...</span></div>
                <div class="ticker-node">ADA/USDT: <span id="marquee-ada">Loading...</span></div>
                <div class="ticker-node">DOGE/USDT: <span id="marquee-doge">Loading...</span></div>
                <div class="ticker-node">DOT/USDT: <span id="marquee-dot">Loading...</span></div>
                <div class="ticker-node">AVAX/USDT: <span id="marquee-avax">Loading...</span></div>
            </div>
        </div>

        <div class="action-row-grid-v2">
            <div class="action-card" style="border-color:var(--primary); cursor:pointer;" onclick="switchView('trade')">Charts & Quotes<span>Live Pairs & Market Indices</span></div>
            <div class="action-card" style="border-color:var(--green); cursor:pointer;" onclick="openFinancierModal('tx-ledger')">Transaction Logs<span>P&L, Deposits & Withdrawals</span></div>
            <div class="action-card" style="border-color:#e0a816; cursor:pointer;" onclick="openFinancierModal('help-guide')">Help & Guidelines<span>English Operating Walkthrough</span></div>
            <div class="action-card" style="border-color:var(--red); cursor:pointer;" onclick="openFinancierModal('live-chat')">Customer Service<span>24/7 Secure Private Portal</span></div>
        </div>

        <div class="data-card">
            <h3>Rising Crypto Assets</h3>
            <table>
                <thead>
                    <tr style="color:#7e9bb8; border-bottom: 2px solid rgba(0,212,255,0.15);">
                        <th>Asset Pair</th>
                        <th>Last Price</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody id="home-top-pairs-body">
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <div class="coin-logo-frame" style="background: var(--primary); display: flex; align-items: center; justify-content: center; font-size: 11px; color: var(--darker); font-weight: bold;">B</div>
                                BITS/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;">5.0337</td>
                        <td style="color:var(--green); font-weight:bold;">+6.17%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/1/large/bitcoin.png" alt="btc">
                                BTC/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-btc">Loading...</td>
                        <td style="color:var(--green); font-weight:bold;">+2.45%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/279/large/ethereum.png" alt="eth">
                                ETH/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-eth">Loading...</td>
                        <td style="color:var(--green); font-weight:bold;">+1.85%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/825/large/binance-coin-logo.png" alt="bnb">
                                BNB/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-bnb">Loading...</td>
                        <td style="color:var(--green); font-weight:bold;">+0.92%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/4128/large/solana.png" alt="sol">
                                SOL/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-sol">Loading...</td>
                        <td style="color:var(--red); font-weight:bold;">-1.12%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/44/large/xrp-symbol-white-rgb.png" alt="xrp">
                                XRP/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-xrp">Loading...</td>
                        <td style="color:var(--green); font-weight:bold;">+0.54%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/975/large/cardano.png" alt="ada">
                                ADA/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-ada">Loading...</td>
                        <td style="color:var(--green); font-weight:bold;">+1.15%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/756/large/dogecoin.png" alt="doge">
                                DOGE/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-doge">Loading...</td>
                        <td style="color:var(--green); font-weight:bold;">+4.20%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/584/large/polkadot.png" alt="dot">
                                DOT/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-dot">Loading...</td>
                        <td style="color:var(--red); font-weight:bold;">-0.85%</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="asset-name-align">
                                <img class="coin-logo-frame" src="https://assets.coingecko.com/coins/images/4713/large/polygon.png" alt="avax">
                                AVAX/USDT
                            </div>
                        </td>
                        <td style="font-family:'Orbitron'; font-weight: bold;" id="row-price-avax">Loading...</td>
                        <td style="color:var(--green); font-weight:bold;">+2.10%</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <div id="view-trade" class="tab-content">
        <div class="trading-mesh">
            <div class="chart-block">
               <div class="control-bar">
                    <div style="display:flex; justify-content: space-between; align-items:center; width: 100%; gap:10px;">
                    <select id="pair-selector" class="pair-select" onchange="changePair()" style="display: block !important; width: 100% !important; max-width: 180px !important; min-height: 44px !important; padding: 0 15px !important; font-family: 'Orbitron', sans-serif; font-weight: bold; font-size: 13px; background: var(--dark) !important; color: #fff !important; border: 1px solid var(--border) !important; border-radius: 6px !important; cursor: pointer !important; box-sizing: border-box !important; -webkit-appearance: select !important; -moz-appearance: select !important; appearance: select !important; position: relative; z-index: 5;">
                            <option value="BTCUSDT" selected>BTC / USDT</option>
                            <option value="ETHUSDT">ETH / USDT</option>
                            <option value="BNBUSDT">BNB / USDT</option>
                            <option value="SOLUSDT">SOL / USDT</option>
                            <option value="XRPUSDT">XRP / USDT</option>
                            <option value="ADAUSDT">ADA / USDT</option>
                            <option value="DOGEUSDT">DOGE / USDT</option>
                            <option value="DOTUSDT">DOT / USDT</option>
                            <option value="AVAXUSDT">AVAX / USDT</option>
                        </select>
                        <div class="live-price" id="price-ticker" style="font-family:'Orbitron'; font-weight:bold; font-size:14px; color:var(--primary);">Synchronizing...</div>
                    </div>
                    <div class="tf-slider-container">
                        <button class="tf-btn active" onclick="changeTimeframe('1m', this)">1M</button>
                        <button class="tf-btn" onclick="changeTimeframe('5m', this)">5M</button>
                        <button class="tf-btn" onclick="changeTimeframe('15m', this)">15M</button>
                        <button class="tf-btn" onclick="changeTimeframe('30m', this)">30M</button>
                        <button class="tf-btn" onclick="changeTimeframe('1h', this)">1H</button>
                        <button class="tf-btn" onclick="changeTimeframe('4h', this)">4H</button>
                        <button class="tf-btn" onclick="changeTimeframe('1d', this)">1D</button>
                    </div>
                </div>
                <div id="chart-container"></div>
            </div>

            <div class="order-block">
                <h3>VIP Entry Execution</h3>
                <div class="input-group">
                    <label>Margin Allocation ($)</label>
                   <input type="number" id="trade-amount-input" placeholder="Calculating..." min="1">
                </div>
                <div class="input-group">
                    <label>Leverage Multiplier</label>
                    <select id="leverage-select" class="pair-select" style="width: 100%; height: 40px;">
                        <option value="1">1x</option>
                        <option value="25">25x</option>
                        <option value="50">50x</option>
                        <option value="75">75x</option>
                        <option value="100">100x</option>
                        <option value="200" selected>200x</option>
                    </select>
                    <div class="input-group" style="margin-top: 12px;">
                        <label>Lot Size / Trades Count</label>
                        <input type="number" id="trade-lot-size" value="1" min="1" max="20" style="width: 100%; padding: 10px; background: var(--dark); border: 1px solid rgba(200,216,232,0.2); color: var(--text); border-radius: 4px; font-family: 'Orbitron', sans-serif;">
                    </div>
                </div>
                <button class="trade-btn btn-buy" onclick="executeTrade('buy')">MARKET BUY</button>
                <button class="trade-btn btn-sell" onclick="executeTrade('sell')">MARKET SELL</button>
            </div>
        </div>

        <div class="data-card">
            <h3>Active Dynamic Open Positions</h3>
            <table>
               <thead>
                    <tr>
                        <th>Asset</th><th>Side</th><th>Lev</th><th>Lot Size</th><th>Margin</th><th>Entry</th><th>Live P&L</th><th>Action</th>
                    </tr>
                </thead>
                <tbody id="positions-list-body">
                    <tr><td colspan="8" style="text-align:center; color:gray;">No active metrics.</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <div id="view-history" class="tab-content">
        <div class="data-card">
            <h3>Account Personal Statement History Ledger</h3>
            <table>
                <thead>
                    <tr><th>Date Timestamp</th><th>Asset</th><th>Operation</th><th>Margin</th><th>Leverage</th><th>Entry Price</th><th>Exit Price</th><th>Net Return P&L</th><th>Status</th></tr>
                </thead>
                <tbody id="history-table-body">
                    <tr><td colspan="9" style="text-align:center; color:gray;">Loading ledger records...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <div id="view-assets" class="tab-content" style="width: 100%; box-sizing: border-box;">
        <div class="promo-banner" style="background: linear-gradient(135deg, #0b1528 0%, #060e1d 100%); padding: 25px; border-radius: 16px; border: 1px solid rgba(0, 212, 255, 0.15); box-shadow: 0 8px 24px rgba(0,0,0,0.4); margin-bottom: 20px; text-align: left;">
            <div style="font-size: 11px; color: #7e9bb8; font-family: 'Orbitron'; letter-spacing: 1px; font-weight: 600; margin-bottom: 8px;">NET MARGIN EXCHANGE BALANCE</div>
            <div id="live-profile-balance" data-base-balance="<?=(isset($_SESSION['is_demo']) && $_SESSION['is_demo'] === true) ? '10000000.00' : $userData['balance'] ?>" style="font-size: 34px; font-weight: 900; color: #00ff88; font-family: 'Orbitron'; filter: drop-shadow(0 0 8px rgba(0,255,136,0.3));">
                                <?php 
                                if (isset($_SESSION['is_demo']) && $_SESSION['is_demo'] === true) {
                                    echo "$10,000,000.00";
                                } else {
                                    echo "$" . number_format($userData['balance'], 2);
                                }
                                ?>
                            </div>
        </div>
        
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 14px; width: 100%; box-sizing: border-box; margin-bottom: 25px;">
            <div onclick="openGatewayModal('deposit')" style="background: linear-gradient(145deg, rgba(0, 255, 136, 0.08), rgba(0, 255, 136, 0.02)); border: 1px solid #00ff88; padding: 16px 10px; border-radius: 12px; cursor: pointer; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; box-shadow: 0 4px 15px rgba(0,255,136,0.05);">
                <div style="font-size: 24px;">&#128229;</div>
                <div style="color: #ffffff; font-family: 'Orbitron'; font-weight: 800; font-size: 13px; letter-spacing: 0.5px;">DEPOSIT FUNDS</div>
                <div style="font-size: 10px; color: #7e9bb8; font-family: 'Rajdhani';">Instant TRC20 Gateway</div>
            </div>

            <div onclick="openGatewayModal('withdrawal')" style="background: linear-gradient(145deg, rgba(255, 51, 102, 0.08), rgba(255, 51, 102, 0.02)); border: 1px solid #ff3366; padding: 16px 10px; border-radius: 12px; cursor: pointer; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; box-shadow: 0 4px 15px rgba(255,33,102,0.05);">
                <div style="font-size: 24px;">&#128228;</div>
                <div style="color: #ffffff; font-family: 'Orbitron'; font-weight: 800; font-size: 13px; letter-spacing: 0.5px;">SECURE WITHDRAW</div>
                <div style="font-size: 10px; color: #7e9bb8; font-family: 'Rajdhani';">Automated Payout Node</div>
            </div>
        </div>
    </div>
</div>

<div id="tx-ledger-modal" class="modal-mask">
    <div style="background: #060e1d; border: 1px solid var(--border); width: 100%; max-width: 520px; border-radius: 12px; padding: 20px; box-sizing: border-box; position: relative; max-height: 85vh; overflow-y: auto; box-shadow: 0 10px 30px rgba(0,0,0,0.6);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 10px;">
            <h3 style="font-family: 'Orbitron'; color: var(--green); margin: 0; font-size: 15px; letter-spacing: 0.5px;">FINANCIAL STATEMENT HISTORY</h3>
            <span style="color: #7e9bb8; cursor: pointer; font-size: 22px; font-weight: bold;" onclick="closeFinancierModal('tx-ledger')">&times;</span>
        </div>
        <div style="overflow-x: auto; max-width: 100%;">
            <table style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="color: var(--primary); font-size: 11px; border-bottom: 1px solid rgba(255,255,255,0.1);">
                        <th style="padding: 8px 5px;">Date</th>
                        <th style="padding: 8px 5px;">Type</th>
                        <th style="padding: 8px 5px;">Amount</th>
                        <th style="padding: 8px 5px;">Status</th>
                    </tr>
                </thead>
                <tbody id="combined-tx-rows"></tbody>
            </table>
        </div>
    </div>
</div>

<div id="help-guide-modal" class="modal-mask">
    <div style="background: #060e1d; border: 1px solid var(--border); width: 100%; max-width: 500px; border-radius: 12px; padding: 20px; box-sizing: border-box; position: relative; max-height: 85vh; overflow-y: auto; box-shadow: 0 10px 30px rgba(0,0,0,0.6);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 10px;">
            <h3 style="font-family: 'Orbitron'; color: #e0a816; margin: 0; font-size: 16px; letter-spacing: 0.5px;">SYSTEM OPERATION MANUAL</h3>
            <span style="color: #7e9bb8; cursor: pointer; font-size: 20px; font-weight: bold;" onclick="closeFinancierModal('help-guide')">&times;</span>
        </div>

        <button class="help-collapse-btn" onclick="toggleHelpSection('help-1')">1. HOW TO TRADE & EXECUTE ORDERS? <span>тЦ╝</span></button>
        <div id="help-1" class="help-collapse-body">
            Go to the <strong>Trade</strong> terminal from the bottom navigation bar. Select your desired crypto asset pair from the market index matrix, input your preferred risk leverage margin configuration, and execute either a Buy (Long) or Sell (Short) contract node based on real-time market trends.
        </div>

        <button class="help-collapse-btn" onclick="toggleHelpSection('help-2')">2. HOW TO DEPOSIT FUNDS SAFELY? <span>тЦ╝</span></button>
        <div id="help-2" class="help-collapse-body">
            Navigate to the <strong>Assets</strong> tab at the bottom right. Click on the <strong>DEPOSIT FUNDS</strong> interface node, scan the securely generated network QR code or copy the unique destination address string (USDT TRC20 protocol), transfer your funds, and upload the successful execution image snapshot for validation checks.
        </div>

        <button class="help-collapse-btn" onclick="toggleHelpSection('help-3')">3. HOW TO SUBMIT A WITHDRAWAL? <span>тЦ╝</span></button>
        <div id="help-3" class="help-collapse-body">
            Open the <strong>Assets</strong> node panel. Trigger the <strong>SECURE WITHDRAW</strong> protocol gateway. Specify your destination transaction network address block and input your settlement value payload parameter. The system smart routing layer will dispatch automated blockchain payouts instantly upon verification checks.
        </div>

        <button class="help-collapse-btn" onclick="toggleHelpSection('help-4')">4. KYC VALIDATION PROCESS <span>тЦ╝</span></button>
        <div id="help-4" class="help-collapse-body">
            Identity clearance requires a clean security pass. Submit clear front and reverse image uploads of your designated government identity file via the account configuration menu module. Administrative verification loops process active accounts within a standard operational schedule framework.
        </div>
    </div>
</div>

<div id="live-chat-modal" class="modal-mask">
    <div style="background: #060e1d; border: 1px solid var(--border); width: 100%; max-width: 480px; border-radius: 12px; display: flex; flex-direction: column; height: 80vh; box-shadow: 0 10px 30px rgba(0,0,0,0.6); overflow: hidden; position: relative;">
        <div style="display: flex; justify-content: space-between; align-items: center; padding: 15px; background: #0b1528; border-bottom: 1px solid rgba(255,255,255,0.05);">
            <div style="display: flex; align-items: center; gap: 10px;">
                <div style="width: 10px; height: 10px; background: #00ff88; border-radius: 50%; box-shadow: 0 0 8px #00ff88;"></div>
                <h3 style="font-family: 'Orbitron'; color: var(--red); margin: 0; font-size: 14px; letter-spacing: 0.5px;">SECURE SUPPORT NODE</h3>
            </div>
            <span style="color: #7e9bb8; cursor: pointer; font-size: 20px; font-weight: bold;" onclick="closeFinancierModal('live-chat')">&times;</span>
        </div>

        <div id="user-chat-box-stream" class="chat-msg-log" style="flex: 1; overflow-y: auto; padding: 15px; display: flex; flex-direction: column; gap: 10px; background: #040a14; height: auto;"></div>

        <form onsubmit="transmitUserMessageNode(event)" style="padding: 12px; background: #0b1528; border-top: 1px solid rgba(255,255,255,0.05); display: flex; flex-direction: column; gap: 8px;">
            <div style="display: flex; gap: 8px; align-items: center;">
                <input type="text" id="chat-txt-input" placeholder="Type secure message protocol..." style="flex: 1; background: #060e1d; border: 1px solid var(--border); color: #fff; padding: 10px; border-radius: 6px; font-size: 13px; font-family: 'Rajdhani'; outline: none;">
                <button type="submit" style="background: var(--red); border: none; color: #fff; padding: 10px 16px; border-radius: 6px; font-family: 'Orbitron'; font-weight: bold; font-size: 12px; cursor: pointer;">SEND</button>
            </div>
            <div style="display: flex; align-items: center; gap: 5px;">
                <label for="chat-media-input" style="font-size: 11px; color: #7e9bb8; cursor: pointer; display: flex; align-items: center; gap: 4px; font-family: 'Rajdhani';">
                    ЁЯУО <span>Attach Image Proof</span>
                </label>
                <input type="file" id="chat-media-input" accept="image/*" style="display: none;" onchange="document.getElementById('file-chosen-flag').innerText = this.files[0].name">
                <span id="file-chosen-flag" style="font-size: 10px; color: #00ff88; font-family: 'Rajdhani'; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"></span>
            </div>
        </form>
    </div>
</div>

<div class="modal-mask" id="deposit-gateway-modal">
    <div class="stylish-modal-box" style="text-align:left; max-width:440px;">
        <div class="modal-title" style="text-align:center;">Add Money (USDT)</div>
        <form id="deposit-submission-form" onsubmit="submitDepositRequestNode(event)" enctype="multipart/form-data">
            <?php
                $cfg_stmt = $pdo->query("SELECT key_name, value_text FROM system_settings");
                $cfg = $cfg_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
            ?>
            <div class="input-group">
                <label>Payment Method:</label>
                <select class="pair-select" style="width:100%; background:#060e1d; color:#fff; padding:8px; border:1px solid rgba(255,255,255,0.1);"><option>USDT - Tron (TRC20)</option></select>
                <span style="font-size:12px; color:var(--red);">Charge 0%</span>
            </div>
            <div class="input-group">
                <label>Enter Amount (USD):</label>
                <input type="number" id="dep-amount" min="<?= $cfg['min_deposit'] ?? 10 ?>" max="<?= $cfg['max_deposit'] ?? 50000 ?>" placeholder="Min <?= $cfg['min_deposit'] ?? 10 ?> - Max <?= $cfg['max_deposit'] ?? 50000 ?>" required style="background:#060e1d; color:#fff; width:100%; padding:8px; border:1px solid rgba(255,255,255,0.1); border-radius:4px;">
            </div>
            <div style="background:rgba(255,255,255,0.02); padding:12px; border-radius:6px; margin-bottom:15px; border:1px dashed var(--border);">
                <div style="font-size:13px; font-weight:bold; color:white;">Network: <span style="color:var(--red);">Tron (TRC20)</span></div>
                <div style="font-size:12px; word-break:break-all; margin-top:5px; color:var(--text);"><strong>Wallet Address:</strong> <br><span style="color:var(--primary); font-family:'Orbitron';"><?= $cfg['usdt_address'] ?? 'TSR5iPT7ZdwlXhH9EF3kTLjnn4di8FU3boG' ?></span></div>
                <div style="text-align:center; margin-top:10px;">
                    <img src="uploads/<?= $cfg['usdt_qr_code'] ?? 'default_qr.png' ?>" style="max-width:140px; border-radius:4px; border:2px solid white;">
                </div>
            </div>
            <div class="input-group">
                <label>Send screenshot after Transaction:</label>
                <input type="file" id="dep-proof" accept="image/*" required style="color:#fff;">
            </div>
            <div class="modal-btn-grid" style="display:flex; gap:10px; margin-top:15px;">
                <button type="submit" class="modal-act-btn m-btn-confirm" style="flex:1; padding:10px; background:var(--green); color:#000; border:none; border-radius:4px; font-weight:bold; cursor:pointer;">SUBMIT DEPOSIT MATRIX</button>
                <button type="button" class="modal-act-btn m-btn-cancel" onclick="closeGatewayModal('deposit')" style="padding:10px; background:rgba(255,255,255,0.1); color:#fff; border:none; border-radius:4px; cursor:pointer;">DISMISS</button>
            </div>
        </form>
    </div>
</div>

<div class="modal-mask" id="withdrawal-gateway-modal">
    <div class="stylish-modal-box" style="text-align:left; max-width:440px;">
        <div class="modal-title" style="text-align:center; color:var(--red);">Secure Network Withdrawal</div>
        <form id="withdrawal-submission-form" onsubmit="submitWithdrawalRequestNode(event)">
            <div class="input-group">
                <label>Target Payout Network:</label>
                <select class="pair-select" style="width:100%; background:#060e1d; color:#fff; padding:8px; border:1px solid rgba(255,255,255,0.1);"><option>USDT (TRC20)</option></select>
            </div>
            <div class="input-group">
                <label>Withdrawal Amount ($):</label>
                <input type="number" id="with-amount" min="<?= $cfg['min_withdrawal'] ?? 15 ?>" max="<?= $cfg['max_withdrawal'] ?? 20000 ?>" placeholder="Min <?= $cfg['min_withdrawal'] ?? 15 ?> - Max <?= $cfg['max_withdrawal'] ?? 20000 ?>" required style="background:#060e1d; color:#fff; width:100%; padding:8px; border:1px solid rgba(255,255,255,0.1); border-radius:4px;">
            </div>
            <div class="input-group">
                <label>Your USDT (TRC20) Destination Address:</label>
                <input type="text" id="with-address" placeholder="T..." required style="background:#060e1d; color:#fff; width:100%; padding:8px; border:1px solid rgba(255,255,255,0.1); border-radius:4px;">
            </div>
            <div class="modal-btn-grid" style="display:flex; gap:10px; margin-top:15px;">
                <button type="submit" class="modal-act-btn m-btn-confirm" style="background:var(--red); color:white; flex:1; padding:10px; border:none; border-radius:4px; font-weight:bold; cursor:pointer;">REQUEST DISBURSEMENT</button>
                <button type="button" class="modal-act-btn m-btn-cancel" onclick="closeGatewayModal('withdrawal')" style="padding:10px; background:rgba(255,255,255,0.1); color:#fff; border:none; border-radius:4px; cursor:pointer;">CANCEL</button>
            </div>
        </form>
    </div>
</div>

<div class="modal-mask" id="custom-alert-modal">
    <div class="stylish-modal-box">
        <div class="modal-title" id="m-box-title">Response Alert</div>
        <div class="modal-body-text" id="m-box-body">Processing order node details.</div>
        <div class="modal-btn-grid">
            <button class="modal-act-btn m-btn-confirm" id="m-btn-yes">OK</button>
            <button class="modal-act-btn m-btn-cancel" onclick="closeModalWindow()">CANCEL</button>
        </div>
    </div>
</div>

<div class="modal-mask" id="kyc-manager-modal">
    <div class="stylish-modal-box" style="max-width:480px; text-align:left;">
        <div class="modal-title" style="text-align:center;">Identification Verification (KYC)</div>
        <div class="modal-body-text">Current Identity Status: <strong style="color:var(--primary); text-transform:uppercase;"><?= $userData['kyc_status'] ?></strong></div>
        <?php if($userData['kyc_status'] === 'none' || $userData['kyc_status'] === 'rejected'): ?>
            <form id="kyc-submit-form" onsubmit="uploadKYCDocument(event)">
                <input type="file" id="kyc_doc" name="kyc_doc" accept="image/*" required style="margin-bottom:15px; color:#fff;">
                <button type="submit" style="width:100%; padding:10px; background:var(--primary); color:var(--darker); font-family:'Orbitron'; font-weight:bold; cursor:pointer; border:none; border-radius:4px;">SUBMIT VERIFICATION</button>
            </form>
        <?php else: ?>
            <div style="padding:12px; background:rgba(0,255,136,0.1); border:1px solid var(--green); color:var(--green); border-radius:6px; font-weight:bold; text-align:center;">
                <?php if($userData['kyc_status'] === 'approved'): ?> Verified Identity Approved Secure Entity.<?php else: ?> Review loops active.<?php endif; ?>
            </div>
        <?php endif; ?>
        <button class="modal-act-btn m-btn-cancel" onclick="closeKYCModal()" style="width:100%; margin-top:10px; padding:8px; background:rgba(255,255,255,0.1); color:#fff; border:none; border-radius:4px; cursor:pointer;">CLOSE WINDOW</button>
    </div>
</div>

<div class="modal-mask" id="password-manager-modal">
    <div class="stylish-modal-box" style="max-width:440px; text-align:left;">
        <div class="modal-title" style="text-align:center;">AUTHENTICATION MUTATION (PASSWORD)</div>
        <form id="password-mutation-form" onsubmit="executePasswordChangeUpdate(event)">
            <div class="input-group">
                <div class="input-group">
                    <label>Current Old Password</label>
                    <input type="password" id="pass-old" placeholder="тАвтАвтАвтАвтАвтАвтАвтАв" required style="color:#fff;">
                </div>
                <div class="input-group">
                    <label>New Secure Password</label>
                    <input type="password" id="pass-new" placeholder="тАвтАвтАвтАвтАвтАвтАвтАв" required style="color:#fff;">
                </div>
                <div class="input-group">
                    <label>Confirm New Password</label>
                    <input type="password" id="pass-confirm" placeholder="тАвтАвтАвтАвтАвтАвтАвтАв" required style="color:#fff;">
                </div>
            </div>
            <div class="modal-btn-grid" style="margin-top:20px;">
                <button type="submit" class="modal-act-btn m-btn-confirm" style="flex:1;">UPDATE SYSTEM CREDENTIALS</button>
                <button type="button" class="modal-act-btn m-btn-cancel" onclick="closePasswordModalWindow()">DISMISS</button>
            </div>
        </form>
    </div>
</div>

<div class="fixed-bottom-bar">
    <div class="bottom-nav-item active" id="btn-nav-home" onclick="switchView('home')">Home</div>
    <div class="bottom-nav-item" id="btn-nav-trade" onclick="switchView('trade')">Trade</div>
    <div class="bottom-nav-item" id="btn-nav-history" onclick="switchView('history')">History</div>
    <div class="bottom-nav-item" id="btn-nav-assets" onclick="switchView('assets')">Assets</div>
</div>

<script>
    let chart, candleSeries;
    let currentSymbol = 'BTCUSDT';
    let currentTimeframe = '1m';
    let currentLivePrice = 0;

    function toggleDropdown() {
        const drop = document.getElementById('nav-dropdown');
        drop.style.display = drop.style.display === 'block' ? 'none' : 'block';
    }

    window.onclick = function(event) {
        if (!event.target.matches('.three-dots-btn')) {
            const dropdown = document.getElementById('nav-dropdown');
            if (dropdown) dropdown.style.display = 'none';
        }
    }

    function openKYCModal() { document.getElementById('kyc-manager-modal').style.display = 'flex'; }
    function closeKYCModal() { document.getElementById('kyc-manager-modal').style.display = 'none'; }
    
    function openPasswordModalWindow() { document.getElementById('password-manager-modal').style.display = 'flex'; }
    function closePasswordModalWindow() { document.getElementById('password-manager-modal').style.display = 'none'; document.getElementById('password-mutation-form').reset(); }

    function openModalWindow(title, message, confirmCallback) {
        document.getElementById('m-box-title').innerText = title;
        document.getElementById('m-box-body').innerText = message;
        document.getElementById('custom-alert-modal').style.display = 'flex';
        document.getElementById('m-btn-yes').onclick = function() { confirmCallback(); closeModalWindow(); };
    }
    function closeModalWindow() { document.getElementById('custom-alert-modal').style.display = 'none'; }

    function executePasswordChangeUpdate(e) {
        e.preventDefault();
        const oldP = document.getElementById('pass-old').value;
        const newP = document.getElementById('pass-new').value;
        const confP = document.getElementById('pass-confirm').value;

        const formData = new FormData();
        formData.append('old_password', oldP);
        formData.append('new_password', newP);
        formData.append('confirm_password', confP);

        fetch('api/change_password.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(res => {
                openModalWindow("Security Ledger Response", res.message, () => {
                    if(res.status === 'success') closePasswordModalWindow();
                });
            });
    }

    function uploadKYCDocument(e) {
        e.preventDefault();
        const fileInput = document.getElementById('kyc_doc');
        const formData = new FormData();
        formData.append('kyc_doc', fileInput.files[0]);
        fetch('api/kyc_upload.php', { method: 'POST', body: formData }).then(res => res.json()).then(res => { alert(res.message); location.reload(); });
    }

    function switchView(target) {
        document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
        document.querySelectorAll('.bottom-nav-item').forEach(el => el.classList.remove('active'));
        document.getElementById(`view-${target}`).classList.add('active');
        document.getElementById(`btn-nav-${target}`).classList.add('active');
        if (target === 'trade' && !chart) { setTimeout(initChart, 200); }
        if (target === 'history') { loadHistoryLedger(); }
    }

    function initChart() {
        const container = document.getElementById('chart-container');
        if(!container) return;
        chart = LightweightCharts.createChart(container, {
            width: container.offsetWidth, height: 400,
            layout: { background: { color: '#0b1528' }, textColor: '#c8d8e8' },
            grid: { vertLines: { color: 'rgba(0,212,255,0.01)' }, horzLines: { color: 'rgba(0,212,255,0.01)' } }
        });
        candleSeries = chart.addSeries(LightweightCharts.CandlestickSeries, { upColor: '#00ff88', downColor: '#ff3366' });
        fetchChartData(true);
    }

    function fetchChartData(isInitialLoad = false) {
        // Dynamic multi-pair endpoint alignment check
        fetch(`api/prices.php?symbol=${currentSymbol}&interval=${currentTimeframe}&limit=120`)
            .then(res => res.json()).then(data => {
                if (data && data.length > 0) {
                    const cleanData = data.map(item => ({
                        time: parseInt(item.time), open: parseFloat(item.open), high: parseFloat(item.high), low: parseFloat(item.low), close: parseFloat(item.close)
                    }));
                    
                    if (isInitialLoad && chart) {
                        candleSeries.setData(cleanData); chart.timeScale().fitContent();
                    } else if (chart) {
                        const latestTick = cleanData[cleanData.length - 1];
                        candleSeries.update(latestTick);
                    }
                    
                    currentLivePrice = cleanData[cleanData.length - 1].close;
                    document.getElementById('price-ticker').innerText = `${currentSymbol}: $${currentLivePrice.toFixed(2)}`;
                    if (typeof calculateAutomaticMargin === 'function') { calculateAutomaticMargin(); }

                    // Sync corresponding ticker nodes dynamic loops
                    let fallbackTickerId = currentSymbol.replace('USDT', '').toLowerCase();
                    let targetMarqueeNode = document.getElementById(`marquee-${fallbackTickerId}`);
                    if (targetMarqueeNode) targetMarqueeNode.innerText = `$${currentLivePrice.toFixed(2)}`;
                    
                    let targetRowNode = document.getElementById(`row-price-${fallbackTickerId}`);
                    if (targetRowNode) targetRowNode.innerText = `$${currentLivePrice.toFixed(2)}`;
                }
            })
            .catch(err => console.error("Stream exception caught:", err));

        // Background pipeline execution thread for all secondary tracking vectors
        const secondaryAssetsList = ['BTC', 'ETH', 'BNB', 'SOL', 'XRP', 'ADA', 'DOGE', 'DOT', 'AVAX'];
        secondaryAssetsList.forEach(asset => {
            let sym = asset + 'USDT';
            if (sym === currentSymbol) return; // Active chart already handled up

            fetch(`api/prices.php?symbol=${sym}&interval=1m&limit=1`)
                .then(res => res.json()).then(data => {
                    if(data && data[0]) {
                        const price = parseFloat(data[0].close).toFixed(2);
                        let nodeKey = asset.toLowerCase();
                        if(document.getElementById(`marquee-${nodeKey}`)) document.getElementById(`marquee-${nodeKey}`).innerText = `$${price}`;
                        if(document.getElementById(`row-price-${nodeKey}`)) document.getElementById(`row-price-${nodeKey}`).innerText = `$${price}`;
                    }
                }).catch(e => {});
        });
    }

    function executeTrade(side) {
        const totalAmount = document.getElementById('trade-amount-input').value;
        const leverage = document.getElementById('leverage-select').value;
        
        const lotInput = document.getElementById('trade-lot-size');
        const lotSize = lotInput ? parseInt(lotInput.value) || 1 : 1;

        openModalWindow("Confirm Order Execution", `Are you sure you want to open a single position with Volume: ${lotSize} Lot(s)?`, () => {
            const formData = new FormData();
            formData.append('action', 'open');
            formData.append('symbol', currentSymbol);
            formData.append('type', side);
            formData.append('amount', lotSize);
            formData.append('leverage', leverage);
            formData.append('current_price', currentLivePrice);

            fetch('api/trade.php', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(res => {
                    openModalWindow("Order Response", res.message, () => {
                        location.reload();
                    });
                })
                .catch(err => {
                    console.error("Trade request failed:", err);
                    location.reload();
                });
        });
    }

    function fetchActivePositions() {
        fetch('api/positions.php')
            .then(res => res.json()).then(trades => {
                const tbody = document.getElementById('positions-list-body');
                if (!trades || trades.length === 0) {
                    tbody.innerHTML = `<tr><td colspan="8" style="text-align:center; color:gray;">No active metrics.</td></tr>`;
                    return;
                }
                let html = '';
               trades.forEach(trade => {
    const entryPrice = parseFloat(trade.entry_price) || 0; 
    let amount = parseFloat(trade.amount) || 1; 
    const lev = parseInt(trade.leverage) || 1;
    
    let pointMultiplier = 10.00; 
    switch (lev) {
        case 200: pointMultiplier = 0.50; break;
        case 100: pointMultiplier = 1.00; break;
        case 75:  pointMultiplier = 25.00; break;
        case 50:  pointMultiplier = 50.00; break;
        case 25:  pointMultiplier = 75.00; break;
        case 1:
        default:  pointMultiplier = 10.00; break;
    }

    // Dynamic price match mapping across multiple index entities safely
    let dynamicTrackedPrice = currentLivePrice;
    if (trade.symbol !== currentSymbol) {
        let lookupKey = trade.symbol.replace('USDT', '').toLowerCase();
        let backgroundTicker = document.getElementById(`marquee-${lookupKey}`) || document.getElementById(`row-price-${lookupKey}`);
        if (backgroundTicker) {
            let parsedVal = parseFloat(backgroundTicker.innerText.replace(/[^0-9.]/g, ''));
            if (!isNaN(parsedVal) && parsedVal > 0) dynamicTrackedPrice = parsedVal;
        }
    }

    let priceDiff = dynamicTrackedPrice - entryPrice;
    let pnl = 0;
    if (trade.type === 'buy') {
        pnl = priceDiff * pointMultiplier * amount;
    } else {
        pnl = (priceDiff * -1) * pointMultiplier * amount;
    }
    
    let dynamicCalculatedMargin = (entryPrice / lev) * amount;
    if (trade.margin) {
        dynamicCalculatedMargin = parseFloat(trade.margin);
    } else if (amount > 500) {
        dynamicCalculatedMargin = amount;
        amount = 1; 
    }
    
    html += `<tr>
        <td>${trade.symbol}</td>
        <td style="color:${trade.type==='buy'?'var(--green)':'var(--red)'}; font-weight:bold;">${trade.type.toUpperCase()}</td>
        <td>${lev}x</td>
        <td style="font-family:'Orbitron'; font-weight:bold; color:var(--primary);">${amount} Lot(s)</td>
        <td>$${dynamicCalculatedMargin.toFixed(2)}</td>
        <td>$${entryPrice.toFixed(2)}</td>
        <td style="color:${pnl>=0?'var(--green)':'var(--red)'}; font-weight:bold;">$${pnl.toFixed(2)}</td>
        <td><button class="close-action-btn" onclick="triggerCloseModal(${trade.id})">CLOSE</button></td>
    </tr>`;
// Har trade ka floating P&L array loop ke global sum variable mein calculate hoga
                });
                tbody.innerHTML = html;
                
                // тЪЩя╕П REAL-TIME DYNAMIC WALLET MULTIPLIER BALANCE SYNC
                let balanceElement = document.getElementById('live-profile-balance');
                if (balanceElement) {
                    let baseWalletBalance = parseFloat(balanceElement.getAttribute('data-base-balance')) || 0;
                    
                    // Saari open positions ka absolute P&L scan vector sum calculate karein
                    let totalFloatingPnL = 0;
                    let rows = tbody.getElementsByTagName('tr');
                    for (let i = 0; i < rows.length; i++) {
                        let pnlCell = rows[i].cells[6]; // 7th Column yaani Live P&L
                        if (pnlCell) {
                            let textVal = pnlCell.innerText.replace('$', '').trim();
                            let currentCellPnL = parseFloat(textVal);
                            if (!isNaN(currentCellPnL)) {
                                totalFloatingPnL += currentCellPnL;
                            }
                        }
                    }
                    
                    // Main layout account global header string inject matrix recalculation
                    let adaptiveNetEquity = baseWalletBalance + totalFloatingPnL;
                    balanceElement.innerText = '$' + adaptiveNetEquity.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    
                    // Dynamic styling nodes shifting matrix coloring
                    if (totalFloatingPnL > 0) {
                        balanceElement.style.color = 'var(--green)';
                    } else if (totalFloatingPnL < 0) {
                        balanceElement.style.color = 'var(--red)';
                    } else {
                        balanceElement.style.color = 'var(--green)';
                    }
                }
            });
    }

    function triggerCloseModal(tradeId) {
        openModalWindow("Confirm Position Exit", "Are you sure you want to completely liquidate and close this trade position at the current synchronized market index rates?", () => {
            const formData = new FormData();
            formData.append('action', 'close'); formData.append('trade_id', tradeId); formData.append('close_price', currentLivePrice);
            fetch('api/trade.php', { method: 'POST', body: formData }).then(() => { location.reload(); });
        });
    }

function loadHistoryLedger() {
    fetch('api/user_history.php')
        .then(res => res.json()).then(data => {
            const container = document.getElementById('history-table-body');
            if (!container) return;
            
            let html = '';
            
            if (!data || data.length === 0) {
                html = `<div style="text-align:center; padding:20px; color:gray; font-family:'Orbitron';">No past logs found.</div>`;
            } else {
                data.forEach(t => {
                    let pnlVal = parseFloat(t.profit_loss) || 0;
                    let entryP = parseFloat(t.entry_price) || 0;
                    let exitP = parseFloat(t.close_price) || 0;
                    let lots = parseFloat(t.amount) || 1; 
                    let lev = parseInt(t.leverage) || 1;
                    
                    let initialMargin = (entryP / lev) * lots;
                    let platformFee = pnlVal > 0 ? pnlVal * 0.20 : 0;
                    
                    let pnlColor = pnlVal >= 0 ? 'var(--green)' : 'var(--red)';
                    let typeColor = t.type === 'buy' ? 'var(--green)' : 'var(--red)';

                    html += `
                    <div style="background:var(--card); border:1px solid var(--primary); border-radius:12px; padding:15px; margin-bottom:15px; box-shadow:0 4px 15px rgba(0,0,0,0.2); box-sizing:border-box; width:100%; white-space:normal; text-align:left;">
                        <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid rgba(255,255,255,0.05); padding-bottom:8px; margin-bottom:10px;">
                            <span style="font-family:'Orbitron'; font-weight:bold; color:#fff; font-size:15px;">${t.symbol}</span>
                            <span style="background:rgba(255,255,255,0.05); border:1px solid ${typeColor}; color:${typeColor}; padding:2px 8px; border-radius:4px; font-family:'Orbitron'; font-size:11px; font-weight:bold;">${t.type.toUpperCase()} ${lev}x</span>
                        </div>
                        <div style="display:flex; flex-direction:column; gap:8px; font-family:'Rajdhani'; font-size:14px;">
                            <div style="display:flex; justify-content:space-between; align-items:center;">
                                <div style="color:#7e9bb8;">Volume Factor: <span style="font-family:'Orbitron'; font-weight:bold; color:#fff; margin-left:5px;">${lots} Lot(s)</span></div>
                                <div style="color:#7e9bb8;">Net Gains: <span style="font-family:'Orbitron'; font-weight:bold; color:${pnlColor}; margin-left:5px;">$${pnlVal.toFixed(2)}</span></div>
                            </div>
                            <div style="display:flex; justify-content:space-between; align-items:center;">
                                <div style="color:#7e9bb8;">Open Rate: <span style="font-family:'Orbitron'; color:#fff; margin-left:5px;">$${entryP.toFixed(2)}</span></div>
                                <div style="color:#7e9bb8;">Close Rate: <span style="font-family:'Orbitron'; color:#fff; margin-left:5px;">$${exitP.toFixed(2)}</span></div>
                            </div>
                            <div style="display:flex; justify-content:space-between; align-items:center;">
                                <div style="color:#7e9bb8;">Margin Invested: <span style="font-family:'Orbitron'; color:var(--primary); margin-left:5px;">$${initialMargin.toFixed(2)}</span></div>
                                <div style="color:#7e9bb8;">Broker Fees (20%): <span style="font-family:'Orbitron'; color:var(--red); margin-left:5px;">$${platformFee.toFixed(2)}</span></div>
                            </div>
                            <div style="display:flex; justify-content:space-between; align-items:center; border-top:1px solid rgba(255,255,255,0.03); padding-top:6px; margin-top:4px; font-size:12px;">
                                <div style="color:#526e8c;">Opened: <span style="color:#a4b8cc; margin-left:3px;">${t.opened_at}</span></div>
                                <div style="color:#526e8c;">Closed: <span style="color:#a4b8cc; margin-left:3px;">${t.closed_at ? t.closed_at : '-'}</span></div>
                            </div>
                        </div>
                    </div>`;
                });
            }

            // Purane table element wrapper ko override karke solid box list inject karna
            let parentCardBlock = container.closest('.data-card');
            if (parentCardBlock) {
                parentCardBlock.innerHTML = `<h3 style="font-family:'Orbitron'; color:var(--primary); margin:0 0 15px 0; font-size:16px;">Account Personal Statement History Ledger</h3><div style="width:100%; max-height:60vh; overflow-y:auto; padding-right:4px; box-sizing:border-box;">${html}</div>`;
            } else {
                container.innerHTML = html;
            }
        });
}
    
    function openGatewayModal(type) {
        document.getElementById(`${type}-gateway-modal`).style.display = 'flex';
    }
    function closeGatewayModal(type) {
        document.getElementById(`${type}-gateway-modal`).style.display = 'none';
        document.getElementById(`${type}-submission-form`).reset();
    }

    function submitDepositRequestNode(e) {
        e.preventDefault();
        const amt = document.getElementById('dep-amount').value;
        const fileInput = document.getElementById('dep-proof');
        
        const formData = new FormData();
        formData.append('action', 'user_deposit');
        formData.append('amount', amt);
        formData.append('proof_img', fileInput.files[0]);

        fetch('api/assets_handler.php', { method: 'POST', body: formData })
            .then(res => res.json()).then(res => {
                openModalWindow("System Ledger Notification", res.message, () => {
                    if(res.status === 'success') {
                        closeGatewayModal('deposit');
                        location.reload();
                    }
                });
            });
    }

    function submitWithdrawalRequestNode(e) {
        e.preventDefault();
        const amt = document.getElementById('with-amount').value;
        const addr = document.getElementById('with-address').value;

        const formData = new FormData();
        formData.append('action', 'user_withdrawal');
        formData.append('amount', amt);
        formData.append('address', addr);

        fetch('api/assets_handler.php', { method: 'POST', body: formData })
            .then(res => res.json()).then(res => {
                openModalWindow("System Ledger Notification", res.message, () => {
                    if(res.status === 'success') {
                        closeGatewayModal('withdrawal');
                        location.reload();
                    }
                });
            });
    }
function changePair() {
        currentSymbol = document.getElementById('pair-selector').value;
        
        // Fresh initialization dynamic pairs ke liye container refresh logic
        const container = document.getElementById('chart-container');
        if (container) {
            container.innerHTML = '';
            chart = null;
            candleSeries = null;
        }
        initChart();
    }

    function changeTimeframe(tf, btn) {
        currentTimeframe = tf;
        document.querySelectorAll('.tf-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        
        const container = document.getElementById('chart-container');
        if (container) {
            container.innerHTML = '';
            chart = null;
            candleSeries = null;
        }
        initChart();
    }

    document.addEventListener("DOMContentLoaded", () => {
        setInterval(() => {
            fetchChartData(false);
            if(document.getElementById('view-trade').classList.contains('active')) { fetchActivePositions(); }
        }, 2000);
    });

    function openFinancierModal(target) {
        var targetModal = document.getElementById(target + '-modal');
        if (targetModal) {
            targetModal.style.setProperty('display', 'flex', 'important');
            
            if (target === 'tx-ledger') { 
                loadCombinedTxLedgerLogs(); 
            } else if (target === 'live-chat') { 
                loadLiveChatLogs(); 
            }
        } else {
            console.error("Target missing: " + target + "-modal");
        }
    }

    function closeFinancierModal(target) {
        var targetModal = document.getElementById(target + '-modal');
        if (targetModal) {
            targetModal.style.setProperty('display', 'none', 'important');
        }
    }

    // Help Toggle Logic
    function toggleHelpSection(id) {
        var section = document.getElementById(id);
        if (section) {
            var isVisible = section.style.display === 'block';
            document.querySelectorAll('.help-collapse-body').forEach(b => b.style.display = 'none');
            section.style.display = isVisible ? 'none' : 'block';
        }
    }

    function loadCombinedTxLedgerLogs() {
        var tbody = document.getElementById('combined-tx-rows');
        if (!tbody) return;
        
        tbody.innerHTML = `<tr><td colspan="4" style="text-align:center; padding:15px; color:#7e9bb8; font-family:'Orbitron';">Syncing system ledger nodes...</td></tr>`;
        
        fetch('api/assets_handler.php?action=fetch_combined_statement')
            .then(res => res.json())
            .then(data => {
                if (!data || data.length === 0) {
                    tbody.innerHTML = `<tr><td colspan="4" style="text-align:center; padding:15px; color:gray; font-family:'Orbitron';">No ledger records found.</td></tr>`;
                    return;
                }
                let html = '';
                data.forEach(tx => {
                    let typeLabel = '', typeColor = '', statusColor = '#e0a816';
                    
                    if (tx.type === 'deposit') { typeLabel = 'DEPOSIT'; typeColor = '#00ff88'; }
                    else if (tx.type === 'withdrawal') { typeLabel = 'WITHDRAWAL'; typeColor = '#ff3366'; }
                    else if (tx.type === 'trade_profit') { typeLabel = 'PROFIT'; typeColor = '#00ff88'; }
                    else if (tx.type === 'trade_loss') { typeLabel = 'LOSS'; typeColor = '#ff3366'; }

                    if (['completed', 'approved', 'success'].includes(tx.status)) { statusColor = '#00ff88'; }
                    else if (['rejected', 'failed'].includes(tx.status)) { statusColor = '#ff3366'; }

                    html += `
                    <tr style="border-bottom: 1px solid rgba(255,255,255,0.05); font-family:'Rajdhani'; font-size:14px;">
                        <td style="padding: 10px 5px; color: #7e9bb8;">${tx.date}</td>
                        <td style="color: ${typeColor}; font-weight: bold;">${typeLabel}</td>
                        <td style="font-family: 'Orbitron'; font-weight: bold; color: #fff;">$${parseFloat(tx.amount).toFixed(2)}</td>
                        <td style="text-transform: uppercase; font-weight: bold; color: ${statusColor}; font-size: 11px; font-family:'Orbitron';">${tx.status}</td>
                    </tr>`;
                });
                tbody.innerHTML = html;
            })
            .catch(err => {
                tbody.innerHTML = `<tr><td colspan="4" style="text-align:center; padding:15px; color:#ff3366;">Ledger pipeline sync error.</td></tr>`;
            });
    }

    function loadLiveChatLogs() {
        var chatBox = document.getElementById('user-chat-box-stream');
        if (!chatBox) return;
        
        fetch('api/assets_handler.php?action=get_chat_stream')
            .then(res => res.json())
            .then(data => {
                chatBox.innerHTML = '';
                data.forEach(msg => {
                    var isUser = msg.sender === 'user';
                    var bubbleClass = isUser ? 'user-side' : 'admin-side';
                    var mediaHtml = msg.media_file ? `<br><img src="uploads/${msg.media_file}" style="max-width:100%; border-radius:6px; margin-top:5px;">` : '';
                    
                    chatBox.innerHTML += `
                        <div class="chat-bubble ${bubbleClass}" style="margin-bottom: 8px;">
                            <div>${msg.message_text}</div>
                            ${mediaHtml}
                            <div style="font-size:9px; opacity:0.5; text-align:right; margin-top:3px;">${msg.created_at}</div>
                        </div>`;
                });
                chatBox.scrollTop = chatBox.scrollHeight;
            });
    }

    function transmitUserMessageNode(e) {
        e.preventDefault();
        var input = document.getElementById('chat-txt-input');
        var fileInput = document.getElementById('chat-media-input');
        if (!input || (!input.value.trim() && !fileInput.files[0])) return;

        var formData = new FormData();
        formData.append('action', 'send_chat_message');
        formData.append('msg', input.value.trim());
        if (fileInput.files[0]) { formData.append('chat_media', fileInput.files[0]); }

        fetch('api/assets_handler.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(res => {
                if (res.status === 'success') {
                    input.value = '';
                    fileInput.value = '';
                    document.getElementById('file-chosen-flag').innerText = '';
                    loadLiveChatLogs();
                }
            });
    }
    
    function keepWebsiteAliveSilently() {
        if (typeof loadLiveChatLogs === 'function') {
            loadLiveChatLogs();
        }
        fetch(window.location.href, { 
            method: 'GET', 
            headers: { 'X-Requested-With': 'XMLHttpRequest' } 
        })
        .then(response => {
            console.log("Web3 Network Loop: Active & Alive (Silent Sync)");
        })
        .catch(error => {
            console.log("Connection glitch bypassed smoothly.");
        });
    }

    setInterval(keepWebsiteAliveSilently, 2000);

    function calculateAutomaticMargin() {
        if (currentLivePrice <= 0) return;
        
        let leverageInput = document.getElementById('leverage-select');
        let selectedLeverage = leverageInput ? parseInt(leverageInput.value) : 1;
        
        let lotInput = document.getElementById('trade-lot-size');
        let lotSize = lotInput ? parseInt(lotInput.value) || 1 : 1;
        
        let baselineMargin = currentLivePrice;

        switch (selectedLeverage) {
            case 200: baselineMargin = currentLivePrice / 200; break;
            case 100: baselineMargin = currentLivePrice / 100; break;
            case 75:  baselineMargin = currentLivePrice / 4; break;
            case 50:  baselineMargin = currentLivePrice / 2; break;
            case 25:  baselineMargin = currentLivePrice / 1.333333; break;
            case 1:
            default:  baselineMargin = currentLivePrice; break;
        }

        let finalCalculatedMargin = baselineMargin * lotSize;

        let marginInputBox = document.getElementById('trade-amount-input');
        if (marginInputBox) {
            marginInputBox.value = finalCalculatedMargin.toFixed(2);
        }
    }

    if(document.getElementById('leverage-select')) {
        document.getElementById('leverage-select').addEventListener('change', calculateAutomaticMargin);
    }
    if(document.getElementById('trade-lot-size')) {
        document.getElementById('trade-lot-size').addEventListener('input', calculateAutomaticMargin);
    }
  // ==========================================
    // 🔥 ULTIMATE GLOBAL MEMORY INJECTION FOR DEMO NETWORKS
    // ==========================================
    const userIsDemoAccount = <?php echo (isset($_SESSION['is_demo']) && $_SESSION['is_demo'] === true) ? 'true' : 'false'; ?>;

    if (userIsDemoAccount) {
        // 1. Core Window Object Mutation
        window.user_balance = 10000000.00;
        window.available_balance = 10000000.00;
        window.balance = 10000000.00;
        
        if (typeof window.userData === 'undefined') {
            window.userData = { balance: 10000000.00 };
        } else {
            window.userData.balance = 10000000.00;
        }

        // 2. Loop checker to completely freeze values against frontend scripts
        setInterval(() => {
            window.user_balance = 10000000.00;
            window.balance = 10000000.00;
            window.available_balance = 10000000.00;
            if (window.userData) window.userData.balance = 10000000.00;
            if (typeof window.insufficient_flag !== 'undefined') { window.insufficient_flag = false; }
            
            // Hard Reset element text in the UI dynamically
            const targetSelectors = ['.user-balance', '#user-balance', '.balance-amount', '#live-profile-balance'];
            targetSelectors.forEach(selector => {
                const el = document.querySelector(selector);
                if (el && el.innerText !== "$10,000,000.00") {
                    el.innerText = "$10,000,000.00";
                }
            });
        }, 300);
    }
</script>
</body>
</html>