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

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

// Fix the menu config include with error handling
if (file_exists('includes/menu_config.php')) {
    require_once 'includes/menu_config.php';
} else {
    // Fallback - create a simple menu config function
    function getMenuConfig($userRole = 'guest') {
        return [
            [
                'title' => 'Dashboard',
                'icon' => 'ph-chart-line',
                'url' => 'index.php',
                'type' => 'link'
            ]
        ];
    }
}

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Fetch user details with proper schema alignment
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name, ur.role_code
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: login.php');
    exit();
}

$role_code = $user_details['role_code'];
$role_name = $user_details['role_name'];
$full_name = $user_details['full_name'];
$email = $user_details['email'];
$phone_primary = $user_details['phone_primary'];

// Initialize metrics array
$metrics = [];

// Universal ENT Hospital Metrics
$today = date('Y-m-d');
$current_month = date('Y-m');

// Today's patient visits
$today_visits_sql = "SELECT COUNT(*) as count FROM patient_visits WHERE DATE(registration_date) = ?";
$stmt = $conn->prepare($today_visits_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['today_visits'] = $stmt->get_result()->fetch_assoc()['count'];

// Today's appointments
$today_appointments_sql = "SELECT COUNT(*) as count FROM appointments WHERE appointment_date = ?";
$stmt = $conn->prepare($today_appointments_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['today_appointments'] = $stmt->get_result()->fetch_assoc()['count'];

// Total active patients
$total_patients_sql = "SELECT COUNT(*) as count FROM patients WHERE is_active = 1";
$metrics['total_patients'] = $conn->query($total_patients_sql)->fetch_assoc()['count'];

// Active ENT doctors
$active_doctors_sql = "SELECT COUNT(*) as count FROM doctors d 
                      JOIN users u ON d.user_id = u.user_id 
                      WHERE d.is_active = 1 AND u.status = 'ACTIVE'";
$metrics['active_doctors'] = $conn->query($active_doctors_sql)->fetch_assoc()['count'];

// Today's revenue
$today_revenue_sql = "SELECT COALESCE(SUM(amount), 0) as revenue FROM payments 
                     WHERE DATE(payment_date) = ? AND status = 'COMPLETED'";
$stmt = $conn->prepare($today_revenue_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['today_revenue'] = $stmt->get_result()->fetch_assoc()['revenue'];

// Pending lab orders
$pending_lab_sql = "SELECT COUNT(*) as count FROM lab_orders WHERE status IN ('PENDING', 'IN_PROGRESS')";
$metrics['pending_labs'] = $conn->query($pending_lab_sql)->fetch_assoc()['count'];

// ENT-specific procedure counts for today
$ent_procedures_today_sql = "SELECT COUNT(*) as count FROM patient_procedures pp
                            JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
                            WHERE DATE(pp.procedure_date) = ?";
$stmt = $conn->prepare($ent_procedures_today_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['ent_procedures_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Audiometry tests scheduled for today
$audiometry_today_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 = 'AUDIOMETRY' AND DATE(lot.scheduled_at) = ?";
$stmt = $conn->prepare($audiometry_today_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['audiometry_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Insurance vs Cash patients ratio for today
$payment_distribution_sql = "SELECT 
    registration_type,
    COUNT(*) as count
    FROM patient_visits 
    WHERE DATE(registration_date) = ?
    GROUP BY registration_type";
$stmt = $conn->prepare($payment_distribution_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$payment_dist_result = $stmt->get_result();

$payment_distribution = ['CASH' => 0, 'INSURANCE' => 0, 'CORPORATE' => 0, 'NHIF' => 0];
while ($row = $payment_dist_result->fetch_assoc()) {
    $payment_distribution[$row['registration_type']] = $row['count'];
}

// Role-specific metrics
switch($role_code) {
    case 'ENT_DOCTOR':
    case 'ENT_CONSULTANT':
        // Get doctor ID
        $doctor_id_sql = "SELECT doctor_id FROM doctors WHERE user_id = ?";
        $stmt = $conn->prepare($doctor_id_sql);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $doctor_result = $stmt->get_result();
        
        if ($doctor_result->num_rows > 0) {
            $doctor_data = $doctor_result->fetch_assoc();
            $doctor_id = $doctor_data['doctor_id'];
            
            // My appointments today
            $my_appointments_sql = "SELECT COUNT(*) as count FROM appointments 
                                   WHERE doctor_id = ? AND appointment_date = ? 
                                   AND status IN ('SCHEDULED', 'CONFIRMED', 'CHECKED_IN')";
            $stmt = $conn->prepare($my_appointments_sql);
            $stmt->bind_param("is", $doctor_id, $today);
            $stmt->execute();
            $metrics['my_appointments_today'] = $stmt->get_result()->fetch_assoc()['count'];
            
            // My completed consultations this month
            $my_consultations_sql = "SELECT COUNT(*) as count, COALESCE(SUM(consultation_fee), 0) as revenue 
                                    FROM consultations 
                                    WHERE doctor_id = ? AND DATE(started_at) LIKE ? AND status = 'COMPLETED'";
            $stmt = $conn->prepare($my_consultations_sql);
            $current_month_pattern = $current_month . '%';
            $stmt->bind_param("is", $doctor_id, $current_month_pattern);
            $stmt->execute();
            $consultation_data = $stmt->get_result()->fetch_assoc();
            $metrics['my_monthly_consultations'] = $consultation_data['count'];
            $metrics['my_monthly_revenue'] = $consultation_data['revenue'];
            
            // My pending lab results
            $my_pending_labs_sql = "SELECT COUNT(*) as count FROM lab_orders lo
                                   JOIN consultations c ON lo.consultation_id = c.consultation_id
                                   WHERE c.doctor_id = ? AND lo.status IN ('PENDING', 'IN_PROGRESS')";
            $stmt = $conn->prepare($my_pending_labs_sql);
            $stmt->bind_param("i", $doctor_id);
            $stmt->execute();
            $metrics['my_pending_labs'] = $stmt->get_result()->fetch_assoc()['count'];
            
            // My procedures today
            $my_procedures_sql = "SELECT COUNT(*) as count FROM patient_procedures 
                                 WHERE performed_by = ? AND DATE(procedure_date) = ?";
            $stmt = $conn->prepare($my_procedures_sql);
            $stmt->bind_param("is", $doctor_id, $today);
            $stmt->execute();
            $metrics['my_procedures_today'] = $stmt->get_result()->fetch_assoc()['count'];
        }
        break;
        
    case 'ENT_NURSE':
    case 'HEAD_NURSE':
        // Patients needing vital signs today
        $vitals_needed_sql = "SELECT COUNT(*) as count FROM patient_visits pv
                             WHERE DATE(pv.registration_date) = ? 
                             AND pv.status IN ('REGISTERED', 'WAITING')
                             AND (pv.vital_signs IS NULL OR JSON_EXTRACT(pv.vital_signs, '$.temperature') IS NULL)";
        $stmt = $conn->prepare($vitals_needed_sql);
        $stmt->bind_param("s", $today);
        $stmt->execute();
        $metrics['vitals_needed'] = $stmt->get_result()->fetch_assoc()['count'];
        
        // Procedures I'm assisting with today
        $assisting_procedures_sql = "SELECT COUNT(*) as count FROM patient_procedures 
                                    WHERE DATE(procedure_date) = ? 
                                    AND JSON_CONTAINS(assisted_by, '\"$user_id\"')";
        $stmt = $conn->prepare($assisting_procedures_sql);
        $stmt->bind_param("s", $today);
        $stmt->execute();
        $metrics['assisting_procedures'] = $stmt->get_result()->fetch_assoc()['count'];
        break;
        
    case 'LAB_TECH':
    case 'AUDIOLOGIST':
        // My pending 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
                                WHERE lot.status IN ('PENDING', 'SCHEDULED')";
        $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'];
        
        if ($role_code === 'AUDIOLOGIST') {
            // 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 = 'AUDIOMETRY' 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'];
        }
        break;
        
    case 'RECEPTIONIST':
        // Patients I registered today
        $my_registrations_sql = "SELECT COUNT(*) as count FROM patient_visits 
                                WHERE registered_by = ? AND DATE(registration_date) = ?";
        $stmt = $conn->prepare($my_registrations_sql);
        $stmt->bind_param("is", $user_id, $today);
        $stmt->execute();
        $metrics['my_registrations_today'] = $stmt->get_result()->fetch_assoc()['count'];
        
        // Waiting patients
        $waiting_patients_sql = "SELECT COUNT(*) as count FROM patient_visits 
                               WHERE status = 'WAITING' AND DATE(registration_date) = ?";
        $stmt = $conn->prepare($waiting_patients_sql);
        $stmt->bind_param("s", $today);
        $stmt->execute();
        $metrics['waiting_patients'] = $stmt->get_result()->fetch_assoc()['count'];
        
        // Online appointments today
        $online_appointments_sql = "SELECT COUNT(*) as count FROM appointments 
                                   WHERE booking_source = 'ONLINE' AND appointment_date = ?";
        $stmt = $conn->prepare($online_appointments_sql);
        $stmt->bind_param("s", $today);
        $stmt->execute();
        $metrics['online_appointments'] = $stmt->get_result()->fetch_assoc()['count'];
        break;
        
    case 'BILLING_CLERK':
        // Today's payments collected
        $my_payments_sql = "SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as total 
                           FROM payments 
                           WHERE received_by = ? AND DATE(payment_date) = ?";
        $stmt = $conn->prepare($my_payments_sql);
        $stmt->bind_param("is", $user_id, $today);
        $stmt->execute();
        $payment_data = $stmt->get_result()->fetch_assoc();
        $metrics['my_payments_count'] = $payment_data['count'];
        $metrics['my_payments_total'] = $payment_data['total'];
        
        // Pending invoices
        $pending_invoices_sql = "SELECT COUNT(*) as count FROM invoices 
                               WHERE status IN ('SENT', 'PARTIAL_PAYMENT', 'OVERDUE')";
        $metrics['pending_invoices'] = $conn->query($pending_invoices_sql)->fetch_assoc()['count'];
        
        // Insurance claims to process
        $insurance_claims_sql = "SELECT COUNT(*) as count FROM invoices 
                               WHERE bill_to = 'INSURANCE' AND status = 'INSURANCE_PENDING'";
        $metrics['insurance_claims'] = $conn->query($insurance_claims_sql)->fetch_assoc()['count'];
        break;
}

// Additional comprehensive metrics for ENT hospital
$current_week = date('Y-m-d', strtotime('monday this week'));

// Total patients registered this week
$weekly_patients_sql = "SELECT COUNT(*) as count FROM patients 
                       WHERE DATE(created_at) >= ?";
$stmt = $conn->prepare($weekly_patients_sql);
$stmt->bind_param("s", $current_week);
$stmt->execute();
$metrics['weekly_new_patients'] = $stmt->get_result()->fetch_assoc()['count'];

// Today's checked-in patients 
$checked_in_sql = "SELECT COUNT(*) as count FROM patient_visits 
                  WHERE DATE(registration_date) = ? AND status IN ('IN_CONSULTATION', 'COMPLETED')";
$stmt = $conn->prepare($checked_in_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['checked_in_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Weekly revenue
$weekly_revenue_sql = "SELECT COALESCE(SUM(amount), 0) as revenue FROM payments 
                      WHERE DATE(payment_date) >= ? AND status = 'COMPLETED'";
$stmt = $conn->prepare($weekly_revenue_sql);
$stmt->bind_param("s", $current_week);
$stmt->execute();
$metrics['weekly_revenue'] = $stmt->get_result()->fetch_assoc()['revenue'];

// Completed consultations today
$completed_consultations_sql = "SELECT COUNT(*) as count FROM consultations 
                               WHERE DATE(started_at) = ? AND status = 'COMPLETED'";
$stmt = $conn->prepare($completed_consultations_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['completed_consultations_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Emergency visits today
$emergency_visits_sql = "SELECT COUNT(*) as count FROM patient_visits 
                        WHERE DATE(registration_date) = ? AND priority = 'EMERGENCY'";
$stmt = $conn->prepare($emergency_visits_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['emergency_visits_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Most common ENT conditions this month
$common_conditions_sql = "SELECT diagnosis_primary, COUNT(*) as count 
                         FROM consultations 
                         WHERE DATE(started_at) LIKE ? AND diagnosis_primary IS NOT NULL AND diagnosis_primary != ''
                         GROUP BY diagnosis_primary 
                         ORDER BY count DESC LIMIT 5";
$stmt = $conn->prepare($common_conditions_sql);
$current_month_pattern = $current_month . '%';
$stmt->bind_param("s", $current_month_pattern);
$stmt->execute();
$common_conditions_result = $stmt->get_result();
$common_conditions = [];
while ($row = $common_conditions_result->fetch_assoc()) {
    $common_conditions[] = $row;
}

// Doctor availability today
$available_doctors_sql = "SELECT COUNT(DISTINCT d.doctor_id) as count 
                         FROM doctors d
                         JOIN users u ON d.user_id = u.user_id
                         LEFT JOIN appointments a ON d.doctor_id = a.doctor_id AND a.appointment_date = ?
                         WHERE d.is_active = 1 AND u.status = 'ACTIVE'";
$stmt = $conn->prepare($available_doctors_sql);
$stmt->bind_param("s", $today);
$stmt->execute();
$metrics['available_doctors_today'] = $stmt->get_result()->fetch_assoc()['count'];

// Insurance vs cash ratio
$payment_ratio = 0;
$total_today_visits = array_sum($payment_distribution);
if ($total_today_visits > 0) {
    $payment_ratio = round(($payment_distribution['INSURANCE'] / $total_today_visits) * 100, 1);
}
$monthly_revenue_sql = "SELECT 
    DATE(payment_date) as date,
    SUM(amount) as revenue,
    COUNT(*) as transaction_count
    FROM payments 
    WHERE payment_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    AND status = 'COMPLETED'
    GROUP BY DATE(payment_date)
    ORDER BY date";
$monthly_revenue_result = $conn->query($monthly_revenue_sql);
$revenue_data = [];
while ($row = $monthly_revenue_result->fetch_assoc()) {
    $revenue_data[] = $row;
}

// ENT procedure type distribution
$procedure_distribution_sql = "SELECT 
    ept.category,
    COUNT(*) as count,
    SUM(pp.cost) as total_cost
    FROM patient_procedures pp
    JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
    WHERE DATE(pp.procedure_date) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY ept.category
    ORDER BY count DESC";
$procedure_dist_result = $conn->query($procedure_distribution_sql);
$procedure_data = [];
while ($row = $procedure_dist_result->fetch_assoc()) {
    $procedure_data[] = $row;
}

// Recent activities based on role
$recent_activities = [];
switch($role_code) {
    case 'ENT_DOCTOR':
    case 'ENT_CONSULTANT':
        if (isset($doctor_id)) {
            $recent_activities_sql = "SELECT 'consultation' as type, c.consultation_number as reference,
                                    p.patient_number, u.full_name as patient_name, c.started_at as activity_time
                                    FROM consultations c
                                    JOIN patients p ON c.patient_id = p.patient_id
                                    JOIN users u ON p.user_id = u.user_id
                                    WHERE c.doctor_id = ? 
                                    ORDER BY c.started_at DESC LIMIT 5";
            $stmt = $conn->prepare($recent_activities_sql);
            $stmt->bind_param("i", $doctor_id);
            $stmt->execute();
            $recent_activities = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        }
        break;
        
    case 'RECEPTIONIST':
        $recent_activities_sql = "SELECT 'registration' as type, pv.visit_number as reference,
                                p.patient_number, u.full_name as patient_name, pv.registration_date as activity_time
                                FROM patient_visits pv
                                JOIN patients p ON pv.patient_id = p.patient_id
                                JOIN users u ON p.user_id = u.user_id
                                WHERE pv.registered_by = ?
                                ORDER BY pv.registration_date 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);
        break;
        
    case 'LAB_TECH':
    case 'AUDIOLOGIST':
        $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
                                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
                                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);
        break;
}

// Fetch active queue data for today
$queue_sql = "SELECT 
    q.queue_id,
    q.queue_number,
    q.patient_name,
    q.patient_number,
    q.phone_number,
    q.age,
    q.gender,
    d.department_name,
    d.department_code,
    q.queue_status,
    q.priority,
    q.position_in_queue,
    q.chief_complaint,
    q.queue_entry_time,
    q.service_start_time,
    TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) as wait_minutes,
    q.is_vip
FROM patient_queue q
INNER JOIN departments d ON q.department_id = d.department_id
WHERE DATE(q.queue_entry_time) = CURDATE()
AND q.queue_status IN ('WAITING', 'IN_SERVICE')
ORDER BY 
    d.display_order,
    CASE q.priority
        WHEN 'EMERGENCY' THEN 1
        WHEN 'URGENT' THEN 2
        WHEN 'NORMAL' THEN 3
    END,
    q.queue_entry_time
LIMIT 20";

$queue_result = $conn->query($queue_sql);

// Get queue statistics by department
$dept_queue_sql = "SELECT 
    d.department_name,
    d.department_code,
    COUNT(CASE WHEN q.queue_status = 'WAITING' THEN 1 END) as waiting,
    COUNT(CASE WHEN q.queue_status = 'IN_SERVICE' THEN 1 END) as in_service,
    AVG(CASE WHEN q.queue_status = 'WAITING' 
        THEN TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) END) as avg_wait
FROM departments d
LEFT JOIN patient_queue q ON d.department_id = q.department_id 
    AND DATE(q.queue_entry_time) = CURDATE()
    AND q.queue_status IN ('WAITING', 'IN_SERVICE')
WHERE d.is_active = 1
GROUP BY d.department_id, d.department_name, d.department_code
HAVING (waiting > 0 OR in_service > 0)
ORDER BY d.display_order";

$dept_queue_result = $conn->query($dept_queue_sql);
//triggerJobProcessing($conn);

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'ENT Hospital Dashboard')); ?>
    <!-- apexcharts css -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.css">
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 0.5rem 1.5rem 1.5rem 1.5rem;
        }
        
        /* Welcome Header - PRODIGY ENT Brand Colors */
        .welcome-header {
            background: linear-gradient(135deg, #8FBC8F 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);
            position: relative;
            overflow: hidden;
        }
        
        .welcome-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><path d="M20,20 Q50,5 80,20 Q85,50 80,80 Q50,95 20,80 Q5,50 20,20" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="1"/></svg>');
            animation: float 20s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: rotate(0deg) translateY(0px); }
            50% { transform: rotate(180deg) translateY(-20px); }
        }
        
        .welcome-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
            position: relative;
            z-index: 1;
        }
        
        .welcome-text h2 {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .welcome-text p {
            opacity: 0.9;
            margin: 0;
        }
        
        .datetime-display {
            text-align: right;
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 1rem;
            min-width: 200px;
        }
        
        .current-time {
            font-size: 1.5rem;
            font-weight: 700;
            font-family: 'Courier New', monospace;
        }
        
        .current-date {
            font-size: 0.9rem;
            opacity: 0.8;
        }
        
        /* ENT-specific Metrics Cards */
        .metrics-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .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 ease;
            position: relative;
            overflow: hidden;
        }
        
        .metric-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: var(--accent-color, #10b981);
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        
        .metric-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        
        .metric-card:hover::before {
            opacity: 1;
        }
        
        .metric-card.revenue { --accent-color: #8FBC8F; }
        .metric-card.patients { --accent-color: #20B2AA; }
        .metric-card.procedures { --accent-color: #9ACD32; }
        .metric-card.labs { --accent-color: #40E0D0; }
        .metric-card.appointments { --accent-color: #66CDAA; }
        
        .metric-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
        }
        
        .metric-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin: 0;
        }
        
        .metric-icon {
            background: #f1f5f9;
            border-radius: 8px;
            padding: 0.5rem;
            font-size: 1.25rem;
            color: var(--accent-color, #10b981);
        }
        
        .metric-value {
            font-size: 2.25rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
            line-height: 1;
        }
        
        .metric-change {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            margin-bottom: 1rem;
        }
        
        .metric-trend {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .trend-up { color: #8FBC8F; }
        .trend-down { color: #CD5C5C; }
        .trend-neutral { color: #20B2AA; }
        
        .metric-link {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            margin-top: 0.5rem;
            color: var(--accent-color, #8FBC8F);
            text-decoration: none;
            font-size: 0.875rem;
            font-weight: 500;
            transition: color 0.2s ease;
        }
        
        .metric-link:hover {
            color: #20B2AA;
        }
        
        /* Quick Actions - ENT Focused */
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .quick-action {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            text-decoration: none;
            color: #1e293b;
            transition: all 0.2s ease;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .quick-action:hover {
            color: #8FBC8F;
            border-color: #8FBC8F;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        
        .quick-action-icon {
            font-size: 2.5rem;
            margin-bottom: 0.75rem;
            color: #8FBC8F;
            display: block;
        }
        
        .quick-action-title {
            font-weight: 600;
            font-size: 0.875rem;
            margin-bottom: 0.25rem;
        }
        
        .quick-action-desc {
            font-size: 0.75rem;
            color: #64748b;
            margin: 0;
        }
        
        /* Charts and Analytics */
        .chart-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .chart-header {
            padding: 1.5rem 1.5rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .chart-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 1rem 0;
        }
        
        .chart-body {
            padding: 1rem 1.5rem 1.5rem;
        }
        
        /* Tables */
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-consultation { background: #dbeafe; color: #1d4ed8; }
        .status-procedure { background: #f3e8ff; color: #7c3aed; }
        .status-test { background: #fef3c7; color: #92400e; }
        .status-registration { background: #dcfce7; color: #166534; }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .welcome-content {
                flex-direction: column;
                text-align: center;
            }
            
            .datetime-display {
                min-width: auto;
                width: 100%;
            }
            
            .metrics-row {
                grid-template-columns: 1fr;
            }
            
            .metric-value {
                font-size: 1.75rem;
            }
            
            .quick-actions {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
    <style>
.table-card {
    margin-bottom: 2rem;
}

.data-table tbody tr {
    transition: background-color 0.2s ease;
}

.data-table tbody tr:hover {
    background-color: #f8fafc;
}

.btn-group-sm .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
}

.card {
    transition: all 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06) !important;
}
</style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Welcome Header -->
                    <div class="welcome-header">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>
                                    <?php 
                                    $hour = date('H');
                                    $greeting = $hour < 12 ? 'Good Morning' : ($hour < 17 ? 'Good Afternoon' : 'Good Evening');
                                    echo $greeting . ', Dr. ' . $full_name;
                                    ?>
                                </h2>
                                <p>ENT Specialist Hospital - <?php echo $role_name; ?>
                                    <?php if($phone_primary): ?> | <?php echo $phone_primary; ?><?php endif; ?>
                                </p>
                                <small style="opacity: 0.8;">Comprehensive Ear, Nose & Throat Care</small>
                            </div>
                            <div class="datetime-display d-none d-md-block">
                                <div class="current-time" id="currentTime"><?php echo date('h:i A'); ?></div>
                                <div class="current-date" id="currentDate"><?php echo date('l, M j, Y'); ?></div>
                            </div>
                        </div>
                    </div>

                    <!-- Hospital Overview Metrics -->
                    <div class="metrics-row">
                        <div class="metric-card patients">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Today's Visits</h6>
                                </div>
                                <span class="metric-icon">🏥</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['today_visits']); ?></div>
                            <div class="metric-change">Patient registrations today</div>
                            <div class="metric-trend trend-up">
                                <i class="ri-arrow-up-line"></i>
                                <span>Checked-in: <?php echo number_format($metrics['checked_in_today']); ?></span>
                            </div>
                            <a href="todays_visits.php" class="metric-link">
                                View all visits <i class="ri-arrow-right-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card appointments">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Today's Appointments</h6>
                                </div>
                                <span class="metric-icon">📅</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['today_appointments']); ?></div>
                            <div class="metric-change">Scheduled consultations</div>
                            <div class="metric-trend trend-neutral">
                                <i class="ri-user-line"></i>
                                <span><?php echo number_format($metrics['available_doctors_today']); ?> doctors available</span>
                            </div>
                            <a href="todays_appointments.php" class="metric-link">
                                View schedule <i class="ri-calendar-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card revenue">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Today's Revenue</h6>
                                </div>
                                <span class="metric-icon">💰</span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($metrics['today_revenue']); ?></div>
                            <div class="metric-change">Payments collected</div>
                            <div class="metric-trend trend-up">
                                <i class="ri-funds-line"></i>
                                <span>Weekly: KES <?php echo number_format($metrics['weekly_revenue']); ?></span>
                            </div>
                            <a href="daily_revenue.php" class="metric-link">
                                View details <i class="ri-money-dollar-circle-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card procedures">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">ENT Procedures Today</h6>
                                </div>
                                <span class="metric-icon">⚕️</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['ent_procedures_today']); ?></div>
                            <div class="metric-change">Surgical & therapeutic procedures</div>
                            <div class="metric-trend trend-neutral">
                                <i class="ri-microscope-line"></i>
                                <span>Consultations: <?php echo $metrics['completed_consultations_today']; ?></span>
                            </div>
                            <a href="todays_procedures.php" class="metric-link">
                                View procedures <i class="ri-surgical-mask-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card labs">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Lab Orders</h6>
                                </div>
                                <span class="metric-icon">🧪</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['pending_labs']); ?></div>
                            <div class="metric-change">Pending test results</div>
                            <div class="metric-trend trend-down">
                                <i class="ri-test-tube-line"></i>
                                <span>Audiometry: <?php echo $metrics['audiometry_today']; ?></span>
                            </div>
                            <a href="pending_lab_orders.php" class="metric-link">
                                Process orders <i class="ri-flask-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card patients">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Total Patients</h6>
                                </div>
                                <span class="metric-icon">👥</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['total_patients']); ?></div>
                            <div class="metric-change">Active patient records</div>
                            <div class="metric-trend trend-up">
                                <i class="ri-user-add-line"></i>
                                <span>New this week: <?php echo $metrics['weekly_new_patients']; ?></span>
                            </div>
                            <a href="list_patients.php" class="metric-link">
                                View patients <i class="ri-group-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Emergency Cases</h6>
                                </div>
                                <span class="metric-icon">🚨</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['emergency_visits_today']); ?></div>
                            <div class="metric-change">Urgent visits today</div>
                            <div class="metric-trend trend-neutral">
                                <i class="ri-alarm-warning-line"></i>
                                <span>Immediate attention</span>
                            </div>
                            <a href="emergency_visits.php" class="metric-link">
                                View cases <i class="ri-siren-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Insurance Ratio</h6>
                                </div>
                                <span class="metric-icon">🛡️</span>
                            </div>
                            <div class="metric-value"><?php echo $payment_ratio; ?>%</div>
                            <div class="metric-change">Insurance vs cash patients</div>
                            <div class="metric-trend trend-neutral">
                                <i class="ri-shield-check-line"></i>
                                <span>NHIF: <?php echo $payment_distribution['NHIF']; ?> patients</span>
                            </div>
                            <a href="payment_analysis.php" class="metric-link">
                                View breakdown <i class="ri-pie-chart-line"></i>
                            </a>
                        </div>
                    </div>

                    <!-- Role-specific Metrics -->
                    <?php if ($role_code === 'ENT_DOCTOR' || $role_code === 'ENT_CONSULTANT'): ?>
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #8FBC8F; font-weight: 600;">My Practice Dashboard</h5>
                        </div>
                    </div>
                    <div class="metrics-row">
                        <div class="metric-card appointments">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">My Appointments Today</h6>
                                </div>
                                <span class="metric-icon">👨‍⚕️</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_appointments_today'] ?? 0); ?></div>
                            <div class="metric-change">Scheduled for today</div>
                            <a href="my_appointments.php" class="metric-link">
                                View my schedule <i class="ri-calendar-check-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card revenue">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Monthly Consultations</h6>
                                </div>
                                <span class="metric-icon">📊</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_monthly_consultations'] ?? 0); ?></div>
                            <div class="metric-change">Revenue: KES <?php echo number_format($metrics['my_monthly_revenue'] ?? 0); ?></div>
                            <a href="my_consultations.php" class="metric-link">
                                View details <i class="ri-line-chart-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card labs">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Pending Lab Results</h6>
                                </div>
                                <span class="metric-icon">📋</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_pending_labs'] ?? 0); ?></div>
                            <div class="metric-change">Awaiting my review</div>
                            <a href="my_pending_results.php" class="metric-link">
                                Review results <i class="ri-file-list-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card procedures">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">My Procedures Today</h6>
                                </div>
                                <span class="metric-icon">🔬</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_procedures_today'] ?? 0); ?></div>
                            <div class="metric-change">Scheduled procedures</div>
                            <a href="my_procedures.php" class="metric-link">
                                View schedule <i class="ri-medicine-bottle-line"></i>
                            </a>
                        </div>
                    </div>
                    
                    <!-- Doctor Quick Actions -->
                    <div class="quick-actions">
                        <a href="new_consultation.php" class="quick-action">
                            <span class="quick-action-icon">👨‍⚕️</span>
                            <div class="quick-action-title">New Consultation</div>
                            <p class="quick-action-desc">Start ENT consultation</p>
                        </a>
                        <a href="order_tests.php" class="quick-action">
                            <span class="quick-action-icon">🧪</span>
                            <div class="quick-action-title">Order Tests</div>
                            <p class="quick-action-desc">Audiometry, imaging, labs</p>
                        </a>
                        <a href="schedule_procedure.php" class="quick-action">
                            <span class="quick-action-icon">⚕️</span>
                            <div class="quick-action-title">Schedule Procedure</div>
                            <p class="quick-action-desc">ENT surgical procedures</p>
                        </a>
                        <a href="my_patients.php" class="quick-action">
                            <span class="quick-action-icon">📋</span>
                            <div class="quick-action-title">My Patients</div>
                            <p class="quick-action-desc">Patient medical records</p>
                        </a>
                    </div>
                    
                    <?php elseif ($role_code === 'RECEPTIONIST'): ?>
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #20B2AA; font-weight: 600;">Front Office Dashboard</h5>
                        </div>
                    </div>
                    <div class="metrics-row">
                        <div class="metric-card patients">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">My Registrations Today</h6>
                                </div>
                                <span class="metric-icon">✅</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_registrations_today'] ?? 0); ?></div>
                            <div class="metric-change">Patients I registered</div>
                            <a href="my_registrations.php" class="metric-link">
                                View details <i class="ri-user-add-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card appointments">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Waiting Patients</h6>
                                </div>
                                <span class="metric-icon">⏱️</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['waiting_patients'] ?? 0); ?></div>
                            <div class="metric-change">Currently in queue</div>
                            <a href="waiting_room.php" class="metric-link">
                                Manage queue <i class="ri-time-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Online Bookings</h6>
                                </div>
                                <span class="metric-icon">💻</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['online_appointments'] ?? 0); ?></div>
                            <div class="metric-change">Digital appointments today</div>
                            <a href="online_bookings.php" class="metric-link">
                                Manage bookings <i class="ri-smartphone-line"></i>
                            </a>
                        </div>
                    </div>
                    
                    <!-- Receptionist Quick Actions -->
                    <div class="quick-actions">
                        <a href="register_patient.php" class="quick-action">
                            <span class="quick-action-icon">👤</span>
                            <div class="quick-action-title">Register Patient</div>
                            <p class="quick-action-desc">New patient registration</p>
                        </a>
                        <a href="register_visit.php" class="quick-action">
                            <span class="quick-action-icon">🏥</span>
                            <div class="quick-action-title">Register Visit</div>
                            <p class="quick-action-desc">Walk-in or appointment</p>
                        </a>
                        <a href="book_appointment.php" class="quick-action">
                            <span class="quick-action-icon">📅</span>
                            <div class="quick-action-title">Book Appointment</div>
                            <p class="quick-action-desc">Schedule consultation</p>
                        </a>
                        <a href="patient_search.php" class="quick-action">
                            <span class="quick-action-icon">🔍</span>
                            <div class="quick-action-title">Patient Search</div>
                            <p class="quick-action-desc">Find patient records</p>
                        </a>
                    </div>
                    
                    <?php elseif ($role_code === 'LAB_TECH' || $role_code === 'AUDIOLOGIST'): ?>
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #40E0D0; font-weight: 600;">
                                <?php echo $role_code === 'AUDIOLOGIST' ? 'Audiology' : 'Laboratory'; ?> Dashboard
                            </h5>
                        </div>
                    </div>
                    <div class="metrics-row">
                        <div class="metric-card labs">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Pending Tests</h6>
                                </div>
                                <span class="metric-icon">⏳</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_pending_tests'] ?? 0); ?></div>
                            <div class="metric-change">Awaiting processing</div>
                            <a href="pending_tests.php" class="metric-link">
                                Process tests <i class="ri-play-circle-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Completed Today</h6>
                                </div>
                                <span class="metric-icon">✅</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['completed_tests_today'] ?? 0); ?></div>
                            <div class="metric-change">Tests completed</div>
                            <a href="completed_tests.php" class="metric-link">
                                View results <i class="ri-check-circle-line"></i>
                            </a>
                        </div>
                        
                        <?php if ($role_code === 'AUDIOLOGIST'): ?>
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Hearing Tests Today</h6>
                                </div>
                                <span class="metric-icon">🎧</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['audio_tests_today'] ?? 0); ?></div>
                            <div class="metric-change">Audiometry scheduled</div>
                            <a href="audio_schedule.php" class="metric-link">
                                View schedule <i class="ri-headphone-line"></i>
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Lab Quick Actions -->
                    <div class="quick-actions">
                        <?php if ($role_code === 'AUDIOLOGIST'): ?>
                        <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_testing.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>
                        <?php else: ?>
                        <a href="sample_collection.php" class="quick-action">
                            <span class="quick-action-icon">🧪</span>
                            <div class="quick-action-title">Sample Collection</div>
                            <p class="quick-action-desc">Collect specimens</p>
                        </a>
                        <a href="test_processing.php" class="quick-action">
                            <span class="quick-action-icon">🔬</span>
                            <div class="quick-action-title">Process Tests</div>
                            <p class="quick-action-desc">Laboratory analysis</p>
                        </a>
                        <a href="enter_results.php" class="quick-action">
                            <span class="quick-action-icon">📊</span>
                            <div class="quick-action-title">Enter Results</div>
                            <p class="quick-action-desc">Input test findings</p>
                        </a>
                        <a href="quality_control.php" class="quick-action">
                            <span class="quick-action-icon">🔍</span>
                            <div class="quick-action-title">Quality Control</div>
                            <p class="quick-action-desc">Verify accuracy</p>
                        </a>
                        <?php endif; ?>
                    </div>
                    
                    <?php elseif ($role_code === 'BILLING_CLERK'): ?>
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #8FBC8F; font-weight: 600;">Billing & Finance Dashboard</h5>
                        </div>
                    </div>
                    <div class="metrics-row">
                        <div class="metric-card revenue">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">My Collections Today</h6>
                                </div>
                                <span class="metric-icon">💳</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['my_payments_count'] ?? 0); ?></div>
                            <div class="metric-change">Total: KES <?php echo number_format($metrics['my_payments_total'] ?? 0); ?></div>
                            <a href="my_collections.php" class="metric-link">
                                View details <i class="ri-money-dollar-box-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Pending Invoices</h6>
                                </div>
                                <span class="metric-icon">📄</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['pending_invoices'] ?? 0); ?></div>
                            <div class="metric-change">Awaiting payment</div>
                            <a href="pending_invoices.php" class="metric-link">
                                Follow up <i class="ri-file-list-2-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Insurance Claims</h6>
                                </div>
                                <span class="metric-icon">🛡️</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['insurance_claims'] ?? 0); ?></div>
                            <div class="metric-change">Processing</div>
                            <a href="insurance_claims.php" class="metric-link">
                                Track claims <i class="ri-shield-check-line"></i>
                            </a>
                        </div>
                    </div>
                    
                    <!-- Billing Quick Actions -->
                    <div class="quick-actions">
                        <a href="create_invoice.php" class="quick-action">
                            <span class="quick-action-icon">📄</span>
                            <div class="quick-action-title">Create Invoice</div>
                            <p class="quick-action-desc">Generate patient bill</p>
                        </a>
                        <a href="record_payment.php" class="quick-action">
                            <span class="quick-action-icon">💳</span>
                            <div class="quick-action-title">Record Payment</div>
                            <p class="quick-action-desc">Cash, card, M-Pesa</p>
                        </a>
                        <a href="insurance_billing.php" class="quick-action">
                            <span class="quick-action-icon">🛡️</span>
                            <div class="quick-action-title">Insurance Billing</div>
                            <p class="quick-action-desc">Submit claims</p>
                        </a>
                        <a href="payment_reports.php" class="quick-action">
                            <span class="quick-action-icon">📊</span>
                            <div class="quick-action-title">Payment Reports</div>
                            <p class="quick-action-desc">Daily collections</p>
                        </a>
                    </div>
                    
                    <?php elseif ($role_code === 'ENT_NURSE' || $role_code === 'HEAD_NURSE'): ?>
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3" style="color: #66CDAA; font-weight: 600;">Nursing Dashboard</h5>
                        </div>
                    </div>
                    <div class="metrics-row">
                        <div class="metric-card patients">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Vitals Needed</h6>
                                </div>
                                <span class="metric-icon">❤️</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['vitals_needed'] ?? 0); ?></div>
                            <div class="metric-change">Patients awaiting vitals</div>
                            <a href="vitals_queue.php" class="metric-link">
                                Record vitals <i class="ri-heart-pulse-line"></i>
                            </a>
                        </div>
                        
                        <div class="metric-card procedures">
                            <div class="metric-header">
                                <div>
                                    <h6 class="metric-title">Procedures Assisting</h6>
                                </div>
                                <span class="metric-icon">🏥</span>
                            </div>
                            <div class="metric-value"><?php echo number_format($metrics['assisting_procedures'] ?? 0); ?></div>
                            <div class="metric-change">Today's schedule</div>
                            <a href="procedure_schedule.php" class="metric-link">
                                View schedule <i class="ri-calendar-todo-line"></i>
                            </a>
                        </div>
                    </div>
                    
                    <!-- Nurse Quick Actions -->
                    <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>
                    <?php endif; ?>
                    
                    <!-- Patient Queue Overview Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5 style="color: #8FBC8F; font-weight: 600; margin: 0;">
                                    <i class="ri-team-line me-2"></i>Today's Patient Queue
                                </h5>
                                <a href="queue_dashboard.php" class="btn btn-outline-primary btn-sm">
                                    <i class="ri-dashboard-line me-1"></i> Full Queue Dashboard
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Department Queue Summary Cards -->
                    <?php if ($dept_queue_result && $dept_queue_result->num_rows > 0): ?>
                    <div class="row mb-4">
                        <?php while ($dept = $dept_queue_result->fetch_assoc()): ?>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card border-0 shadow-sm h-100">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                        <div>
                                            <h6 class="text-muted text-uppercase" style="font-size: 0.75rem; font-weight: 600;">
                                                <?php echo htmlspecialchars($dept['department_name']); ?>
                                            </h6>
                                        </div>
                                        <span class="badge bg-info-subtle text-info">
                                            <?php echo ($dept['waiting'] + $dept['in_service']); ?> Active
                                        </span>
                                    </div>
                                    
                                    <div class="row text-center">
                                        <div class="col-6">
                                            <div class="p-2" style="background: #dbeafe; border-radius: 8px;">
                                                <h4 class="mb-0" style="color: #1d4ed8;"><?php echo $dept['waiting']; ?></h4>
                                                <small class="text-muted">Waiting</small>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="p-2" style="background: #fef3c7; border-radius: 8px;">
                                                <h4 class="mb-0" style="color: #92400e;"><?php echo $dept['in_service']; ?></h4>
                                                <small class="text-muted">In Service</small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <?php if ($dept['avg_wait']): ?>
                                    <div class="mt-3 text-center">
                                        <small class="text-muted">
                                            <i class="ri-time-line"></i> Avg Wait: 
                                            <strong><?php echo round($dept['avg_wait']); ?> min</strong>
                                        </small>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Active Queue List -->
                    <div class="table-card">
                        <div class="table-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h3 class="table-title mb-0">
                                    <i class="ri-user-follow-line me-2"></i>Active Patients in Queue
                                </h3>
                                <div class="d-flex gap-2">
                                    <span class="badge bg-danger-subtle text-danger">
                                        <i class="ri-error-warning-line"></i> Emergency: 
                                        <?php 
                                        $emergency_count = 0;
                                        $queue_result->data_seek(0);
                                        while($q = $queue_result->fetch_assoc()) {
                                            if ($q['priority'] === 'EMERGENCY') $emergency_count++;
                                        }
                                        echo $emergency_count;
                                        ?>
                                    </span>
                                    <span class="badge bg-warning-subtle text-warning">
                                        <i class="ri-alarm-line"></i> Urgent: 
                                        <?php 
                                        $urgent_count = 0;
                                        $queue_result->data_seek(0);
                                        while($q = $queue_result->fetch_assoc()) {
                                            if ($q['priority'] === 'URGENT') $urgent_count++;
                                        }
                                        echo $urgent_count;
                                        ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <?php if ($queue_result && $queue_result->num_rows > 0): ?>
                        <div class="table-responsive">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th style="width: 5%;">#</th>
                                        <th style="width: 15%;">Queue Number</th>
                                        <th style="width: 20%;">Patient</th>
                                        <th style="width: 15%;">Department</th>
                                        <th style="width: 10%;">Priority</th>
                                        <th style="width: 10%;">Status</th>
                                        <th style="width: 10%;">Wait Time</th>
                                        <th style="width: 5%;">Pos.</th>
                                        <th style="width: 10%;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $queue_result->data_seek(0);
                                    $row_num = 1;
                                    while ($queue = $queue_result->fetch_assoc()): 
                                        $wait_class = $queue['wait_minutes'] > 60 ? 'text-danger fw-bold' : 'text-muted';
                                    ?>
                                    <tr>
                                        <td><?php echo $row_num++; ?></td>
                                        <td>
                                            <strong class="text-primary"><?php echo htmlspecialchars($queue['queue_number']); ?></strong>
                                            <?php if ($queue['is_vip']): ?>
                                            <span class="badge bg-warning-subtle text-warning" style="font-size: 0.65rem;">VIP</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div>
                                                <div class="fw-semibold"><?php echo htmlspecialchars($queue['patient_name']); ?></div>
                                                <small class="text-muted">
                                                    <?php echo $queue['patient_number']; ?> | 
                                                    <?php echo $queue['age']; ?>Y <?php echo $queue['gender']; ?>
                                                </small>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge" style="background: #e0f2fe; color: #0369a1; font-weight: 500;">
                                                <?php echo htmlspecialchars($queue['department_name']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php
                                            $priority_colors = [
                                                'EMERGENCY' => 'bg-danger text-white',
                                                'URGENT' => 'bg-warning text-dark',
                                                'NORMAL' => 'bg-success-subtle text-success'
                                            ];
                                            $priority_class = $priority_colors[$queue['priority']] ?? 'bg-secondary';
                                            ?>
                                            <span class="badge <?php echo $priority_class; ?>">
                                                <?php echo $queue['priority']; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php
                                            $status_colors = [
                                                'WAITING' => 'bg-info-subtle text-info',
                                                'IN_SERVICE' => 'bg-warning-subtle text-warning'
                                            ];
                                            $status_class = $status_colors[$queue['queue_status']] ?? 'bg-secondary';
                                            ?>
                                            <span class="badge <?php echo $status_class; ?>">
                                                <?php echo str_replace('_', ' ', $queue['queue_status']); ?>
                                            </span>
                                        </td>
                                        <td class="<?php echo $wait_class; ?>">
                                            <i class="ri-time-line"></i>
                                            <?php 
                                            if ($queue['wait_minutes'] < 60) {
                                                echo $queue['wait_minutes'] . ' min';
                                            } else {
                                                $hours = floor($queue['wait_minutes'] / 60);
                                                $mins = $queue['wait_minutes'] % 60;
                                                echo $hours . 'h ' . $mins . 'm';
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <?php if ($queue['queue_status'] === 'WAITING' && $queue['position_in_queue']): ?>
                                            <span class="badge bg-primary">#<?php echo $queue['position_in_queue']; ?></span>
                                            <?php else: ?>
                                            <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="view_patient.php?id=<?php echo htmlspecialchars($queue['patient_id'] ?? ''); ?>&queue_id=<?php echo htmlspecialchars($queue['queue_id'] ?? ''); ?>" 
                                                   class="btn btn-info btn-sm" 
                                                   title="View Patient">
                                                    <i class="ri-eye-line"></i>
                                                </a>
                                                <?php if (($queue['queue_status'] ?? '') === 'WAITING'): ?>
                                                    <button class="btn btn-success btn-sm" 
                                                            onclick="startService(<?php echo (int)($queue['queue_id'] ?? 0); ?>)" 
                                                            title="Start Service">
                                                        <i class="ri-play-line"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>

                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <?php if ($queue_result->num_rows >= 20): ?>
                        <div class="p-3 text-center bg-light">
                            <a href="queue_dashboard.php" class="btn btn-primary">
                                <i class="ri-list-check me-1"></i> View All Patients in Queue
                            </a>
                        </div>
                        <?php endif; ?>
                        
                        <?php else: ?>
                        <div class="text-center p-5">
                            <i class="ri-inbox-line" style="font-size: 4rem; color: #cbd5e1;"></i>
                            <h5 class="mt-3 text-muted">No Patients in Queue</h5>
                            <p class="text-muted">All patients have been attended to or there are no pending queue entries.</p>
                            <a href="register_patient.php" class="btn btn-primary mt-2">
                                <i class="ri-user-add-line me-1"></i> Register New Patient
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Charts Section -->
                    <div class="row">
                        <div class="col-xl-6">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">ENT Hospital Revenue Trends (Last 30 Days)</h3>
                                </div>
                                <div class="chart-body">
                                    <div id="revenue-chart" style="height: 350px;"></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3">
                            <div class="chart-card">
                                <div class="chart-header">
                                    <h3 class="chart-title">ENT Procedure Distribution</h3>
                                </div>
                                <div class="chart-body">
                                    <div id="procedure-chart" style="height: 350px;"></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3">
                            <div class="table-card">
                                <div class="table-header">
                                    <h3 class="table-title">Common ENT Conditions</h3>
                                </div>
                                <div style="padding: 1rem;">
                                    <?php if (!empty($common_conditions)): ?>
                                        <?php foreach ($common_conditions as $index => $condition): ?>
                                        <div class="d-flex justify-content-between align-items-center py-2 <?php echo $index < count($common_conditions) - 1 ? 'border-bottom' : ''; ?>">
                                            <div>
                                                <small class="fw-medium text-truncate" style="max-width: 150px;">
                                                    <?php echo htmlspecialchars(ucwords(strtolower($condition['diagnosis_primary']))); ?>
                                                </small>
                                            </div>
                                            <span class="badge bg-primary-subtle text-primary">
                                                <?php echo $condition['count']; ?>
                                            </span>
                                        </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div class="text-center text-muted py-3">
                                            <i class="ri-stethoscope-line fs-24"></i>
                                            <p class="mb-0 mt-2 small">No diagnoses recorded this month</p>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="mt-3">
                                        <a href="diagnosis_reports.php" class="btn btn-outline-primary btn-sm w-100">
                                            <i class="ri-bar-chart-line me-1"></i> View Full Report
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Activities -->
                    <?php if (!empty($recent_activities)): ?>
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">My Recent Activities</h3>
                        </div>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Activity Type</th>
                                    <th>Reference</th>
                                    <th>Patient</th>
                                    <th>Date & Time</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($recent_activities as $activity): ?>
                                <tr>
                                    <td>
                                        <span class="status-badge status-<?php echo $activity['type']; ?>">
                                            <?php echo ucfirst($activity['type']); ?>
                                        </span>
                                    </td>
                                    <td style="font-weight: 600;"><?php echo htmlspecialchars($activity['reference']); ?></td>
                                    <td>
                                        <div>
                                            <div style="font-weight: 600;"><?php echo htmlspecialchars($activity['patient_name']); ?></div>
                                            <div style="color: #64748b; font-size: 0.75rem;"><?php echo htmlspecialchars($activity['patient_number']); ?></div>
                                        </div>
                                    </td>
                                    <td style="color: #64748b;"><?php echo date('M j, g:i A', strtotime($activity['activity_time'])); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>

                    <!-- Payment Distribution & Quick Stats -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="table-card">
                                <div class="table-header">
                                    <h3 class="table-title">Today's Payment Distribution</h3>
                                </div>
                                <div style="padding: 1.5rem;">
                                    <div class="row text-center">
                                        <div class="col-6 mb-3">
                                            <div style="background: #f0fdf4; border-radius: 8px; padding: 1rem;">
                                                <div style="font-size: 1.5rem; font-weight: 700; color: #059669;"><?php echo $payment_distribution['CASH']; ?></div>
                                                <div style="font-size: 0.875rem; color: #64748b;">Cash Patients</div>
                                            </div>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <div style="background: #eff6ff; border-radius: 8px; padding: 1rem;">
                                                <div style="font-size: 1.5rem; font-weight: 700; color: #3b82f6;"><?php echo $payment_distribution['INSURANCE']; ?></div>
                                                <div style="font-size: 0.875rem; color: #64748b;">Insurance</div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div style="background: #fef3c7; border-radius: 8px; padding: 1rem;">
                                                <div style="font-size: 1.5rem; font-weight: 700; color: #d97706;"><?php echo $payment_distribution['CORPORATE']; ?></div>
                                                <div style="font-size: 0.875rem; color: #64748b;">Corporate</div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div style="background: #f3e8ff; border-radius: 8px; padding: 1rem;">
                                                <div style="font-size: 1.5rem; font-weight: 700; color: #7c3aed;"><?php echo $payment_distribution['NHIF']; ?></div>
                                                <div style="font-size: 0.875rem; color: #64748b;">NHIF</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="table-card">
                                <div class="table-header">
                                    <h3 class="table-title">ENT Hospital Quick Stats</h3>
                                </div>
                                <div style="padding: 1.5rem;">
                                    <div class="d-grid gap-2">
                                        <div class="d-flex justify-content-between align-items-center p-2 bg-light rounded">
                                            <span class="fw-medium">Total Active Patients</span>
                                            <span class="badge bg-success"><?php echo number_format($metrics['total_patients']); ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center p-2 bg-light rounded">
                                            <span class="fw-medium">ENT Specialists</span>
                                            <span class="badge bg-primary"><?php echo number_format($metrics['active_doctors']); ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center p-2 bg-light rounded">
                                            <span class="fw-medium">Today's Revenue</span>
                                            <span class="badge bg-warning">KES <?php echo number_format($metrics['today_revenue']); ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center p-2 bg-light rounded">
                                            <span class="fw-medium">Pending Lab Orders</span>
                                            <span class="badge bg-danger"><?php echo number_format($metrics['pending_labs']); ?></span>
                                        </div>
                                        
                                        <hr class="my-2">
                                        
                                        <div class="d-grid gap-2 mt-3">
                                            <?php if ($role_code === 'ENT_DOCTOR' || $role_code === 'ENT_CONSULTANT'): ?>
                                            <a href="my_patients.php" class="btn btn-outline-success btn-sm">My Patients</a>
                                            <a href="pending_results.php" class="btn btn-outline-primary btn-sm">Lab Results</a>
                                            <?php elseif ($role_code === 'RECEPTIONIST'): ?>
                                            <a href="patient_search.php" class="btn btn-outline-primary btn-sm">Patient Search</a>
                                            <a href="waiting_room.php" class="btn btn-outline-warning btn-sm">Waiting Room</a>
                                            <?php elseif ($role_code === 'LAB_TECH' || $role_code === 'AUDIOLOGIST'): ?>
                                            <a href="pending_tests.php" class="btn btn-outline-warning btn-sm">Pending Tests</a>
                                            <a href="test_results.php" class="btn btn-outline-success btn-sm">Results Entry</a>
                                            <?php else: ?>
                                            <a href="profile.php" class="btn btn-outline-primary btn-sm">My Profile</a>
                                            <a href="notifications.php" class="btn btn-outline-info btn-sm">Notifications</a>
                                            <?php endif; ?>
                                            <a href="help_support.php" class="btn btn-outline-secondary btn-sm">Help & Support</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.min.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Update time and date
        function updateDateTime() {
            const now = new Date();
            
            const timeElement = document.getElementById('currentTime');
            const dateElement = document.getElementById('currentDate');
            
            if (timeElement) {
                timeElement.textContent = now.toLocaleTimeString('en-US', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true
                });
            }
            
            if (dateElement) {
                dateElement.textContent = now.toLocaleDateString('en-US', {
                    weekday: 'long',
                    month: 'short',
                    day: 'numeric',
                    year: 'numeric'
                });
            }
        }
        
        // Update every minute
        setInterval(updateDateTime, 60000);
        updateDateTime();

        // Revenue Chart
        const revenueData = <?php echo json_encode($revenue_data); ?>;
        const revenueDates = revenueData.map(item => item.date);
        const revenueAmounts = revenueData.map(item => parseFloat(item.revenue));
        const transactionCounts = revenueData.map(item => parseInt(item.transaction_count));

        const revenueOptions = {
            series: [{
                name: 'Revenue (KES)',
                type: 'area',
                data: revenueAmounts
            }, {
                name: 'Transactions',
                type: 'line',
                data: transactionCounts
            }],
            chart: {
                height: 350,
                type: 'line',
                toolbar: { show: false },
                animations: { enabled: true }
            },
            stroke: {
                curve: 'smooth',
                width: [0, 3]
            },
            fill: {
                type: ['gradient', 'solid'],
                gradient: {
                    shadeIntensity: 1,
                    type: 'vertical',
                    colorStops: [
                        { offset: 0, color: '#8FBC8F', opacity: 0.8 },
                        { offset: 100, color: '#8FBC8F', opacity: 0.1 }
                    ]
                }
            },
            colors: ['#8FBC8F', '#20B2AA'],
            labels: revenueDates.map(date => new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })),
            markers: { size: 4 },
            xaxis: { 
                type: 'category',
                labels: {
                    style: {
                        fontSize: '12px'
                    }
                }
            },
            yaxis: [{
                title: { text: 'Revenue (KES)', style: { color: '#059669' } },
                labels: {
                    formatter: function (val) {
                        return 'KES ' + val.toLocaleString();
                    }
                }
            }, {
                opposite: true,
                title: { text: 'Transactions', style: { color: '#3b82f6' } }
            }],
            tooltip: {
                shared: true,
                intersect: false,
                y: [{
                    formatter: function (y) {
                        return typeof y !== "undefined" ? "KES " + y.toLocaleString() : y;
                    }
                }, {
                    formatter: function (y) {
                        return typeof y !== "undefined" ? y + " transactions" : y;
                    }
                }]
            },
            grid: {
                borderColor: '#e2e8f0',
                strokeDashArray: 3
            }
        };

        try {
            const revenueChart = new ApexCharts(document.querySelector("#revenue-chart"), revenueOptions);
            revenueChart.render();
        } catch(e) {
            console.error("Error rendering revenue chart:", e);
            document.querySelector("#revenue-chart").innerHTML = '<div class="text-center p-4"><p style="color: #64748b;">Revenue data will appear here</p></div>';
        }

        // Procedure Distribution Chart
        const procedureData = <?php echo json_encode($procedure_data); ?>;
        const procedureLabels = procedureData.map(item => item.category.replace('_', ' '));
        const procedureCounts = procedureData.map(item => parseInt(item.count));

        const procedureOptions = {
            series: procedureCounts,
            chart: {
                type: 'donut',
                height: 350,
                animations: { enabled: true }
            },
            labels: procedureLabels,
            plotOptions: {
                pie: {
                    donut: { 
                        size: '65%',
                        labels: {
                            show: true,
                            total: {
                                show: true,
                                label: 'Total Procedures',
                                formatter: function (w) {
                                    return w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                }
                            }
                        }
                    }
                }
            },
            legend: { 
                position: 'bottom',
                fontSize: '12px'
            },
            colors: ['#8FBC8F', '#20B2AA', '#9ACD32', '#40E0D0', '#66CDAA'],
            tooltip: {
                y: {
                    formatter: function(value) {
                        return value + " procedures";
                    }
                }
            },
            dataLabels: {
                enabled: true,
                formatter: function (val, opts) {
                    return opts.w.config.series[opts.seriesIndex];
                }
            }
        };

        try {
            const procedureChart = new ApexCharts(document.querySelector("#procedure-chart"), procedureOptions);
            procedureChart.render();
        } catch(e) {
            console.error("Error rendering procedure chart:", e);
            document.querySelector("#procedure-chart").innerHTML = '<div class="text-center p-4"><p style="color: #64748b;">Procedure data will appear here</p></div>';
        }

        // Add hover effects to metric cards
        document.querySelectorAll('.metric-card').forEach(card => {
            card.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-4px)';
                this.style.boxShadow = '0 8px 15px rgba(0, 0, 0, 0.1)';
            });
            
            card.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
                this.style.boxShadow = '0 1px 3px 0 rgba(0, 0, 0, 0.1)';
            });
        });

        // Add hover effects to quick actions
        document.querySelectorAll('.quick-action').forEach(action => {
            action.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px) scale(1.02)';
            });
            
            action.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0) scale(1)';
            });
        });
    });
    </script>
    <script>
function startService(queueId) {
    Swal.fire({
        title: 'Start Service?',
        text: 'Mark this patient as in service?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Start Service',
        confirmButtonColor: '#10b981',
        cancelButtonColor: '#6b7280'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = 'queue_actions.php?action=start_service&queue_id=' + queueId;
        }
    });
}

// Auto-refresh queue every 60 seconds
setInterval(function() {
    // Only refresh if user is still on the page
    if (document.hasFocus()) {
        location.reload();
    }
}, 60000);
</script>
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>