<?php 
include 'layouts/dbconn.php';

$current_month = date('m');
$current_year = date('Y');

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

// Fetch user details with ENT Hospital schema alignment
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name
                     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_data = $stmt_user->get_result()->fetch_assoc();

if ($user_data) {
    $username = $user_data['username'];
    $role_name = $user_data['role_name'];
    $full_name = $user_data['full_name'];
    $email = $user_data['email'];
    $phone_number = $user_data['phone_primary'];
    $profile_picture = $user_data['profile_picture'] ?? null;
}

// Fetch recent activity from activity_log (using as notifications)
$notifications_query = "SELECT al.log_id, al.action, al.module, al.record_id, al.logged_at, u.full_name as created_by 
                       FROM activity_log al 
                       LEFT JOIN users u ON al.user_id = u.user_id 
                       WHERE al.action IN ('LOGIN', 'CREATE', 'UPDATE', 'DELETE')
                       AND al.logged_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
                       ORDER BY al.logged_at DESC LIMIT 10";
$notifications_result = $conn->query($notifications_query);
$notifications = [];
if ($notifications_result) {
    $notifications = $notifications_result->fetch_all(MYSQLI_ASSOC);
}

// Count recent activities as unread notifications
$unread_count_query = "SELECT COUNT(*) as count FROM activity_log 
                      WHERE logged_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) 
                      AND action IN ('CREATE', 'UPDATE', 'DELETE')";
$unread_result = $conn->query($unread_count_query);
$unread_count = $unread_result ? $unread_result->fetch_assoc()['count'] : 0;

// Get team members (other active users)
$team_query = "SELECT u.user_id, u.full_name, ur.role_name, u.profile_picture 
              FROM users u 
              LEFT JOIN user_roles ur ON u.role_id = ur.role_id 
              WHERE u.status = 'ACTIVE' AND u.user_id != ? 
              ORDER BY u.full_name
              LIMIT 5";
$stmt_team = $conn->prepare($team_query);
$stmt_team->bind_param("i", $user_id);
$stmt_team->execute();
$team_members = $stmt_team->get_result()->fetch_all(MYSQLI_ASSOC);

// Get quick stats for current user based on role
$quick_stats = [];
if ($role_name === 'Super Admin') {
    // Get admin's system stats
    $admin_stats_query = "SELECT 
        COUNT(DISTINCT pv.visit_id) as total_visits,
        COUNT(DISTINCT p.patient_id) as total_patients,
        COALESCE(SUM(pay.amount), 0) as total_revenue,
        COUNT(CASE WHEN pay.status = 'PENDING' THEN 1 END) as pending_payments
        FROM patient_visits pv
        LEFT JOIN patients p ON p.is_active = 1
        LEFT JOIN payments pay ON pv.visit_id = pay.visit_id
        WHERE pv.status != 'CANCELLED'";
    $admin_result = $conn->query($admin_stats_query);
    $quick_stats = $admin_result->fetch_assoc();
} elseif ($role_name === 'Hospital Admin') {
    // Get hospital admin's stats
    $admin_stats_query = "SELECT 
        COUNT(DISTINCT pv.visit_id) as daily_visits,
        COUNT(DISTINCT a.appointment_id) as total_appointments,
        COALESCE(SUM(pay.amount), 0) as daily_revenue,
        COUNT(CASE WHEN a.status = 'SCHEDULED' THEN 1 END) as scheduled_appointments
        FROM patient_visits pv
        LEFT JOIN appointments a ON DATE(a.appointment_date) = CURDATE()
        LEFT JOIN payments pay ON pv.visit_id = pay.visit_id AND DATE(pay.payment_date) = CURDATE()
        WHERE DATE(pv.registration_date) = CURDATE()";
    $admin_result = $conn->query($admin_stats_query);
    $quick_stats = $admin_result->fetch_assoc();
} elseif (strpos($role_name, 'Doctor') !== false || strpos($role_name, 'Consultant') !== false) {
    // Get doctor's daily stats
    $doctor_stats_query = "SELECT 
        COUNT(DISTINCT a.appointment_id) as daily_appointments,
        COUNT(DISTINCT c.consultation_id) as daily_consultations,
        COALESCE(SUM(c.consultation_fee), 0) as daily_revenue,
        COUNT(CASE WHEN a.status = 'SCHEDULED' THEN 1 END) as scheduled_appointments
        FROM appointments a
        LEFT JOIN patient_visits pv ON a.appointment_id = pv.appointment_id
        LEFT JOIN consultations c ON pv.visit_id = c.visit_id AND DATE(c.started_at) = CURDATE()
        WHERE a.doctor_id = (SELECT doctor_id FROM doctors WHERE user_id = ?)
        AND DATE(a.appointment_date) = CURDATE()";
    $stmt_doctor = $conn->prepare($doctor_stats_query);
    $stmt_doctor->bind_param("i", $user_id);
    $stmt_doctor->execute();
    $quick_stats = $stmt_doctor->get_result()->fetch_assoc();
} elseif ($role_name === 'Receptionist') {
    // Get receptionist's daily stats
    $receptionist_stats_query = "SELECT 
        COUNT(CASE WHEN DATE(pv.registration_date) = CURDATE() THEN 1 END) as daily_registrations,
        COUNT(CASE WHEN DATE(a.appointment_date) = CURDATE() THEN 1 END) as daily_appointments,
        COUNT(CASE WHEN a.status = 'CHECKED_IN' THEN 1 END) as checked_in_patients,
        COUNT(CASE WHEN a.status = 'SCHEDULED' THEN 1 END) as pending_checkins
        FROM patient_visits pv
        LEFT JOIN appointments a ON DATE(a.appointment_date) = CURDATE()
        WHERE pv.registered_by = ? OR a.appointment_date >= CURDATE()";
    $stmt_receptionist = $conn->prepare($receptionist_stats_query);
    $stmt_receptionist->bind_param("i", $user_id);
    $stmt_receptionist->execute();
    $quick_stats = $stmt_receptionist->get_result()->fetch_assoc();
} elseif ($role_name === 'Lab Technician' || $role_name === 'Audiologist') {
    // Get technician's test stats
    $tech_stats_query = "SELECT 
        COUNT(CASE WHEN lo.status = 'PENDING' THEN 1 END) as pending_tests,
        COUNT(CASE WHEN lo.status = 'IN_PROGRESS' THEN 1 END) as in_progress_tests,
        COUNT(CASE WHEN lo.status = 'COMPLETED' AND DATE(lo.completed_at) = CURDATE() THEN 1 END) as completed_today,
        COUNT(CASE WHEN lot.scheduled_at IS NOT NULL AND DATE(lot.scheduled_at) = CURDATE() THEN 1 END) as scheduled_today
        FROM lab_orders lo
        LEFT JOIN lab_order_tests lot ON lo.order_id = lot.order_id
        WHERE lot.tested_by = (SELECT tech_id FROM lab_technicians WHERE user_id = ?) 
        OR lo.status IN ('PENDING', 'SCHEDULED')";
    $stmt_tech = $conn->prepare($tech_stats_query);
    $stmt_tech->bind_param("i", $user_id);
    $stmt_tech->execute();
    $quick_stats = $stmt_tech->get_result()->fetch_assoc();
} elseif ($role_name === 'Billing Clerk') {
    // Get billing clerk's daily stats
    $billing_stats_query = "SELECT 
        COUNT(CASE WHEN DATE(i.invoice_date) = CURDATE() THEN 1 END) as daily_invoices,
        COUNT(CASE WHEN DATE(pay.payment_date) = CURDATE() THEN 1 END) as daily_payments,
        COALESCE(SUM(CASE WHEN DATE(pay.payment_date) = CURDATE() THEN pay.amount END), 0) as daily_revenue,
        COUNT(CASE WHEN i.status = 'OVERDUE' THEN 1 END) as overdue_invoices
        FROM invoices i
        LEFT JOIN payments pay ON i.visit_id = pay.visit_id
        WHERE i.created_by = ? OR pay.received_by = ?";
    $stmt_billing = $conn->prepare($billing_stats_query);
    $stmt_billing->bind_param("ii", $user_id, $user_id);
    $stmt_billing->execute();
    $quick_stats = $stmt_billing->get_result()->fetch_assoc();
} elseif (strpos($role_name, 'Nurse') !== false) {
    // Get nurse's patient care stats
    $nurse_stats_query = "SELECT 
        COUNT(CASE WHEN pv.status = 'WAITING' THEN 1 END) as waiting_patients,
        COUNT(CASE WHEN pv.status = 'IN_CONSULTATION' THEN 1 END) as in_consultation,
        COUNT(CASE WHEN DATE(pv.registration_date) = CURDATE() THEN 1 END) as daily_patients,
        COUNT(CASE WHEN pp.status = 'SCHEDULED' AND DATE(pp.procedure_date) = CURDATE() THEN 1 END) as scheduled_procedures
        FROM patient_visits pv
        LEFT JOIN patient_procedures pp ON pv.visit_id = pp.visit_id
        WHERE DATE(pv.registration_date) = CURDATE()";
    $nurse_result = $conn->query($nurse_stats_query);
    $quick_stats = $nurse_result->fetch_assoc();
}

// Helper functions for activity formatting
function getActivityColor($action) {
    return match($action) {
        'CREATE' => 'success',
        'UPDATE' => 'primary',
        'DELETE' => 'danger',
        'LOGIN' => 'info',
        default => 'secondary'
    };
}

function getActivityIcon($action) {
    return match($action) {
        'CREATE' => 'ph-plus-circle',
        'UPDATE' => 'ph-pencil-circle',
        'DELETE' => 'ph-minus-circle',
        'LOGIN' => 'ph-sign-in',
        default => 'ph-bell'
    };
}

function formatActivityMessage($notification) {
    $action = $notification['action'];
    $module = $notification['module'];
    $user = $notification['created_by'] ?: 'System';
    
    return match($action) {
        'CREATE' => "New {$module} created by {$user}",
        'UPDATE' => "{$module} updated by {$user}",
        'DELETE' => "{$module} deleted by {$user}",
        'LOGIN' => "{$user} logged into the system",
        default => "System activity in {$module}"
    };
}

function getTimeAgo($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) return 'Just now';
    if ($diff < 3600) return floor($diff / 60) . 'm ago';
    if ($diff < 86400) return floor($diff / 3600) . 'h ago';
    if ($diff < 604800) return floor($diff / 86400) . 'd ago';
    return date('M j', $time);
}

// Function to get hospital settings
function getHospitalSetting($conn, $key) {
    $sql = "SELECT setting_value FROM system_settings WHERE setting_key = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $key);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        return $row['setting_value'];
    }
    return '';
}

$hospital_name = getHospitalSetting($conn, 'hospital_name') ?: 'ENT Medical Center';
$hospital_address = getHospitalSetting($conn, 'hospital_address') ?: '';
$hospital_phone = getHospitalSetting($conn, 'hospital_phone') ?: '';
$hospital_email = getHospitalSetting($conn, 'hospital_email') ?: '';
$hospital_website = getHospitalSetting($conn, 'hospital_website') ?: '';
$hospital_logo = getHospitalSetting($conn, 'hospital_logo') ?: 'assets/images/logo.png'; // Default logo path
?>

<header id="page-topbar">
    <div class="layout-width">
        <div class="navbar-header">
            <div class="d-flex">
                <!-- ENT HOSPITAL LOGO -->
                <div class="logo-container">
                <?php if (file_exists($hospital_logo)): ?>
                <img src="<?php echo htmlspecialchars($hospital_logo); ?>" alt="<?php echo htmlspecialchars($hospital_name); ?> Logo">
                <?php endif; ?>
            </div>

                <button type="button" class="btn btn-sm px-3 fs-16 header-item vertical-menu-btn topnav-hamburger" id="topnav-hamburger-icon">
                    <span class="hamburger-icon">
                        <span></span>
                        <span></span>
                        <span></span>
                    </span>
                </button>

                <!-- Enhanced Search for ENT Hospital System -->
                <form class="app-search d-none d-md-block" id="search-form">
                    <div class="position-relative">
                        <input type="text" class="form-control search-input" 
                               placeholder="Search patients, appointments, doctors..." 
                               autocomplete="off" id="search-options">
                        <span class="search-widget-icon">
                            <i class="ph-magnifying-glass"></i>
                        </span>
                        <div class="search-loading d-none">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>

                    <div class="dropdown-menu dropdown-menu-lg search-dropdown" id="search-dropdown">
                        <div data-simplebar style="max-height: 350px;">
                            <!-- Quick Actions -->
                            <div class="dropdown-header bg-light">
                                <h6 class="text-overflow text-muted mb-0 text-uppercase">
                                    <i class="ph-lightning me-1"></i>Quick Actions
                                </h6>
                            </div>

                            <div class="dropdown-item bg-transparent text-wrap p-2">
                                <div class="d-flex flex-wrap gap-1">
                                    <?php if ($role_name === 'Receptionist' || $role_name === 'Super Admin'): ?>
                                    <a href="register_patient.php" class="btn btn-soft-primary btn-sm">
                                        <i class="ph-user-plus me-1"></i>Register Patient
                                    </a>
                                    <a href="schedule_appointment.php" class="btn btn-soft-success btn-sm">
                                        <i class="ph-calendar-plus me-1"></i>Book Appointment
                                    </a>
                                    <?php endif; ?>
                                    <?php if (strpos($role_name, 'Doctor') !== false || $role_name === 'Super Admin'): ?>
                                    <a href="new_consultation.php" class="btn btn-soft-info btn-sm">
                                        <i class="ph-user-focus me-1"></i>New Consultation
                                    </a>
                                    <?php endif; ?>
                                    <?php if ($role_name === 'Billing Clerk' || $role_name === 'Super Admin'): ?>
                                    <a href="create_invoice.php" class="btn btn-soft-warning btn-sm">
                                        <i class="ph-receipt me-1"></i>Create Invoice
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- ENT Hospital Modules -->
                            <div class="dropdown-header bg-light">
                                <h6 class="text-overflow text-muted mb-1 text-uppercase">
                                    <i class="ph-hospital me-1"></i>ENT Hospital Modules
                                </h6>
                            </div>

                            <a href="list_patients.php" class="dropdown-item notify-item">
                                <i class="ph-address-book align-middle fs-18 text-primary me-2"></i>
                                <span>Patients</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+P</small>
                            </a>

                            <a href="list_appointments.php" class="dropdown-item notify-item">
                                <i class="ph-calendar align-middle fs-18 text-success me-2"></i>
                                <span>Appointments</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+A</small>
                            </a>

                            <?php if (strpos($role_name, 'Doctor') !== false || $role_name === 'Super Admin'): ?>
                            <a href="list_consultations.php" class="dropdown-item notify-item">
                                <i class="ph-user-focus align-middle fs-18 text-info me-2"></i>
                                <span>Consultations</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+C</small>
                            </a>
                            <?php endif; ?>

                            <?php if ($role_name === 'Lab Technician' || $role_name === 'Audiologist' || $role_name === 'Super Admin'): ?>
                            <a href="list_lab_orders.php" class="dropdown-item notify-item">
                                <i class="ph-test-tube align-middle fs-18 text-warning me-2"></i>
                                <span>Lab Orders</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+L</small>
                            </a>
                            <?php endif; ?>

                            <?php if ($role_name === 'Billing Clerk' || $role_name === 'Super Admin'): ?>
                            <a href="list_payments.php" class="dropdown-item notify-item">
                                <i class="ph-money align-middle fs-18 text-danger me-2"></i>
                                <span>Payments</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+M</small>
                            </a>
                            <?php endif; ?>

                            <!-- Search Results Container -->
                            <div id="search-results-container" style="display: none;">
                                <div class="dropdown-header bg-light">
                                    <h6 class="text-overflow text-muted mb-2 text-uppercase">
                                        <i class="ph-magnifying-glass me-1"></i>Search Results
                                    </h6>
                                </div>
                                <div id="search-results"></div>
                            </div>

                            <!-- Medical Staff -->
                            <?php if(!empty($team_members)): ?>
                            <div class="dropdown-header bg-light">
                                <h6 class="text-overflow text-muted mb-2 text-uppercase">
                                    <i class="ph-stethoscope me-1"></i>Medical Staff
                                </h6>
                            </div>

                            <div class="notification-list">
                                <?php foreach($team_members as $member): ?>
                                <a href="view_user.php?id=<?php echo $member['user_id']; ?>" class="dropdown-item notify-item py-2">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0 me-2">
                                            <?php if($member['profile_picture']): ?>
                                                <img src="assets/images/users/<?php echo $member['profile_picture']; ?>" 
                                                     class="rounded-circle avatar-xs" alt="user-pic">
                                            <?php else: ?>
                                                <div class="avatar-xs">
                                                    <span class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                        <?php echo strtoupper(substr($member['full_name'], 0, 1)); ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="m-0 fs-13"><?php echo htmlspecialchars($member['full_name']); ?></h6>
                                            <span class="fs-11 mb-0 text-muted">
                                                <?php echo htmlspecialchars($member['role_name']); ?>
                                            </span>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-xs">
                                                <span class="avatar-title bg-soft-success text-success rounded-circle">
                                                    <i class="ph-check fs-10"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        </div>

                        <div class="text-center p-3 border-top">
                            <a href="advanced_search.php" class="btn btn-primary btn-sm w-100">
                                <i class="ph-magnifying-glass me-1"></i>Advanced Search
                            </a>
                        </div>
                    </div>
                </form>
            </div>

            <div class="d-flex align-items-center">
                <!-- Country/Region Flag -->
                <div class="ms-1 header-item d-none d-sm-flex">
                    <img src="assets/images/flags/ke.svg" alt="Kenya Flag" class="me-2 rounded" height="20">
                    <span class="align-middle text-white fw-medium">Kenya</span>
                </div>

                <!-- Activity/Notifications Dropdown -->
                <div class="dropdown topbar-head-dropdown ms-1 header-item" id="notificationDropdown">
                    <button type="button" class="btn btn-icon btn-topbar btn-ghost-secondary rounded-circle" 
                            id="page-header-notifications-dropdown" data-bs-toggle="dropdown" 
                            data-bs-auto-close="outside" aria-haspopup="true" aria-expanded="false">
                        <i class='ph-bell fs-22'></i>
                        <?php if ($unread_count > 0): ?>
                        <span class="position-absolute topbar-badge fs-10 translate-middle badge rounded-pill bg-danger">
                            <?php echo min($unread_count, 99); ?>
                            <span class="visually-hidden">unread notifications</span>
                        </span>
                        <?php endif; ?>
                    </button>
                    
                    <div class="dropdown-menu dropdown-menu-lg dropdown-menu-end p-0" aria-labelledby="page-header-notifications-dropdown">
                        <!-- Header -->
                        <div class="dropdown-head bg-primary bg-pattern rounded-top">
                            <div class="p-3">
                                <div class="row align-items-center">
                                    <div class="col">
                                        <h6 class="m-0 fs-16 fw-semibold text-white">
                                            <i class="ph-bell me-1"></i>Hospital Activity
                                        </h6>
                                    </div>
                                    <div class="col-auto dropdown-tabs">
                                        <span class="badge bg-light-subtle text-body fs-13">
                                            <?php echo $unread_count; ?> New
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    
                        <!-- Content -->
                        <div class="tab-content position-relative" id="notificationItemsTabContent">
                            <div class="tab-pane fade show active py-2 ps-2" id="all-noti-tab" role="tabpanel">
                                <div data-simplebar style="max-height: 300px;" class="pe-2">
                                    <?php if(empty($notifications)): ?>
                                        <div class="text-center text-muted p-4">
                                            <i class="ph-bell-slash fs-1 text-muted mb-3 d-block"></i>
                                            <h6 class="mb-1">No recent activity</h6>
                                            <p class="mb-0 fs-12">When hospital activities occur, they'll appear here</p>
                                        </div>
                                    <?php else: ?>
                                        <?php foreach($notifications as $notification): ?>
                                            <div class="text-reset notification-item d-block dropdown-item position-relative">
                                                <div class="d-flex">
                                                    <div class="avatar-xs me-3 flex-shrink-0">
                                                        <span class="avatar-title bg-<?php echo getActivityColor($notification['action']); ?>-subtle text-<?php echo getActivityColor($notification['action']); ?> rounded-circle fs-16">
                                                            <i class="<?php echo getActivityIcon($notification['action']); ?>"></i>
                                                        </span>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="mt-0 mb-2 lh-base fs-13">
                                                            <?php echo formatActivityMessage($notification); ?>
                                                        </h6>
                                                        <p class="mb-0 fs-11 fw-medium text-uppercase text-muted">
                                                            <span>
                                                                <i class="ph-clock"></i> 
                                                                <?php echo getTimeAgo($notification['logged_at']); ?>
                                                            </span>
                                                        </p>
                                                    </div>
                                                    <div class="px-2 fs-15">
                                                        <div class="avatar-xs">
                                                            <span class="avatar-title bg-light text-muted rounded-circle">
                                                                <i class="ph-dots-three fs-12"></i>
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                                
                                <?php if(!empty($notifications)): ?>
                                <div class="p-2 border-top text-center">
                                    <div class="d-grid">
                                        <a class="btn btn-sm btn-link fw-semibold" href="activity_log.php">
                                            View All Activities <i class="ph-arrow-right align-middle"></i>
                                        </a>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- User Profile Dropdown -->
                <div class="dropdown ms-sm-3 header-item topbar-user">
                    <button type="button" class="btn shadow-none" id="page-header-user-dropdown" 
                            data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <span class="d-flex align-items-center">
                            <div class="me-2">
                                <?php if($profile_picture): ?>
                                    <img class="rounded-circle header-profile-user" 
                                         src="assets/images/users/<?php echo $profile_picture; ?>" 
                                         alt="Header Avatar">
                                <?php else: ?>
                                    <div class="avatar-xs">
                                        <span class="avatar-title bg-white text-primary rounded-circle">
                                            <?php echo strtoupper(substr($full_name, 0, 1)); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <span class="text-start ms-xl-2">
                                <span class="d-none d-xl-inline-block ms-1 fw-semibold user-name-text text-white">
                                    <?php echo htmlspecialchars($full_name); ?>
                                </span>
                                <span class="d-none d-xl-block ms-1 fs-13 user-name-sub-text text-white-50">
                                    <?php echo htmlspecialchars($role_name); ?>
                                </span>
                            </span>
                        </span>
                    </button>
                    
                    <div class="dropdown-menu dropdown-menu-end">
                        <!-- User Info Header -->
                        <div class="dropdown-header bg-light">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0 me-2">
                                    <?php if($profile_picture): ?>
                                        <img class="rounded-circle" 
                                             src="assets/images/users/<?php echo $profile_picture; ?>" 
                                             alt="Avatar" width="32" height="32">
                                    <?php else: ?>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-primary text-white rounded-circle">
                                                <?php echo strtoupper(substr($full_name, 0, 1)); ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0"><?php echo htmlspecialchars($full_name); ?></h6>
                                    <small class="text-muted"><?php echo htmlspecialchars($email); ?></small>
                                    <div class="mt-1">
                                        <span class="badge bg-soft-primary text-primary fs-11">
                                            <?php echo htmlspecialchars($role_name); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- Role-based Menu Items -->
                        <a class="dropdown-item" href="profile.php">
                            <i class="ph-user-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Profile</span>
                        </a>
                        
                        <?php if($role_name === 'Super Admin'): ?>
                        <a class="dropdown-item" href="hospital_settings.php">
                            <i class="ph-gear text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Hospital Settings</span>
                        </a>
                        
                        <a class="dropdown-item" href="list_users.php">
                            <i class="ph-users-three text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">User Management</span>
                        </a>
                        
                        <a class="dropdown-item" href="role_permissions.php">
                            <i class="ph-key text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Role Permissions</span>
                        </a>
                        
                        <a class="dropdown-item" href="backup_restore.php">
                            <i class="ph-database text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Backup & Restore</span>
                        </a>
                        
                        <?php elseif($role_name === 'Hospital Admin'): ?>
                        <a class="dropdown-item" href="list_patients.php">
                            <i class="ph-address-book text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">All Patients</span>
                        </a>
                        
                        <a class="dropdown-item" href="list_appointments.php">
                            <i class="ph-calendar text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Appointments</span>
                        </a>
                        
                        <a class="dropdown-item" href="financial_reports.php">
                            <i class="ph-chart-line text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Financial Reports</span>
                        </a>
                        
                        <a class="dropdown-item" href="list_doctors.php">
                            <i class="ph-stethoscope text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Medical Staff</span>
                        </a>
                        
                        <?php elseif(strpos($role_name, 'Doctor') !== false || strpos($role_name, 'Consultant') !== false): ?>
                        <a class="dropdown-item" href="my_appointments.php">
                            <i class="ph-calendar text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Appointments</span>
                            <?php if(isset($quick_stats['scheduled_appointments']) && $quick_stats['scheduled_appointments'] > 0): ?>
                                <span class="badge bg-primary ms-2 fs-11"><?php echo $quick_stats['scheduled_appointments']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="my_patients.php">
                            <i class="ph-address-book text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Patients</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_consultations.php">
                            <i class="ph-user-focus text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Consultations</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_procedures.php">
                            <i class="ph-activity text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Procedures</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_commissions.php">
                            <i class="ph-chart-bar text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Commission Tracker</span>
                        </a>
                        
                        <?php elseif($role_name === 'Receptionist'): ?>
                        <a class="dropdown-item" href="register_patient.php">
                            <i class="ph-user-plus text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Register Patient</span>
                        </a>
                        
                        <a class="dropdown-item" href="schedule_appointment.php">
                            <i class="ph-calendar-plus text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Book Appointment</span>
                        </a>
                        
                        <a class="dropdown-item" href="patient_checkin.php">
                            <i class="ph-sign-in text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Patient Check-in</span>
                            <?php if(isset($quick_stats['pending_checkins']) && $quick_stats['pending_checkins'] > 0): ?>
                                <span class="badge bg-warning ms-2 fs-11"><?php echo $quick_stats['pending_checkins']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="collect_payment.php">
                            <i class="ph-money text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Collect Payment</span>
                        </a>
                        
                        <a class="dropdown-item" href="send_reminders.php">
                            <i class="ph-bell text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Send Reminders</span>
                        </a>
                        
                        <?php elseif($role_name === 'Lab Technician' || $role_name === 'Audiologist'): ?>
                        <a class="dropdown-item" href="pending_lab_tests.php">
                            <i class="ph-clock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Pending Tests</span>
                            <?php if(isset($quick_stats['pending_tests']) && $quick_stats['pending_tests'] > 0): ?>
                                <span class="badge bg-danger ms-2 fs-11"><?php echo $quick_stats['pending_tests']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="inprogress_tests.php">
                            <i class="ph-arrows-clockwise text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">In Progress Tests</span>
                            <?php if(isset($quick_stats['in_progress_tests']) && $quick_stats['in_progress_tests'] > 0): ?>
                                <span class="badge bg-primary ms-2 fs-11"><?php echo $quick_stats['in_progress_tests']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="test_results_entry.php">
                            <i class="ph-test-tube text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Enter Results</span>
                        </a>
                        
                        <a class="dropdown-item" href="equipment_log.php">
                            <i class="ph-gear text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Equipment Log</span>
                        </a>
                        
                        <?php elseif($role_name === 'Billing Clerk'): ?>
                        <a class="dropdown-item" href="create_invoice.php">
                            <i class="ph-receipt text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Create Invoice</span>
                        </a>
                        
                        <a class="dropdown-item" href="list_invoices.php">
                            <i class="ph-list text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">All Invoices</span>
                        </a>
                        
                        <a class="dropdown-item" href="overdue_invoices.php">
                            <i class="ph-warning text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Overdue Invoices</span>
                            <?php if(isset($quick_stats['overdue_invoices']) && $quick_stats['overdue_invoices'] > 0): ?>
                                <span class="badge bg-danger ms-2 fs-11"><?php echo $quick_stats['overdue_invoices']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="insurance_claims.php">
                            <i class="ph-shield-check text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Insurance Claims</span>
                        </a>
                        
                        <a class="dropdown-item" href="payment_reconciliation.php">
                            <i class="ph-check-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Payment Reconciliation</span>
                        </a>
                        
                        <?php elseif(strpos($role_name, 'Nurse') !== false): ?>
                        <a class="dropdown-item" href="ward_patients.php">
                            <i class="ph-heart text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Ward Patients</span>
                            <?php if(isset($quick_stats['waiting_patients']) && $quick_stats['waiting_patients'] > 0): ?>
                                <span class="badge bg-warning ms-2 fs-11"><?php echo $quick_stats['waiting_patients']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="patient_vitals.php">
                            <i class="ph-activity text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Patient Vitals</span>
                        </a>
                        
                        <a class="dropdown-item" href="medication_schedule.php">
                            <i class="ph-pill text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Medication Schedule</span>
                        </a>
                        
                        <a class="dropdown-item" href="pre_procedure_care.php">
                            <i class="ph-first-aid text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Pre-procedure Care</span>
                            <?php if(isset($quick_stats['scheduled_procedures']) && $quick_stats['scheduled_procedures'] > 0): ?>
                                <span class="badge bg-info ms-2 fs-11"><?php echo $quick_stats['scheduled_procedures']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="nursing_notes.php">
                            <i class="ph-note text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Nursing Notes</span>
                        </a>
                        
                        <?php elseif($role_name === 'Medical Records'): ?>
                        <a class="dropdown-item" href="all_patient_records.php">
                            <i class="ph-file-text text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Patient Records</span>
                        </a>
                        
                        <a class="dropdown-item" href="document_upload.php">
                            <i class="ph-upload text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Upload Documents</span>
                        </a>
                        
                        <a class="dropdown-item" href="share_medical_data.php">
                            <i class="ph-share-fat text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Share Medical Data</span>
                        </a>
                        
                        <a class="dropdown-item" href="records_audit_trail.php">
                            <i class="ph-lock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Audit Trail</span>
                        </a>
                        <?php endif; ?>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- System Info -->
                        <?php if($phone_number): ?>
                        <div class="dropdown-item-text">
                            <small class="text-muted">
                                <i class="ph-phone text-muted me-1"></i>
                                Phone: <?php echo htmlspecialchars($phone_number); ?>
                            </small>
                        </div>
                        <?php endif; ?>
                        
                        <div class="dropdown-item-text">
                            <small class="text-muted">
                                <i class="ph-clock text-muted me-1"></i>
                                Last Login: <?php echo $user_data['last_login'] ? date('M j, Y g:i A', strtotime($user_data['last_login'])) : 'First time'; ?>
                            </small>
                        </div>
                        
                        <?php if($user_data['branch_id']): ?>
                        <div class="dropdown-item-text">
                            <small class="text-muted">
                                <i class="ph-buildings text-muted me-1"></i>
                                Branch: <?php 
                                $branch_query = "SELECT branch_name FROM hospital_branches WHERE branch_id = ?";
                                $stmt_branch = $conn->prepare($branch_query);
                                $stmt_branch->bind_param("i", $user_data['branch_id']);
                                $stmt_branch->execute();
                                $branch_result = $stmt_branch->get_result()->fetch_assoc();
                                echo htmlspecialchars($branch_result['branch_name'] ?? 'Main Branch');
                                ?>
                            </small>
                        </div>
                        <?php endif; ?>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- Account Actions -->
                        <a class="dropdown-item" href="change_password.php">
                            <i class="ph-lock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Change Password</span>
                        </a>
                        
                        <a class="dropdown-item" href="#" onclick="lockScreen()" title="Lock your session">
                            <i class="ph-lock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Lock Screen</span>
                            <small class="text-muted ms-auto">Ctrl+L</small>
                        </a>
                        
                        <div class="dropdown-divider"></div>
                        
                        <a class="dropdown-item text-danger" href="logout.php">
                            <i class="ph-sign-out text-danger fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Logout</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Add proper spacing after topbar -->
<div class="topbar-spacer"></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Enhanced search functionality for ENT hospital system
    const searchInput = document.getElementById('search-options');
    const searchDropdown = document.getElementById('search-dropdown');
    const resultsContainer = document.getElementById('search-results-container');
    const resultsDiv = document.getElementById('search-results');
    const searchLoading = document.querySelector('.search-loading');
    
    let searchTimeout;
    
    if (searchInput) {
        // Search input handler
        searchInput.addEventListener('input', function(e) {
            const query = e.target.value.trim();
            
            clearTimeout(searchTimeout);
            
            if (query.length >= 3) {
                showSearchLoading(true);
                searchTimeout = setTimeout(() => {
                    performSearch(query);
                }, 300);
            } else {
                hideSearchResults();
                showSearchLoading(false);
            }
        });
        
        // Show dropdown on focus
        searchInput.addEventListener('focus', function() {
            searchDropdown.classList.add('show');
        });
        
        // Hide dropdown when clicking outside
        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !searchDropdown.contains(e.target)) {
                searchDropdown.classList.remove('show');
            }
        });
        
        // Keyboard navigation for search
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                searchDropdown.classList.remove('show');
                searchInput.blur();
            }
        });
    }
    
    function showSearchLoading(show) {
        if (searchLoading) {
            searchLoading.classList.toggle('d-none', !show);
        }
    }
    
    function hideSearchResults() {
        if (resultsContainer) {
            resultsContainer.style.display = 'none';
        }
    }
    
    function performSearch(query) {
        fetch('ent_search_api.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({ query: query })
        })
        .then(response => response.json())
        .then(data => {
            showSearchLoading(false);
            if (data.success && data.results.length > 0) {
                displaySearchResults(data.results);
                resultsContainer.style.display = 'block';
            } else {
                displayNoResults(query);
                resultsContainer.style.display = 'block';
            }
        })
        .catch(error => {
            console.error('Search error:', error);
            showSearchLoading(false);
            hideSearchResults();
        });
    }
    
    function displaySearchResults(results) {
        resultsDiv.innerHTML = results.map(result => {
            const icon = getResultIcon(result.type);
            const url = getResultUrl(result);
            const badge = getResultBadge(result.type);
            
            return `
                <a href="${url}" class="dropdown-item notify-item">
                    <div class="d-flex align-items-center">
                        <div class="avatar-xs me-3 flex-shrink-0">
                            <span class="avatar-title ${badge} rounded-circle fs-16">
                                <i class="${icon}"></i>
                            </span>
                        </div>
                        <div class="flex-grow-1">
                            <h6 class="mt-0 mb-1 fs-13">${getResultTitle(result)}</h6>
                            <p class="mb-0 fs-11 text-muted">${getResultSubtitle(result)}</p>
                        </div>
                        <div class="flex-shrink-0">
                            <span class="badge ${getBadgeClass(result.type)} fs-11">${result.type}</span>
                        </div>
                    </div>
                </a>
            `;
        }).join('');
    }
    
    function displayNoResults(query) {
        resultsDiv.innerHTML = `
            <div class="text-center p-3">
                <i class="ph-magnifying-glass fs-1 text-muted mb-2 d-block"></i>
                <h6 class="mb-1">No results found</h6>
                <p class="mb-0 fs-12 text-muted">No matches for "${query}"</p>
            </div>
        `;
    }
    
    function getResultIcon(type) {
        const icons = {
            'PATIENT': 'ph-address-book',
            'APPOINTMENT': 'ph-calendar',
            'CONSULTATION': 'ph-user-focus',
            'DOCTOR': 'ph-stethoscope',
            'LAB_ORDER': 'ph-test-tube',
            'PAYMENT': 'ph-money',
            'INVOICE': 'ph-receipt',
            'USER': 'ph-user-circle'
        };
        return icons[type] || 'ph-magnifying-glass';
    }
    
    function getResultBadge(type) {
        const badges = {
            'PATIENT': 'bg-soft-primary text-primary',
            'APPOINTMENT': 'bg-soft-success text-success',
            'CONSULTATION': 'bg-soft-info text-info',
            'DOCTOR': 'bg-soft-warning text-warning',
            'LAB_ORDER': 'bg-soft-secondary text-secondary',
            'PAYMENT': 'bg-soft-success text-success',
            'INVOICE': 'bg-soft-danger text-danger',
            'USER': 'bg-soft-primary text-primary'
        };
        return badges[type] || 'bg-soft-light text-muted';
    }
    
    function getBadgeClass(type) {
        const classes = {
            'PATIENT': 'bg-soft-primary text-primary',
            'APPOINTMENT': 'bg-soft-success text-success',
            'CONSULTATION': 'bg-soft-info text-info',
            'DOCTOR': 'bg-soft-warning text-warning',
            'LAB_ORDER': 'bg-soft-secondary text-secondary',
            'PAYMENT': 'bg-soft-success text-success',
            'INVOICE': 'bg-soft-danger text-danger',
            'USER': 'bg-soft-primary text-primary'
        };
        return classes[type] || 'bg-soft-light text-muted';
    }
    
    function getResultUrl(result) {
        const baseUrls = {
            'PATIENT': 'view_patient.php?id=',
            'APPOINTMENT': 'view_appointment.php?id=',
            'CONSULTATION': 'view_consultation.php?id=',
            'DOCTOR': 'view_doctor.php?id=',
            'LAB_ORDER': 'view_lab_order.php?id=',
            'PAYMENT': 'view_payment.php?id=',
            'INVOICE': 'view_invoice.php?id=',
            'USER': 'view_user.php?id='
        };
        
        const identifier = result.patient_id || result.appointment_id || 
                          result.consultation_id || result.doctor_id || 
                          result.order_id || result.payment_id || 
                          result.invoice_id || result.user_id;
        return baseUrls[result.type] + encodeURIComponent(identifier);
    }
    
    function getResultTitle(result) {
        switch(result.type) {
            case 'PATIENT':
                return `${result.first_name || ''} ${result.last_name || ''}`.trim();
            case 'APPOINTMENT':
                return result.appointment_number;
            case 'CONSULTATION':
                return result.consultation_number;
            case 'DOCTOR':
                return result.full_name;
            case 'LAB_ORDER':
                return result.order_number;
            case 'PAYMENT':
                return result.payment_number;
            case 'INVOICE':
                return result.invoice_number;
            case 'USER':
                return result.full_name;
            default:
                return 'Unknown';
        }
    }
    
    function getResultSubtitle(result) {
        switch(result.type) {
            case 'PATIENT':
                return `Patient • ${result.patient_number || ''}`;
            case 'APPOINTMENT':
                return `Appointment • ${result.appointment_date || ''}`;
            case 'CONSULTATION':
                return `Consultation • KSh ${result.consultation_fee || '0'}`;
            case 'DOCTOR':
                return `Doctor • ${result.specialization || ''}`;
            case 'LAB_ORDER':
                return `Lab Order • ${result.status || ''}`;
            case 'PAYMENT':
                return `Payment • KSh ${result.amount || '0'}`;
            case 'INVOICE':
                return `Invoice • KSh ${result.total_amount || '0'}`;
            case 'USER':
                return `User • ${result.role_name || ''}`;
            default:
                return '';
        }
    }
    
    // Auto-refresh activity feed every 2 minutes
    setInterval(refreshActivityFeed, 120000);
    
    function refreshActivityFeed() {
        fetch('get_activity_feed.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateActivityCount(data.count);
                }
            })
            .catch(error => console.error('Activity refresh error:', error));
    }
    
    function updateActivityCount(count) {
        const countBadge = document.querySelector('.topbar-badge');
        const dropdownCount = document.querySelector('.dropdown-tabs .badge');
        
        if (count > 0) {
            if (countBadge) {
                countBadge.textContent = Math.min(count, 99);
                countBadge.style.display = '';
            }
            if (dropdownCount) {
                dropdownCount.textContent = `${count} New`;
            }
        } else {
            if (countBadge) {
                countBadge.style.display = 'none';
            }
            if (dropdownCount) {
                dropdownCount.textContent = '0 New';
            }
        }
    }
});

// Lock screen functionality
function lockScreen() {
    if (confirm('Are you sure you want to lock your screen?')) {
        fetch('lock_screen.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.location.href = 'lock_screen.php';
            }
        })
        .catch(error => {
            console.error('Lock screen error:', error);
            // Fallback to logout if lock screen fails
            window.location.href = 'logout.php';
        });
    }
}

// Enhanced keyboard shortcuts for ENT hospital system
document.addEventListener('keydown', function(e) {
    // Only trigger if not in an input field
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) {
        return;
    }
    
    // Ctrl/Cmd + K for search
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        document.getElementById('search-options')?.focus();
    }
    
    // Ctrl/Cmd + Shift + P for patients
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'P') {
        e.preventDefault();
        window.location.href = 'list_patients.php';
    }
    
    // Ctrl/Cmd + Shift + A for appointments
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'A') {
        e.preventDefault();
        window.location.href = 'list_appointments.php';
    }
    
    // Ctrl/Cmd + Shift + C for consultations
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'C') {
        e.preventDefault();
        window.location.href = 'list_consultations.php';
    }
    
    // Ctrl/Cmd + Shift + L for lab orders
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'L') {
        e.preventDefault();
        window.location.href = 'list_lab_orders.php';
    }
    
    // Ctrl/Cmd + Shift + M for payments (Money)
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'M') {
        e.preventDefault();
        window.location.href = 'list_payments.php';
    }
    
    // Ctrl/Cmd + L for lock screen
    if ((e.ctrlKey || e.metaKey) && e.key === 'l') {
        e.preventDefault();
        lockScreen();
    }
    
    // Escape to close any open dropdowns
    if (e.key === 'Escape') {
        // Close search dropdown
        document.getElementById('search-dropdown')?.classList.remove('show');
        // Close notification dropdown
        document.querySelector('#notificationDropdown .dropdown-menu')?.classList.remove('show');
        // Close user dropdown
        document.querySelector('.topbar-user .dropdown-menu')?.classList.remove('show');
    }
});
</script>

<style>
/* Enhanced topbar styles for ENT Hospital System */
#page-topbar {
    background: linear-gradient(135deg, #ffffff 0%, #f8fffe 30%, #f0fdf4 100%) !important;
    border-right: 4px solid var(--primary-green);
    box-shadow: 0 2px 20px rgba(0,0,0,0.1);
}


.navbar-header {
    padding: 0 1.5rem;
}

.logo-container {
            margin-bottom: 20px;
        }
        
        .logo-container img {
            max-height: 80px;
            max-width: 250px;
            object-fit: contain;
        }

/* Enhanced search styles */
.app-search {
    margin-left: 1.5rem;
    min-width: 320px;
    position: relative;
}

/* Enhanced visibility for light backgrounds */
.search-input {
    background: rgba(255, 255, 255, 0.85);
    border: 1px solid rgba(0, 0, 0, 0.1);
    color: #1f2937; /* dark gray text for contrast */
    padding-left: 45px;
    padding-right: 45px;
    border-radius: 25px;
    backdrop-filter: blur(8px);
    transition: all 0.3s ease;
}

.search-input::placeholder {
    color: rgba(75, 85, 99, 0.6); /* softer gray placeholder */
}

.search-input:focus {
    background: #ffffff;
    border-color: var(--primary-green);
    box-shadow: 0 0 0 0.2rem rgba(16, 185, 129, 0.25); /* soft green glow */
    color: #111827;
}

.search-widget-icon {
    position: absolute;
    top: 50%;
    left: 15px;
    transform: translateY(-50%);
    color: var(--primary-green);
    z-index: 10;
}

.search-loading {
    position: absolute;
    top: 50%;
    right: 15px;
    transform: translateY(-50%);
    z-index: 10;
}

/* Dropdown remains subtle */
.search-dropdown {
    width: 450px;
    border: none;
    border-radius: 15px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.1);
    margin-top: 10px;
}

.search-dropdown .dropdown-header {
    background: #f8f9fa;
    border-radius: 10px 10px 0 0;
    margin: 0;
    padding: 10px 15px;
    border-bottom: 1px solid #e9ecef;
}

.search-dropdown .dropdown-item {
    padding: 8px 15px;
    border-radius: 8px;
    margin: 2px 8px;
    transition: all 0.2s ease;
}

.search-dropdown .dropdown-item:hover {
    background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
    transform: translateX(5px);
}


/* Notification styles */
.notification-item {
    transition: all 0.2s ease;
    border-radius: 8px;
    margin: 2px;
}

.notification-item:hover {
    background: linear-gradient(135deg, rgba(5, 150, 105, 0.05) 0%, rgba(16, 185, 129, 0.05) 100%);
    transform: translateX(3px);
}

/* User profile styles */
.header-profile-user {
    width: 36px;
    height: 36px;
    object-fit: cover;
    border: 2px solid rgba(255, 255, 255, 0.3);
    transition: all 0.3s ease;
}

.topbar-user:hover .header-profile-user {
    border-color: rgba(255, 255, 255, 0.6);
    transform: scale(1.05);
}

.topbar-badge {
    top: -8px;
    right: -8px;
    min-width: 18px;
    height: 18px;
    font-size: 10px;
    line-height: 1;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

/* Button styles */
.btn-icon {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.btn-ghost-secondary {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: white;
}

.btn-ghost-secondary:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.3);
    color: white;
    transform: translateY(-2px);
}

/* Logo styles */
.logo img {
    transition: all 0.3s ease;
}

.logo:hover img {
    transform: scale(1.05);
}

/* Hamburger menu */
.topnav-hamburger {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: white;
    transition: all 0.3s ease;
}

.topnav-hamburger:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: rotate(90deg);
}

/* Country flag section */
.header-item img {
    transition: all 0.3s ease;
}

.header-item:hover img {
    transform: scale(1.1);
}

/* Dropdown menu enhancements */
.dropdown-menu {
    border: none;
    border-radius: 12px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
    backdrop-filter: blur(10px);
}

.dropdown-header {
    font-weight: 600;
    color: #495057;
    background: #f8f9fa;
    border-radius: 8px;
    margin: 5px;
    padding: 8px 12px;
}

.dropdown-item {
    padding: 8px 15px;
    border-radius: 6px;
    margin: 1px 5px;
    transition: all 0.2s ease;
}

.dropdown-item:hover {
    background: linear-gradient(135deg, #059669 0%, #10b981 100%);
    color: white;
    transform: translateX(3px);
}

.dropdown-item i {
    width: 20px;
    text-align: center;
}

/* Badge enhancements */
.badge {
    font-weight: 500;
    border-radius: 6px;
    padding: 4px 8px;
}

/* Avatar enhancements */
.avatar-xs {
    width: 24px;
    height: 24px;
}

.avatar-sm {
    width: 32px;
    height: 32px;
}

.avatar-title {
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 12px;
}

/* Responsive adjustments */
@media (max-width: 991.98px) {
    .app-search {
        display: none !important;
    }
    
    .user-name-text,
    .user-name-sub-text {
        display: none !important;
    }
    
    .navbar-header {
        padding: 0 1rem;
    }
}

@media (max-width: 767.98px) {
    .header-item.d-none.d-sm-flex {
        display: none !important;
    }
    
    .dropdown-menu {
        width: 280px;
        max-width: 90vw;
    }
    
    .search-dropdown {
        width: 320px;
        max-width: 95vw;
    }
}

/* Loading spinner */
.spinner-border-sm {
    width: 1rem;
    height: 1rem;
}

/* Custom scrollbar for dropdown */
.dropdown-menu [data-simplebar] {
    scrollbar-width: thin;
    scrollbar-color: #cbd5e0 #f7fafc;
}

.dropdown-menu [data-simplebar]::-webkit-scrollbar {
    width: 4px;
}

.dropdown-menu [data-simplebar]::-webkit-scrollbar-track {
    background: #f7fafc;
    border-radius: 2px;
}

.dropdown-menu [data-simplebar]::-webkit-scrollbar-thumb {
    background: #cbd5e0;
    border-radius: 2px;
}

.dropdown-menu [data-simplebar]::-webkit-scrollbar-thumb:hover {
    background: #a0aec0;
}

/* Animation for smooth transitions */
.dropdown-menu {
    opacity: 0;
    transform: translateY(-10px);
    transition: all 0.3s ease;
}

.dropdown-menu.show {
    opacity: 1;
    transform: translateY(0);
}

/* Focus states for accessibility */
.btn:focus,
.dropdown-item:focus {
    outline: 2px solid rgba(255, 255, 255, 0.5);
    outline-offset: 2px;
}

.search-input:focus {
    outline: none;
}

/* Performance optimization */
* {
    backface-visibility: hidden;
    -webkit-backface-visibility: hidden;
}

/* Fix topbar overlap issue */
#page-topbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1030;
    height: 70px; /* Define explicit height */
}

/* CRITICAL: Topbar spacer styling */
.topbar-spacer {
    height: 70px; /* Match topbar height exactly */
    width: 100%;
    flex-shrink: 0;
    background: transparent;
}

/* Alternative/additional approach - body padding */
body {
    padding-top: 70px; /* Global padding to account for fixed header */
}

/* Ensure first content elements have extra spacing */
.page-header:first-of-type,
.form-card:first-of-type,
.filter-card:first-of-type {
    margin-top: 20px;
}

/* ENT Hospital specific color scheme */
.bg-primary {
    background-color: #059669 !important;
}

.text-primary {
    color: #059669 !important;
}

.btn-primary {
    background-color: #059669;
    border-color: #059669;
}

.btn-primary:hover {
    background-color: #047857;
    border-color: #047857;
}

.badge-primary {
    background-color: #059669;
}

/* Medical theme colors */
.bg-soft-primary {
    background-color: rgba(5, 150, 105, 0.1) !important;
}

.text-soft-primary {
    color: #059669 !important;
}

/* Emergency/urgent colors */
.badge-danger {
    background-color: #dc2626;
}

.text-danger {
    color: #dc2626 !important;
}

/* Success colors for completed actions */
.badge-success {
    background-color: #16a34a;
}

.text-success {
    color: #16a34a !important;
}

/* Warning colors for pending/scheduled */
.badge-warning {
    background-color: #d97706;
}

.text-warning {
    color: #d97706 !important;
}

/* Info colors for in-progress */
.badge-info {
    background-color: #0891b2;
}

.text-info {
    color: #0891b2 !important;
}

/* Responsive adjustments */
@media (max-width: 991.98px) {
    #page-topbar { height: 60px; }
    .topbar-spacer { height: 60px; }
    body { padding-top: 60px; }
}

@media (max-width: 767.98px) {
    #page-topbar { height: 55px; }
    .topbar-spacer { height: 55px; }
    body { padding-top: 55px; }
}

/* ENT Hospital specific animations */
@keyframes medical-pulse {
    0% { 
        box-shadow: 0 0 0 0 rgba(5, 150, 105, 0.7);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(5, 150, 105, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(5, 150, 105, 0);
    }
}

.medical-pulse {
    animation: medical-pulse 2s infinite;
}

/* Medical staff indicators */
.staff-online {
    position: relative;
}

.staff-online::after {
    content: '';
    position: absolute;
    top: -2px;
    right: -2px;
    width: 8px;
    height: 8px;
    background-color: #16a34a;
    border-radius: 50%;
    border: 2px solid white;
}

/* Emergency notification styling */
.emergency-notification {
    background: linear-gradient(135deg, #dc2626 0%, #ef4444 100%);
    color: white;
    animation: medical-pulse 1s infinite;
}

/* Quick stats styling */
.quick-stat-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    padding: 12px 16px;
    margin: 4px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transition: all 0.3s ease;
}

.quick-stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.quick-stat-value {
    font-size: 1.5rem;
    font-weight: 700;
    color: #059669;
    margin-bottom: 4px;
}

.quick-stat-label {
    font-size: 0.75rem;
    color: #6b7280;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}
</style>