<?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'];

if ($role_code !== 'AUDIOLOGIST') {
    // Redirect logic
     $redirect_url = match($role_code) {
        'SUPER_ADMIN', 'HOSPITAL_ADMIN' => 'admin_dashboard.php',
        'ENT_CONSULTANT', 'ENT_DOCTOR' => 'doctor_dashboard.php',
        'RESIDENT_DOCTOR' => 'resident_dashboard.php',
        'HEAD_NURSE', 'ENT_NURSE' => 'nursing_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');

// My pending tests - filter by audiometry tests
$my_pending_tests_sql = "SELECT COUNT(*) as count FROM lab_order_tests lot
                        JOIN lab_orders lo ON lot.order_id = lo.order_id
                        JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
                        WHERE lot.status IN ('PENDING', 'SCHEDULED')
                        AND ett.category IN ('AUDIOMETRY', 'VESTIBULAR')";
$metrics['my_pending_tests'] = $conn->query($my_pending_tests_sql)->fetch_assoc()['count'];

// Tests completed today
$completed_today_sql = "SELECT COUNT(*) as count FROM lab_order_tests 
                       WHERE DATE(completed_at) = ? AND status = 'COMPLETED'";
$stmt = $conn->prepare($completed_today_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['completed_tests_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Audiometry-specific metrics
$audio_tests_sql = "SELECT COUNT(*) as count FROM lab_order_tests lot
                   JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
                   WHERE ett.category IN ('AUDIOMETRY', 'VESTIBULAR') AND DATE(lot.scheduled_at) = ?";
$stmt = $conn->prepare($audio_tests_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['audio_tests_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Get AUDIOLOGY department for queue
$audiology_dept_sql = "SELECT department_id FROM departments 
                       WHERE department_code IN ('AUDIOLOGY', 'VESTIBULAR') AND is_active = 1";
$audiology_dept_result = $conn->query($audiology_dept_sql);
$audiology_dept_ids = [];
while ($row = $audiology_dept_result->fetch_assoc()) {
    $audiology_dept_ids[] = $row['department_id'];
}

// Get queue count for audiology departments
$queue_count = 0;
$queue_patients = [];
if (!empty($audiology_dept_ids)) {
    $dept_ids_str = implode(',', $audiology_dept_ids);
    $queue_sql = "SELECT COUNT(*) as count FROM patient_queue 
                  WHERE department_id IN ($dept_ids_str) 
                  AND queue_status = 'WAITING' 
                  AND DATE(queue_entry_time) = CURDATE()";
    $queue_result = $conn->query($queue_sql);
    $queue_count = $queue_result->fetch_assoc()['count'];
    
    // Get recent queue patients
    $recent_queue_sql = "SELECT q.queue_id, q.queue_number, q.patient_name, q.patient_number, 
                        q.age, q.gender, q.priority, q.queue_entry_time, q.chief_complaint,
                        d.department_name
                        FROM patient_queue q
                        INNER JOIN departments d ON q.department_id = d.department_id
                        WHERE q.department_id IN ($dept_ids_str) 
                        AND q.queue_status = 'WAITING' 
                        AND DATE(q.queue_entry_time) = CURDATE()
                        ORDER BY 
                            CASE q.priority
                                WHEN 'EMERGENCY' THEN 1
                                WHEN 'URGENT' THEN 2
                                WHEN 'NORMAL' THEN 3
                            END,
                            q.queue_entry_time
                        LIMIT 5";
    $recent_queue_result = $conn->query($recent_queue_sql);
    while ($row = $recent_queue_result->fetch_assoc()) {
        $queue_patients[] = $row;
    }
}

// Get last checked queue ID for notification tracking
$last_queue_id = 0;
if (!empty($audiology_dept_ids)) {
    $last_queue_check_sql = "SELECT MAX(queue_id) as last_queue_id FROM patient_queue 
                             WHERE department_id IN (" . implode(',', $audiology_dept_ids) . ") 
                             AND DATE(queue_entry_time) = CURDATE()";
    $last_check_result = $conn->query($last_queue_check_sql);
    $last_queue_id = $last_check_result->fetch_assoc()['last_queue_id'] ?? 0;
}

// Recent tests
$recent_activities_sql = "SELECT 'test' as type, lo.order_number as reference,
                        p.patient_number, u.full_name as patient_name, lot.completed_at as activity_time,
                        ett.test_name
                        FROM lab_order_tests lot
                        JOIN lab_orders lo ON lot.order_id = lo.order_id
                        JOIN patients p ON lo.patient_id = p.patient_id
                        JOIN users u ON p.user_id = u.user_id
                        JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
                        WHERE lot.status = 'COMPLETED' AND lot.tested_by = ?
                        ORDER BY lot.completed_at DESC LIMIT 5";
$stmt = $conn->prepare($recent_activities_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$recent_activities = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

?>
<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Audiology Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .welcome-header {
            background: linear-gradient(135deg, #40E0D0 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;
        }
        .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: #40E0D0; 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: #40E0D0;
        }
        .quick-action-icon { font-size: 2rem; margin-bottom: 0.5rem; display: block; color: #40E0D0;}
        .quick-action-title { font-weight: 600; margin-bottom: 0.25rem; color: #334155; }
        .quick-action-desc { font-size: 0.875rem; color: #64748b; margin: 0; }
    </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">
                        <h2>Hello, <?php echo htmlspecialchars($full_name); ?></h2>
                        <p>Audiology Department</p>
                    </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">Pending Tests</h6>
                                <div class="metric-value"><?php echo number_format($metrics['my_pending_tests'] ?? 0); ?></div>
                                <div class="metric-change">Total queue</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"><?php echo number_format($metrics['completed_tests_today'] ?? 0); ?></div>
                                <div class="metric-change">Tests finalized</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">Hearing Tests Today</h6>
                                <div class="metric-value"><?php echo number_format($metrics['audio_tests_today'] ?? 0); ?></div>
                                <div class="metric-change">Scheduled audiometry</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="metric-card" id="queue-count-card">
                                <span class="metric-icon">⏳</span>
                                <h6 class="metric-title">Queue Waiting</h6>
                                <div class="metric-value" id="queue-count-value"><?php echo number_format($queue_count); ?></div>
                                <div class="metric-change">Patients in audiology queue</div>
                            </div>
                        </div>
                    </div>

                    <h5 class="mb-3">Audiology Services</h5>
                    <div class="quick-actions">
                        <a href="pure_tone_audiometry.php" class="quick-action">
                            <span class="quick-action-icon">🎧</span>
                            <div class="quick-action-title">Pure Tone Audiometry</div>
                            <p class="quick-action-desc">Hearing threshold testing</p>
                        </a>
                        <a href="speech_audiometry.php" class="quick-action">
                            <span class="quick-action-icon">🗣️</span>
                            <div class="quick-action-title">Speech Audiometry</div>
                            <p class="quick-action-desc">Speech recognition tests</p>
                        </a>
                        <a href="vestibular_tests.php" class="quick-action">
                            <span class="quick-action-icon">⚖️</span>
                            <div class="quick-action-title">Vestibular Testing</div>
                            <p class="quick-action-desc">Balance assessment</p>
                        </a>
                        <a href="hearing_aid_fitting.php" class="quick-action">
                            <span class="quick-action-icon">🔊</span>
                            <div class="quick-action-title">Hearing Aid Fitting</div>
                            <p class="quick-action-desc">Device programming</p>
                        </a>
                    </div>

                    <!-- Patient Queue Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">
                                        <i class="ri-list-check me-2"></i>Audiology Queue
                                        <span class="badge bg-primary ms-2" id="queue-badge"><?php echo $queue_count; ?></span>
                                    </h5>
                                    <a href="queue_dashboard.php?department=<?php echo !empty($audiology_dept_ids) ? $audiology_dept_ids[0] : ''; ?>" class="btn btn-sm btn-primary">
                                        <i class="ri-external-link-line me-1"></i>View Full Queue
                                    </a>
                                </div>
                                <div class="card-body">
                                    <div id="queue-list-container">
                                        <?php if (!empty($queue_patients)): ?>
                                            <div class="table-responsive">
                                                <table class="table table-hover">
                                                    <thead>
                                                        <tr>
                                                            <th>Queue #</th>
                                                            <th>Patient</th>
                                                            <th>Age/Gender</th>
                                                            <th>Priority</th>
                                                            <th>Chief Complaint</th>
                                                            <th>Wait Time</th>
                                                            <th>Action</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="queue-table-body">
                                                        <?php foreach ($queue_patients as $patient): ?>
                                                            <tr data-queue-id="<?php echo $patient['queue_id']; ?>">
                                                                <td><strong><?php echo htmlspecialchars($patient['queue_number']); ?></strong></td>
                                                                <td>
                                                                    <div><?php echo htmlspecialchars($patient['patient_name']); ?></div>
                                                                    <small class="text-muted"><?php echo htmlspecialchars($patient['patient_number']); ?></small>
                                                                </td>
                                                                <td><?php echo $patient['age']; ?>Y / <?php echo $patient['gender']; ?></td>
                                                                <td>
                                                                    <span class="badge bg-<?php 
                                                                        echo $patient['priority'] === 'EMERGENCY' ? 'danger' : 
                                                                            ($patient['priority'] === 'URGENT' ? 'warning' : 'success'); 
                                                                    ?>">
                                                                        <?php echo htmlspecialchars($patient['priority']); ?>
                                                                    </span>
                                                                </td>
                                                                <td><?php echo htmlspecialchars(substr($patient['chief_complaint'] ?? 'N/A', 0, 40)); ?></td>
                                                                <td>
                                                                    <?php 
                                                                    $wait_minutes = round((time() - strtotime($patient['queue_entry_time'])) / 60);
                                                                    echo $wait_minutes . ' min';
                                                                    ?>
                                                                </td>
                                                                <td>
                                                                    <a href="queue_actions.php?action=start_service&queue_id=<?php echo $patient['queue_id']; ?>" 
                                                                       class="btn btn-sm btn-success">
                                                                        <i class="ri-play-line"></i> Start
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        <?php else: ?>
                                            <div class="text-center py-4">
                                                <i class="ri-inbox-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                                                <p class="text-muted mt-2">No patients in queue</p>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Tests -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">My Recent Tests</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Date/Time</th>
                                                    <th>Order #</th>
                                                    <th>Patient</th>
                                                    <th>Test</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (!empty($recent_activities)): ?>
                                                    <?php foreach ($recent_activities as $activity): ?>
                                                    <tr>
                                                        <td><?php echo date('M d, H:i', strtotime($activity['activity_time'])); ?></td>
                                                        <td><?php echo htmlspecialchars($activity['reference']); ?></td>
                                                        <td><?php echo htmlspecialchars($activity['patient_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($activity['test_name']); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr><td colspan="4" class="text-center">No recent tests found.</td></tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Notification Toast Container -->
    <div id="toast-container" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>
    
    <!-- Notification Sound (hidden audio element) -->
    <audio id="notification-sound" preload="auto">
        <source src="assets/sounds/notification.mp3" type="audio/mpeg">
        <source src="assets/sounds/notification.wav" type="audio/wav">
    </audio>
    
    <script>
        // Store last queue ID for comparison
        let lastQueueId = <?php echo $last_queue_id; ?>;
        let queueCheckInterval;
        
        // Function to play notification sound
        function playNotificationSound() {
            const audio = document.getElementById('notification-sound');
            if (audio && audio.readyState >= 2) {
                audio.play().catch(e => {
                    playBeepSound();
                });
            } else {
                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);
                
                oscillator.frequency.value = 800;
                oscillator.type = 'sine';
                
                gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
                
                oscillator.start(audioContext.currentTime);
                oscillator.stop(audioContext.currentTime + 0.3);
            } catch (e) {
                console.log('Could not play notification sound:', e);
            }
        }
        
        // Function to show toast notification
        function showQueueNotification(patientName, queueNumber, priority) {
            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;';
            toast.innerHTML = `
                <div class="d-flex align-items-center">
                    <i class="ri-notification-3-line me-2" style="font-size: 1.5rem;"></i>
                    <div class="flex-grow-1">
                        <strong>New Patient in Queue!</strong><br>
                        <small>${patientName} - ${queueNumber}</small><br>
                        <span class="badge bg-${priority === 'EMERGENCY' ? 'danger' : (priority === 'URGENT' ? 'warning' : 'success')}">${priority}</span>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            document.getElementById('toast-container').appendChild(toast);
            
            setTimeout(() => {
                toast.remove();
            }, 5000);
            
            playNotificationSound();
        }
        
        // Function to check for new queue entries
        function checkQueueUpdates() {
            fetch('ajax/check_queue_updates.php?role=audiologist&last_id=' + lastQueueId)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.new_entries && data.new_entries.length > 0) {
                        if (data.queue_count !== undefined) {
                            document.getElementById('queue-count-value').textContent = data.queue_count;
                            document.getElementById('queue-badge').textContent = data.queue_count;
                            
                            const queueCard = document.getElementById('queue-count-card');
                            queueCard.style.animation = 'pulse 0.5s ease-in-out';
                            setTimeout(() => {
                                queueCard.style.animation = '';
                            }, 500);
                        }
                        
                        data.new_entries.forEach(entry => {
                            showQueueNotification(entry.patient_name, entry.queue_number, entry.priority);
                            lastQueueId = Math.max(lastQueueId, entry.queue_id);
                        });
                        
                        if (data.new_entries.length > 0) {
                            loadQueueTable();
                        }
                    }
                })
                .catch(error => {
                    console.error('Error checking queue updates:', error);
                });
        }
        
        // Function to load queue table
        function loadQueueTable() {
            fetch('ajax/get_audiologist_queue.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.patients) {
                        const tbody = document.getElementById('queue-table-body');
                        if (tbody) {
                            tbody.innerHTML = data.patients.map(patient => {
                                const waitMinutes = Math.round((new Date() - new Date(patient.queue_entry_time)) / 60000);
                                const priorityClass = patient.priority === 'EMERGENCY' ? 'danger' : 
                                                    (patient.priority === 'URGENT' ? 'warning' : 'success');
                                return `
                                    <tr data-queue-id="${patient.queue_id}">
                                        <td><strong>${patient.queue_number}</strong></td>
                                        <td>
                                            <div>${patient.patient_name}</div>
                                            <small class="text-muted">${patient.patient_number}</small>
                                        </td>
                                        <td>${patient.age}Y / ${patient.gender}</td>
                                        <td><span class="badge bg-${priorityClass}">${patient.priority}</span></td>
                                        <td>${(patient.chief_complaint || 'N/A').substring(0, 40)}</td>
                                        <td>${waitMinutes} min</td>
                                        <td>
                                            <a href="queue_actions.php?action=start_service&queue_id=${patient.queue_id}" 
                                               class="btn btn-sm btn-success">
                                                <i class="ri-play-line"></i> Start
                                            </a>
                                        </td>
                                    </tr>
                                `;
                            }).join('');
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading queue table:', error);
                });
        }
        
        // Start checking for updates every 10 seconds
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(checkQueueUpdates, 2000);
            queueCheckInterval = setInterval(checkQueueUpdates, 10000);
        });
        
        window.addEventListener('beforeunload', function() {
            if (queueCheckInterval) {
                clearInterval(queueCheckInterval);
            }
        });
    </script>
    
    <style>
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }
    </style>
</body>
</html>
