<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'];

// Verify Role Access
if ($role_code !== 'HEAD_NURSE' && $role_code !== 'ENT_NURSE') {
    $redirect_url = match ($role_code) {
        'SUPER_ADMIN', 'HOSPITAL_ADMIN' => 'admin_dashboard.php',
        'ENT_CONSULTANT', 'ENT_DOCTOR' => 'doctor_dashboard.php',
        'RESIDENT_DOCTOR' => 'resident_dashboard.php',
        'AUDIOLOGIST' => 'audiologist_dashboard.php',
        'LAB_TECHNICIAN' => 'lab_dashboard.php',
        'RECEPTIONIST' => 'reception_dashboard.php',
        'BILLING_CLERK' => 'billing_dashboard.php',
        'MEDICAL_RECORDS' => 'records_dashboard.php',
        'PATIENT' => 'patient_portal.php',
        default => 'index.php'
    };
    header("Location: $redirect_url");
    exit();
}

// Fetch user details
$sql_user_details = "SELECT full_name FROM users WHERE user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$val = $stmt_user->get_result()->fetch_assoc();
$full_name = $val['full_name'];

$metrics = [];
$today = date('Y-m-d');

// Patients needing vital signs today
$vitals_needed_sql = "SELECT COUNT(*) as count FROM patient_queue
                     WHERE DATE(queue_entry_time) = ? 
                     AND queue_status IN ('WAITING', 'IN_SERVICE')
                     AND department_id = 2
                     AND vitals_taken = 0";
$stmt = $conn->prepare($vitals_needed_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['vitals_needed'] = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// Procedures I'm assisting with today
$assisting_procedures_sql = "SELECT COUNT(*) as count FROM patient_procedures 
                            WHERE DATE(procedure_date) = ? 
                            AND status IN ('SCHEDULED', 'PREPARING', 'IN_PROGRESS')";
$stmt = $conn->prepare($assisting_procedures_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['assisting_procedures'] = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// Patients in triage queue today
$triage_queue_sql = "SELECT COUNT(*) as count FROM patient_queue
                    WHERE DATE(queue_entry_time) = ?
                    AND department_id = 2
                    AND queue_status IN ('WAITING', 'IN_SERVICE')";
$stmt = $conn->prepare($triage_queue_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['triage_queue'] = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// Patients completed today
$completed_today_sql = "SELECT COUNT(*) as count FROM patient_queue
                       WHERE DATE(queue_entry_time) = ?
                       AND department_id = 2
                       AND queue_status = 'COMPLETED'";
$stmt = $conn->prepare($completed_today_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['completed_today'] = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// Get triage queue details
$triage_details_sql = "SELECT 
    q.queue_id,
    q.queue_number,
    q.patient_id,
    q.patient_name,
    q.patient_number,
    q.age,
    q.gender,
    q.phone_number,
    q.chief_complaint,
    q.triage_category,
    q.priority,
    q.queue_status,
    q.vitals_taken,
    q.queue_entry_time,
    TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) as wait_minutes,
    q.position_in_queue
FROM patient_queue q
WHERE DATE(q.queue_entry_time) = ?
AND q.department_id = 2
AND q.queue_status IN ('WAITING', 'IN_SERVICE')
ORDER BY 
    CASE q.priority
        WHEN 'EMERGENCY' THEN 1
        WHEN 'URGENT' THEN 2
        WHEN 'NORMAL' THEN 3
    END,
    q.queue_entry_time
LIMIT 10";

$stmt = $conn->prepare($triage_details_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$triage_queue_result = $stmt->get_result();

// Get initial queue IDs for JavaScript
$initial_queue_ids = [];
while ($row = $triage_queue_result->fetch_assoc()) {
    $initial_queue_ids[] = $row['queue_id'];
}
// Reset result pointer for later use
$triage_queue_result->data_seek(0);

?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Nursing Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .welcome-header {
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .metric-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s;
            height: 100%;
        }

        .metric-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .metric-title {
            font-size: 0.875rem;
            font-weight: 600;
            color: #64748b;
            margin: 0;
        }

        .metric-icon {
            font-size: 1.5rem;
            float: right;
        }

        .metric-value {
            font-size: 2rem;
            font-weight: 700;
            color: #66CDAA;
            margin-top: 0.5rem;
        }

        .metric-change {
            font-size: 0.875rem;
            color: #64748b;
            margin-top: 0.25rem;
        }

        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .quick-action {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            text-align: center;
            border: 1px solid #e2e8f0;
            text-decoration: none;
            color: inherit;
            transition: all 0.2s;
        }

        .quick-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            border-color: #66CDAA;
        }

        .quick-action-icon {
            font-size: 2rem;
            margin-bottom: 0.5rem;
            display: block;
            color: #66CDAA;
        }

        .quick-action-title {
            font-weight: 600;
            margin-bottom: 0.25rem;
            color: #334155;
        }

        .quick-action-desc {
            font-size: 0.875rem;
            color: #64748b;
            margin: 0;
        }
        
        .triage-queue-card {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .triage-queue-header {
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            color: white;
            padding: 1.5rem;
        }
        
        .patient-queue-item {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.2s;
            cursor: pointer;
        }
        
        .patient-queue-item:hover {
            background: #f8fafc;
        }
        
        .patient-queue-item:last-child {
            border-bottom: none;
        }
        
        .queue-patient-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .queue-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
        }
        
        .queue-details {
            flex: 1;
        }
        
        .queue-patient-name {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .queue-patient-meta {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .queue-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .priority-normal {
            background: #dcfce7;
            color: #166534;
        }
        
        .priority-urgent {
            background: #fef3c7;
            color: #92400e;
        }
        
        .priority-emergency {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .status-waiting {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-in-service {
            background: #fef3c7;
            color: #92400e;
        }
        
        .vitals-indicator {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .vitals-done {
            color: #10b981;
        }
        
        .vitals-pending {
            color: #f59e0b;
        }
        
        .empty-queue {
            text-align: center;
            padding: 2rem;
            color: #64748b;
        }
        
        .empty-queue i {
            font-size: 3rem;
            opacity: 0.3;
            margin-bottom: 1rem;
        }
        
        .view-all-link {
            display: block;
            text-align: center;
            padding: 1rem;
            background: #f8fafc;
            color: #66CDAA;
            font-weight: 600;
            text-decoration: none;
            transition: background 0.2s;
        }
        
        .view-all-link:hover {
            background: #f1f5f9;
        }
        
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <div class="welcome-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2>Nurse <?php echo htmlspecialchars($full_name); ?></h2>
                                <p>Nursing Station Dashboard • <?php echo date('l, F j, Y'); ?></p>
                            </div>
                            <div>
                                <button type="button" class="btn btn-warning btn-sm" onclick="testNotification()" title="Test notification sound and toast" style="font-weight: 600; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">
                                    <i class="ri-volume-up-line me-1"></i> Test Notification
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Debug Test Button (Alternative location) -->
                    <div class="mb-3">
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="testNotification()" title="Test notification sound and toast">
                            <i class="ri-volume-up-line me-1"></i> 🧪 Test Notification Sound
                        </button>
                    </div>

                    <div class="row">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="metric-card">
                                <span class="metric-icon">❤️</span>
                                <h6 class="metric-title">Vitals Needed</h6>
                                <div class="metric-value" id="metric-vitals">
                                    <?php echo number_format($metrics['vitals_needed'] ?? 0); ?>
                                </div>
                                <div class="metric-change">Patients awaiting intake</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="metric-card">
                                <span class="metric-icon">🏥</span>
                                <h6 class="metric-title">Procedures Today</h6>
                                <div class="metric-value" id="metric-procedures">
                                    <?php echo number_format($metrics['assisting_procedures'] ?? 0); ?>
                                </div>
                                <div class="metric-change">Scheduled procedures</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="metric-card">
                                <span class="metric-icon">👥</span>
                                <h6 class="metric-title">Triage Queue</h6>
                                <div class="metric-value" id="metric-triage">
                                    <?php echo number_format($metrics['triage_queue'] ?? 0); ?>
                                </div>
                                <div class="metric-change">Patients in triage</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="metric-card">
                                <span class="metric-icon">✅</span>
                                <h6 class="metric-title">Completed Today</h6>
                                <div class="metric-value" id="metric-completed">
                                    <?php echo number_format($metrics['completed_today'] ?? 0); ?>
                                </div>
                                <div class="metric-change">Triage completed</div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <h5 class="mb-3">Nursing Actions</h5>
                            <div class="quick-actions">
                                <a href="record_vitals.php" class="quick-action">
                                    <span class="quick-action-icon">❤️</span>
                                    <div class="quick-action-title">Record Vitals</div>
                                    <p class="quick-action-desc">BP, temperature, pulse</p>
                                </a>
                                <a href="medication_admin.php" class="quick-action">
                                    <span class="quick-action-icon">💊</span>
                                    <div class="quick-action-title">Medication Admin</div>
                                    <p class="quick-action-desc">Drug administration</p>
                                </a>
                                <a href="patient_prep.php" class="quick-action">
                                    <span class="quick-action-icon">🏥</span>
                                    <div class="quick-action-title">Patient Prep</div>
                                    <p class="quick-action-desc">Pre-procedure care</p>
                                </a>
                                <a href="nursing_notes.php" class="quick-action">
                                    <span class="quick-action-icon">📝</span>
                                    <div class="quick-action-title">Nursing Notes</div>
                                    <p class="quick-action-desc">Patient observations</p>
                                </a>
                            </div>
                        </div>
                        
                        <div class="col-xl-4">
                            <div class="triage-queue-card">
                                <div class="triage-queue-header">
                                    <h5 class="mb-0">
                                        <i class="ri-heart-pulse-line me-2"></i>Triage Queue
                                        <span class="badge bg-light text-dark ms-2" id="triage-badge"><?php echo $metrics['triage_queue']; ?></span>
                                    </h5>
                                    <small class="opacity-75">Patients awaiting triage</small>
                                </div>
                                
                                <div id="triage-queue-container" style="max-height: 500px; overflow-y: auto;">
                                    <?php if ($triage_queue_result->num_rows > 0): ?>
                                        <?php while ($patient = $triage_queue_result->fetch_assoc()): ?>
                                            <div class="patient-queue-item" onclick="window.location.href='record_vitals.php?patient_id=<?php echo $patient['patient_id']; ?>'">
                                                <div class="queue-patient-info">
                                                    <div class="queue-avatar">
                                                        <?php echo strtoupper(substr($patient['patient_name'], 0, 1)); ?>
                                                    </div>
                                                    <div class="queue-details">
                                                        <div class="queue-patient-name">
                                                            <?php echo htmlspecialchars($patient['patient_name']); ?>
                                                        </div>
                                                        <div class="queue-patient-meta">
                                                            <?php echo $patient['patient_number']; ?> • 
                                                            <?php echo $patient['age']; ?>Y <?php echo $patient['gender']; ?>
                                                        </div>
                                                        <?php if ($patient['chief_complaint']): ?>
                                                        <div class="queue-patient-meta mt-1">
                                                            <i class="ri-stethoscope-line"></i> 
                                                            <?php echo htmlspecialchars(substr($patient['chief_complaint'], 0, 30)); ?>...
                                                        </div>
                                                        <?php endif; ?>
                                                        <div class="mt-2">
                                                            <span class="queue-badge priority-<?php echo strtolower($patient['priority']); ?>">
                                                                <?php echo $patient['priority']; ?>
                                                            </span>
                                                            <span class="queue-badge status-<?php echo str_replace('_', '-', strtolower($patient['queue_status'])); ?>">
                                                                <?php echo str_replace('_', ' ', $patient['queue_status']); ?>
                                                            </span>
                                                        </div>
                                                    </div>
                                                    <div class="text-end">
                                                        <div class="vitals-indicator <?php echo $patient['vitals_taken'] ? 'vitals-done' : 'vitals-pending'; ?>">
                                                            <?php if ($patient['vitals_taken']): ?>
                                                                <i class="ri-check-line"></i> Done
                                                            <?php else: ?>
                                                                <i class="ri-time-line"></i> Pending
                                                            <?php endif; ?>
                                                        </div>
                                                        <div class="queue-patient-meta mt-1">
                                                            Wait: <?php echo $patient['wait_minutes']; ?>m
                                                        </div>
                                                        <?php if ($patient['position_in_queue']): ?>
                                                        <div class="queue-patient-meta">
                                                            Pos: #<?php echo $patient['position_in_queue']; ?>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                        
                                        <a href="queue_dashboard.php" class="view-all-link">
                                            <i class="ri-arrow-right-line me-1"></i>View Full Queue
                                        </a>
                                    <?php else: ?>
                                        <div class="empty-queue">
                                            <i class="ri-inbox-line"></i>
                                            <p class="mb-0">No patients in triage queue</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Notification Sound (hidden audio element) -->
    <audio id="notification-sound" preload="auto" style="display: none;">
        <source src="assets/sounds/notification.mp3" type="audio/mpeg">
        <source src="assets/sounds/notification.wav" type="audio/wav">
    </audio>
    
    <script>
    // State management for notifications
    let lastNotificationTime = 0;
    const NOTIFICATION_INTERVAL = 2 * 60 * 1000; // 2 minutes in milliseconds
    let refreshInterval;
    let notificationCheckInterval;
    let knownQueueIds = new Set(); // Track patients we've already notified about
    
    // Initialize known queue IDs from current patients on page load
    const initialPatients = <?php echo json_encode($initial_queue_ids); ?>;
    if (initialPatients && initialPatients.length > 0) {
        initialPatients.forEach(id => knownQueueIds.add(id));
    }
    
    // Function to play notification sound
    function playNotificationSound() {
        try {
            const audio = document.getElementById('notification-sound');
            if (audio) {
                // Reset audio to beginning
                audio.currentTime = 0;
                audio.play().catch(e => {
                    // If audio file fails, use beep sound
                    playBeepSound();
                });
            } else {
                playBeepSound();
            }
        } catch (e) {
            playBeepSound();
        }
    }
    
    // Fallback beep sound using Web Audio API
    function playBeepSound() {
        try {
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            // Pleasant notification tone (two beeps)
            oscillator.frequency.value = 800;
            oscillator.type = 'sine';
            
            gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
            
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.2);
            
            // Second beep after short delay
            setTimeout(() => {
                const oscillator2 = audioContext.createOscillator();
                const gainNode2 = audioContext.createGain();
                
                oscillator2.connect(gainNode2);
                gainNode2.connect(audioContext.destination);
                
                oscillator2.frequency.value = 1000;
                oscillator2.type = 'sine';
                
                gainNode2.gain.setValueAtTime(0.3, audioContext.currentTime);
                gainNode2.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
                
                oscillator2.start(audioContext.currentTime);
                oscillator2.stop(audioContext.currentTime + 0.2);
            }, 250);
        } catch (e) {
            console.log('Could not play notification sound:', e);
        }
    }
    
    // Function to show toast notification
    function showPatientToast(patientName, queueNumber, priority) {
        // Create toast container if it doesn't exist
        let toastContainer = document.getElementById('toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.id = 'toast-container';
            toastContainer.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999;';
            document.body.appendChild(toastContainer);
        }
        
        const toast = document.createElement('div');
        toast.className = 'alert alert-info alert-dismissible fade show';
        toast.style.cssText = 'min-width: 300px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); animation: slideInRight 0.3s ease-out; margin-bottom: 10px;';
        
        const priorityClass = priority === 'EMERGENCY' ? 'danger' : (priority === 'URGENT' ? 'warning' : 'success');
        
        toast.innerHTML = `
            <div class="d-flex align-items-center">
                <i class="ri-user-add-line me-2" style="font-size: 1.5rem; color: #66CDAA;"></i>
                <div class="flex-grow-1">
                    <strong>New Patient Added to Queue</strong><br>
                    <small>${escapeHtml(patientName)}</small><br>
                    <small class="text-muted">Queue #: ${escapeHtml(queueNumber)}</small><br>
                    <span class="badge bg-${priorityClass} mt-1">${priority}</span>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
        
        toastContainer.appendChild(toast);
        
        // Auto-remove after 5 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                toast.remove();
            }, 300);
        }, 5000);
        
        // Play sound
        playNotificationSound();
    }
    
    // Helper function to escape HTML
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // Function to silently refresh dashboard data
    function refreshDashboardData() {
        fetch('ajax/get_nursing_queue_status.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Check for new patients and show toast notifications
                    if (data.triage_patients && data.triage_patients.length > 0) {
                        data.triage_patients.forEach(patient => {
                            // Check if this is a new patient we haven't notified about
                            if (!knownQueueIds.has(patient.queue_id)) {
                                // New patient detected - show toast
                                showPatientToast(
                                    patient.patient_name,
                                    patient.queue_number,
                                    patient.priority
                                );
                                // Add to known queue IDs
                                knownQueueIds.add(patient.queue_id);
                            }
                        });
                    }
                    
                    // Update metrics
                    if (data.metrics) {
                        const metrics = data.metrics;
                        
                        // Update metric values
                        const vitalsEl = document.getElementById('metric-vitals');
                        const proceduresEl = document.getElementById('metric-procedures');
                        const triageEl = document.getElementById('metric-triage');
                        const completedEl = document.getElementById('metric-completed');
                        
                        if (vitalsEl) vitalsEl.textContent = metrics.vitals_needed || 0;
                        if (proceduresEl) proceduresEl.textContent = metrics.assisting_procedures || 0;
                        if (triageEl) triageEl.textContent = metrics.triage_queue || 0;
                        if (completedEl) completedEl.textContent = metrics.completed_today || 0;
                        
                        // Update badge in triage queue header
                        const badgeElement = document.getElementById('triage-badge');
                        if (badgeElement) {
                            badgeElement.textContent = metrics.triage_queue || 0;
                        }
                    }
                    
                    // Update triage queue list
                    if (data.triage_patients !== undefined) {
                        updateTriageQueueList(data.triage_patients);
                    }
                }
            })
            .catch(error => {
                console.error('Error refreshing dashboard:', error);
            });
    }
    
    // Function to check for waiting patients and play notification
    function checkAndNotifyWaitingPatients() {
        fetch('ajax/get_nursing_queue_status.php')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.has_waiting_patients) {
                    const now = Date.now();
                    // Play sound if it's been 2 minutes since last notification
                    if (now - lastNotificationTime >= NOTIFICATION_INTERVAL) {
                        playNotificationSound();
                        lastNotificationTime = now;
                    }
                } else {
                    // Reset notification timer if no patients waiting
                    lastNotificationTime = 0;
                }
            })
            .catch(error => {
                console.error('Error checking queue status:', error);
            });
    }
    
    // Function to update triage queue list
    function updateTriageQueueList(patients) {
        const container = document.getElementById('triage-queue-container');
        if (!container) return;
        
        if (patients.length === 0) {
            container.innerHTML = `
                <div class="empty-queue">
                    <i class="ri-inbox-line"></i>
                    <p class="mb-0">No patients in triage queue</p>
                </div>
            `;
            return;
        }
        
        let html = '';
        patients.forEach(patient => {
            const priorityClass = patient.priority.toLowerCase();
            const statusClass = patient.queue_status.toLowerCase().replace('_', '-');
            const vitalsClass = patient.vitals_taken ? 'vitals-done' : 'vitals-pending';
            const vitalsIcon = patient.vitals_taken ? 'ri-check-line' : 'ri-time-line';
            const vitalsText = patient.vitals_taken ? 'Done' : 'Pending';
            
            html += `
                <div class="patient-queue-item" onclick="window.location.href='record_vitals.php?patient_id=${patient.patient_id}'">
                    <div class="queue-patient-info">
                        <div class="queue-avatar">
                            ${patient.patient_name.charAt(0).toUpperCase()}
                        </div>
                        <div class="queue-details">
                            <div class="queue-patient-name">
                                ${escapeHtml(patient.patient_name)}
                            </div>
                            <div class="queue-patient-meta">
                                ${patient.patient_number} • 
                                ${patient.age}Y ${patient.gender}
                            </div>
                            ${patient.chief_complaint ? `
                            <div class="queue-patient-meta mt-1">
                                <i class="ri-stethoscope-line"></i> 
                                ${escapeHtml(patient.chief_complaint.substring(0, 30))}...
                            </div>
                            ` : ''}
                            <div class="mt-2">
                                <span class="queue-badge priority-${priorityClass}">
                                    ${patient.priority}
                                </span>
                                <span class="queue-badge status-${statusClass}">
                                    ${patient.queue_status.replace('_', ' ')}
                                </span>
                            </div>
                        </div>
                        <div class="text-end">
                            <div class="vitals-indicator ${vitalsClass}">
                                <i class="${vitalsIcon}"></i> ${vitalsText}
                            </div>
                            <div class="queue-patient-meta mt-1">
                                Wait: ${patient.wait_minutes}m
                            </div>
                            ${patient.position_in_queue ? `
                            <div class="queue-patient-meta">
                                Pos: #${patient.position_in_queue}
                            </div>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
        });
        
        html += `
            <a href="queue_dashboard.php" class="view-all-link">
                <i class="ri-arrow-right-line me-1"></i>View Full Queue
            </a>
        `;
        
        container.innerHTML = html;
    }
    
    // Debug function to test notification sound and toast
    function testNotification() {
        console.log('🔔 Testing notification...');
        console.log('Function called successfully!');
        
        // Test sound
        console.log('🔊 Playing notification sound...');
        try {
            playNotificationSound();
            console.log('✅ Sound function called');
        } catch (e) {
            console.error('❌ Error playing sound:', e);
        }
        
        // Test toast with sample patient data
        console.log('📢 Showing test toast...');
        try {
            showPatientToast(
                'Test Patient - John Doe',
                'TRIAGE-20250101-001',
                'NORMAL'
            );
            console.log('✅ Toast function called');
        } catch (e) {
            console.error('❌ Error showing toast:', e);
        }
        
        // Log notification state
        console.log('📊 Notification test completed');
        console.log('Known queue IDs:', Array.from(knownQueueIds));
        console.log('Last notification time:', lastNotificationTime > 0 ? new Date(lastNotificationTime).toLocaleTimeString() : 'Never');
        console.log('Notification interval:', NOTIFICATION_INTERVAL / 1000, 'seconds');
        
        // Show alert to confirm function was called
        alert('Test notification triggered! Check console for details and listen for sound.');
    }
    
    // Make function globally available
    window.testNotification = testNotification;
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        // Initial refresh after 1 second
        setTimeout(refreshDashboardData, 1000);
        
        // Refresh data every 30 seconds (silent background refresh)
        refreshInterval = setInterval(refreshDashboardData, 30000);
        
        // Check for waiting patients every minute to manage notifications
        notificationCheckInterval = setInterval(checkAndNotifyWaitingPatients, 60000); // Check every minute
        
        // Also check immediately
        setTimeout(checkAndNotifyWaitingPatients, 2000);
    });
    
    // Cleanup on page unload
    window.addEventListener('beforeunload', function() {
        if (refreshInterval) {
            clearInterval(refreshInterval);
        }
        if (notificationCheckInterval) {
            clearInterval(notificationCheckInterval);
        }
    });
    </script>
</body>

</html>
