<?php 
session_start();
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 proper Healthcare EMR schema alignment
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name, b.branch_name, b.branch_code 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     LEFT JOIN branches b ON u.branch_id = b.branch_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'];
    $branch_name = $user_data['branch_name'];
    $staff_number = $user_data['staff_number'];
    $profile_picture = $user_data['profile_picture'];
    $commission_rate = $user_data['commission_rate'];
    $license_number = $user_data['license_number'];
    $phone_number = $user_data['phone_number'];
}

// Fetch recent activity from activity_log (using as notifications)
$notifications_query = "SELECT al.log_id, al.action, al.module, al.record_type, 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', 'PATIENT_REGISTERED', 'CONSULTATION_COMPLETED', 'PAYMENT_RECEIVED', 'LAB_ORDER_CREATED')
                       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 ('PATIENT_REGISTERED', 'CONSULTATION_COMPLETED', 'PAYMENT_RECEIVED', 'LAB_ORDER_CREATED')";
$unread_result = $conn->query($unread_count_query);
$unread_count = $unread_result ? $unread_result->fetch_assoc()['count'] : 0;

// Get team members from the same branch
$team_query = "SELECT u.full_name, u.staff_number, ur.role_name, u.profile_picture 
              FROM users u 
              LEFT JOIN user_roles ur ON u.role_id = ur.role_id 
              WHERE u.branch_id = ? AND u.status = 'ACTIVE' AND u.user_id != ? 
              ORDER BY u.full_name
              LIMIT 5";
$stmt_team = $conn->prepare($team_query);
$stmt_team->bind_param("ii", $user_data['branch_id'], $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 === 'Doctor') {
    // Get doctor's today stats
    $doctor_stats_query = "SELECT 
        COUNT(c.consultation_id) as consultations_today,
        COALESCE(SUM(c.consultation_fee), 0) as revenue_today,
        COALESCE(SUM(c.doctor_commission), 0) as commission_today
        FROM doctors d
        LEFT JOIN consultations c ON d.doctor_id = c.doctor_id 
            AND DATE(c.started_at) = CURDATE() 
            AND c.status = 'COMPLETED'
        WHERE d.user_id = ?";
    $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 today stats
    $reception_stats_query = "SELECT 
        COUNT(pv.visit_id) as visits_registered,
        COUNT(p.payment_id) as payments_processed,
        COALESCE(SUM(p.amount), 0) as payments_total
        FROM users u
        LEFT JOIN patient_visits pv ON u.user_id = pv.registered_by 
            AND DATE(pv.registration_date) = CURDATE()
        LEFT JOIN payments p ON u.user_id = p.received_by 
            AND DATE(p.payment_date) = CURDATE()
        WHERE u.user_id = ?";
    $stmt_reception = $conn->prepare($reception_stats_query);
    $stmt_reception->bind_param("i", $user_id);
    $stmt_reception->execute();
    $quick_stats = $stmt_reception->get_result()->fetch_assoc();
} elseif ($role_name === 'Lab Technician') {
    // Get lab tech's today stats
    $lab_stats_query = "SELECT 
        COUNT(lo.order_id) as lab_orders_today,
        COUNT(CASE WHEN lot.status = 'COMPLETED' THEN 1 END) as tests_completed,
        COUNT(CASE WHEN lot.status = 'PENDING' THEN 1 END) as tests_pending
        FROM users u
        LEFT JOIN lab_orders lo ON DATE(lo.ordered_at) = CURDATE()
        LEFT JOIN lab_order_tests lot ON lo.order_id = lot.order_id 
            AND (lot.tested_by = u.user_id OR lot.verified_by = u.user_id)
        WHERE u.user_id = ?";
    $stmt_lab = $conn->prepare($lab_stats_query);
    $stmt_lab->bind_param("i", $user_id);
    $stmt_lab->execute();
    $quick_stats = $stmt_lab->get_result()->fetch_assoc();
}

// Helper functions for activity formatting
function getActivityColor($action) {
    return match($action) {
        'PATIENT_REGISTERED' => 'primary',
        'CONSULTATION_COMPLETED' => 'success',
        'PAYMENT_RECEIVED' => 'info',
        'LAB_ORDER_CREATED' => 'warning',
        'LOGIN' => 'secondary',
        default => 'secondary'
    };
}

function getActivityIcon($action) {
    return match($action) {
        'PATIENT_REGISTERED' => 'ph-user-plus',
        'CONSULTATION_COMPLETED' => 'ph-chat-circle-dots',
        'PAYMENT_RECEIVED' => 'ph-credit-card',
        'LAB_ORDER_CREATED' => 'ph-test-tube',
        'LOGIN' => 'ph-sign-in',
        default => 'ph-bell'
    };
}

function formatActivityMessage($notification) {
    $action = $notification['action'];
    $module = $notification['module'];
    $user = $notification['created_by'] ?: 'System';
    
    return match($action) {
        'PATIENT_REGISTERED' => "New patient registered by {$user}",
        'CONSULTATION_COMPLETED' => "Consultation completed by {$user}",
        'PAYMENT_RECEIVED' => "Payment received by {$user}",
        'LAB_ORDER_CREATED' => "Lab order created 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);
}
?>

<header id="page-topbar">
    <div class="layout-width">
        <div class="navbar-header">
            <div class="d-flex">
                <!-- LOGO -->
                <div class="navbar-brand-box horizontal-logo">
                    <a href="index.php" class="logo logo-dark">
                        <span class="logo-sm">
                            <img src="assets/images/logo/healthcare_logo.png" alt="Healthcare EMR" height="40">
                        </span>
                        <span class="logo-lg">
                            <img src="assets/images/logo/healthcare_logo.png" alt="Healthcare EMR System" height="40">
                        </span>
                    </a>

                    <a href="index.php" class="logo logo-light">
                        <span class="logo-sm">
                            <img src="assets/images/logo/healthcare_logo_white.png" alt="Healthcare EMR" height="40">
                        </span>
                        <span class="logo-lg">
                            <img src="assets/images/logo/healthcare_logo_white.png" alt="Healthcare EMR System" height="40">
                        </span>
                    </a>
                </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 Healthcare EMR -->
                <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, visits, lab orders..." 
                               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">
                                    <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="register_visit.php" class="btn btn-soft-success btn-sm">
                                        <i class="ph-calendar-plus me-1"></i>New Visit
                                    </a>
                                    <a href="active_consultations.php" class="btn btn-soft-info btn-sm">
                                        <i class="ph-chat-circle-dots me-1"></i>Consultations
                                    </a>
                                    <a href="pending_lab_orders.php" class="btn btn-soft-warning btn-sm">
                                        <i class="ph-test-tube me-1"></i>Lab Orders
                                    </a>
                                </div>
                            </div>

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

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

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

                            <a href="list_consultations.php" class="dropdown-item notify-item">
                                <i class="ph-chat-circle-dots align-middle fs-18 text-info me-2"></i>
                                <span>Consultations</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+C</small>
                            </a>

                            <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>Laboratory</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+L</small>
                            </a>

                            <a href="list_payments.php" class="dropdown-item notify-item">
                                <i class="ph-credit-card align-middle fs-18 text-danger me-2"></i>
                                <span>Billing & Payments</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+B</small>
                            </a>

                            <a href="daily_revenue.php" class="dropdown-item notify-item">
                                <i class="ph-chart-bar align-middle fs-18 text-secondary me-2"></i>
                                <span>Reports & Analytics</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+R</small>
                            </a>

                            <!-- 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>

                            <!-- Team Members -->
                            <?php if(!empty($team_members)): ?>
                            <div class="dropdown-header bg-light">
                                <h6 class="text-overflow text-muted mb-2 text-uppercase">
                                    <i class="ph-users me-1"></i>
                                    <?php echo $branch_name ?: 'Team'; ?> Members
                                </h6>
                            </div>

                            <div class="notification-list">
                                <?php foreach($team_members as $member): ?>
                                <a href="view_staff.php?id=<?php echo $member['staff_number']; ?>" 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']); ?>
                                                <?php if($member['staff_number']): ?>
                                                    | <?php echo $member['staff_number']; ?>
                                                <?php endif; ?>
                                            </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>

                <!-- Quick Stats (based on user role) -->
                <?php if(!empty($quick_stats)): ?>
                <div class="dropdown topbar-head-dropdown ms-1 header-item d-none d-lg-block">
                    <button type="button" class="btn btn-icon btn-topbar btn-ghost-secondary rounded-circle" 
                            data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <i class='ph-chart-line fs-22'></i>
                    </button>
                    <div class="dropdown-menu dropdown-menu-end">
                        <div class="dropdown-header">
                            <h6 class="mb-0">Today's Performance</h6>
                        </div>
                        
                        <?php if($role_name === 'Doctor'): ?>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Consultations:</span>
                                    <strong><?php echo $quick_stats['consultations_today']; ?></strong>
                                </div>
                            </div>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Revenue:</span>
                                    <strong>KES <?php echo number_format($quick_stats['revenue_today'], 2); ?></strong>
                                </div>
                            </div>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Commission:</span>
                                    <strong>KES <?php echo number_format($quick_stats['commission_today'], 2); ?></strong>
                                </div>
                            </div>
                        <?php elseif($role_name === 'Receptionist'): ?>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Visits Registered:</span>
                                    <strong><?php echo $quick_stats['visits_registered']; ?></strong>
                                </div>
                            </div>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Payments Processed:</span>
                                    <strong><?php echo $quick_stats['payments_processed']; ?></strong>
                                </div>
                            </div>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Total Collected:</span>
                                    <strong>KES <?php echo number_format($quick_stats['payments_total'], 2); ?></strong>
                                </div>
                            </div>
                        <?php elseif($role_name === 'Lab Technician'): ?>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Lab Orders:</span>
                                    <strong><?php echo $quick_stats['lab_orders_today']; ?></strong>
                                </div>
                            </div>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Tests Completed:</span>
                                    <strong><?php echo $quick_stats['tests_completed']; ?></strong>
                                </div>
                            </div>
                            <div class="dropdown-item-text">
                                <div class="d-flex justify-content-between">
                                    <span>Tests Pending:</span>
                                    <strong><?php echo $quick_stats['tests_pending']; ?></strong>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="my_performance.php">
                            <i class="ph-chart-bar me-1"></i>View Full Performance
                        </a>
                    </div>
                </div>
                <?php endif; ?>

                <!-- 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>Activity Feed
                                        </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 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); ?>
                                    <?php if($staff_number): ?>
                                        <span class="badge bg-white text-primary ms-1 fs-11"><?php echo $staff_number; ?></span>
                                    <?php endif; ?>
                                </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>
                                    <?php if($staff_number): ?>
                                        <div class="mt-1">
                                            <span class="badge bg-soft-primary text-primary fs-11">
                                                Staff: <?php echo $staff_number; ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- Main 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 === 'Doctor'): ?>
                        <a class="dropdown-item" href="my_consultation_queue.php">
                            <i class="ph-chat-circle-dots text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Consultation Queue</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_commission_summary.php">
                            <i class="ph-money text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Earnings</span>
                            <?php if($commission_rate > 0): ?>
                                <span class="badge bg-soft-success text-success ms-1 fs-11"><?php echo $commission_rate; ?>%</span>
                            <?php endif; ?>
                        </a>
                        <?php elseif($role_name === 'Receptionist'): ?>
                        <a class="dropdown-item" href="todays_visits.php">
                            <i class="ph-calendar-check text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Today's Visits</span>
                        </a>
                        
                        <a class="dropdown-item" href="waiting_patients.php">
                            <i class="ph-clock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Waiting Patients</span>
                        </a>
                        <?php elseif($role_name === 'Lab Technician'): ?>
                        <a class="dropdown-item" href="pending_lab_orders.php">
                            <i class="ph-test-tube text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Pending Lab Orders</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_lab_performance.php">
                            <i class="ph-chart-line text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Performance</span>
                        </a>
                        <?php elseif($role_name === 'Nurse'): ?>
                        <a class="dropdown-item" href="nurse_patient_list.php">
                            <i class="ph-user-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Patients</span>
                        </a>
                        
                        <a class="dropdown-item" href="nurse_procedures.php">
                            <i class="ph-syringe text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Pending Procedures</span>
                        </a>
                        <?php endif; ?>
                        
                        <a class="dropdown-item" href="help_center.php">
                            <i class="ph-question text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Help Center</span>
                        </a>
                        
                        <a class="dropdown-item" href="notifications.php">
                            <i class="ph-bell text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Notifications</span>
                            <?php if($unread_count > 0): ?>
                                <span class="badge bg-danger ms-2 fs-11"><?php echo $unread_count; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- System Info -->
                        <?php if($branch_name): ?>
                        <div class="dropdown-item-text">
                            <small class="text-muted">
                                <i class="ph-hospital text-muted me-1"></i>
                                Branch: <?php echo htmlspecialchars($branch_name); ?>
                            </small>
                        </div>
                        <?php endif; ?>
                        
                        <?php if($license_number): ?>
                        <div class="dropdown-item-text">
                            <small class="text-muted">
                                <i class="ph-identification-card text-muted me-1"></i>
                                License: <?php echo htmlspecialchars($license_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>
                        
                        <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="system_settings.php">
                            <i class="ph-gear text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">System Settings</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 healthcare EMR
    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('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-user-circle',
            'VISIT': 'ph-calendar-check',
            'CONSULTATION': 'ph-chat-circle-dots',
            'LAB_ORDER': 'ph-test-tube',
            'PAYMENT': 'ph-credit-card',
            'STAFF': 'ph-users'
        };
        return icons[type] || 'ph-magnifying-glass';
    }
    
    function getResultBadge(type) {
        const badges = {
            'PATIENT': 'bg-soft-primary text-primary',
            'VISIT': 'bg-soft-success text-success',
            'CONSULTATION': 'bg-soft-info text-info',
            'LAB_ORDER': 'bg-soft-warning text-warning',
            'PAYMENT': 'bg-soft-danger text-danger',
            'STAFF': 'bg-soft-secondary text-secondary'
        };
        return badges[type] || 'bg-soft-light text-muted';
    }
    
    function getBadgeClass(type) {
        const classes = {
            'PATIENT': 'bg-soft-primary text-primary',
            'VISIT': 'bg-soft-success text-success',
            'CONSULTATION': 'bg-soft-info text-info',
            'LAB_ORDER': 'bg-soft-warning text-warning',
            'PAYMENT': 'bg-soft-danger text-danger',
            'STAFF': 'bg-soft-secondary text-secondary'
        };
        return classes[type] || 'bg-soft-light text-muted';
    }
    
    function getResultUrl(result) {
        const baseUrls = {
            'PATIENT': 'view_patient.php?number=',
            'VISIT': 'view_visit.php?number=',
            'CONSULTATION': 'view_consultation.php?id=',
            'LAB_ORDER': 'view_lab_order.php?number=',
            'PAYMENT': 'view_payment.php?number=',
            'STAFF': 'view_staff.php?id='
        };
        
        const identifier = result.patient_number || result.visit_number || 
                          result.consultation_id || result.order_number || 
                          result.payment_number || result.staff_number;
        return baseUrls[result.type] + encodeURIComponent(identifier);
    }
    
    function getResultTitle(result) {
        switch(result.type) {
            case 'PATIENT':
                return `${result.first_name || ''} ${result.last_name || ''}`.trim();
            case 'VISIT':
                return result.visit_number;
            case 'CONSULTATION':
                return `Consultation #${result.consultation_id}`;
            case 'LAB_ORDER':
                return result.order_number;
            case 'PAYMENT':
                return result.payment_number;
            case 'STAFF':
                return result.full_name;
            default:
                return 'Unknown';
        }
    }
    
    function getResultSubtitle(result) {
        switch(result.type) {
            case 'PATIENT':
                return `Patient • ${result.patient_number || ''}`;
            case 'VISIT':
                return `Visit • ${result.visit_type || 'Consultation'}`;
            case 'CONSULTATION':
                return `Consultation • ${result.status || 'Active'}`;
            case 'LAB_ORDER':
                return `Lab Order • ${result.status || 'Pending'}`;
            case 'PAYMENT':
                return `Payment • KES ${result.amount || '0'}`;
            case 'STAFF':
                return `Staff • ${result.staff_number || ''}`;
            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 healthcare EMR
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 register patient
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'P') {
        e.preventDefault();
        window.location.href = 'register_patient.php';
    }
    
    // Ctrl/Cmd + Shift + V for register visit
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'V') {
        e.preventDefault();
        window.location.href = 'register_visit.php';
    }
    
    // Ctrl/Cmd + Shift + C for consultations
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'C') {
        e.preventDefault();
        window.location.href = 'active_consultations.php';
    }
    
    // Ctrl/Cmd + Shift + L for lab orders
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'L') {
        e.preventDefault();
        window.location.href = 'pending_lab_orders.php';
    }
    
    // Ctrl/Cmd + Shift + B for billing
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'B') {
        e.preventDefault();
        window.location.href = 'record_payment.php';
    }
    
    // Ctrl/Cmd + Shift + R for reports
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'R') {
        e.preventDefault();
        window.location.href = 'daily_revenue.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');
    }
});

// Quick actions for common healthcare tasks
function quickRegisterPatient() {
    window.location.href = 'register_patient.php';
}

function quickRegisterVisit() {
    window.location.href = 'register_visit.php';
}

function quickActiveConsultations() {
    window.location.href = 'active_consultations.php';
}

function quickPendingLabOrders() {
    window.location.href = 'pending_lab_orders.php';
}

function quickRecordPayment() {
    window.location.href = 'record_payment.php';
}

// Initialize tooltips for enhanced UX
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Bootstrap tooltips if available
    if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
});
</script>

<style>
/* Professional Healthcare Topbar - Improved Colors and Spacing */

/* Topbar with professional healthcare colors */
#page-topbar {
    background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

/* Critical: Add spacing after topbar */
.topbar-spacer {
    height: 70px; /* Adjust based on your topbar height */
    width: 100%;
}

/* Ensure main content doesn't overlap topbar */
.main-content {
    margin-top: 0;
    padding-top: 0;
}

.page-content {
    padding-top: 1.5rem; /* Add top padding to content */
}

.navbar-header {
    padding: 0 1.5rem;
    height: 70px;
    display: flex;
    align-items: center;
}

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

.search-input {
    background: rgba(255, 255, 255, 0.15);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: white;
    padding-left: 45px;
    padding-right: 45px;
    border-radius: 25px;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    height: 40px;
}

.search-input::placeholder {
    color: rgba(255, 255, 255, 0.7);
}

.search-input:focus {
    background: rgba(255, 255, 255, 0.25);
    border-color: rgba(255, 255, 255, 0.4);
    box-shadow: 0 0 0 0.2rem rgba(255, 255, 255, 0.25);
    color: white;
}

.search-widget-icon {
    position: absolute;
    top: 50%;
    left: 15px;
    transform: translateY(-50%);
    color: rgba(255, 255, 255, 0.8);
    z-index: 10;
}

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

.search-dropdown {
    width: 450px;
    border: none;
    border-radius: 15px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
    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, #f8f9fa 0%, #e9ecef 100%);
    transform: translateX(5px);
}

/* Button styles with professional colors */
.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.15);
    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);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

/* 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-user .btn {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 25px;
    padding: 8px 16px;
    transition: all 0.3s ease;
}

.topbar-user .btn:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.3);
    transform: translateY(-1px);
}

/* Text colors for better visibility */
.user-name-text {
    color: white !important;
    font-weight: 600;
}

.user-name-sub-text {
    color: rgba(255, 255, 255, 0.8) !important;
}

/* Country flag and text */
.header-item span {
    color: rgba(255, 255, 255, 0.9);
}

/* Notification styles */
.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); }
}

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

.notification-item:hover {
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(30, 64, 175, 0.05) 100%);
    transform: translateX(3px);
}

/* Logo styles */
.logo img {
    transition: all 0.3s ease;
    filter: brightness(1.1);
}

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

/* 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;
    border-radius: 8px;
}

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

/* 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, #3b82f6 0%, #1e40af 100%);
    color: white;
    transform: translateX(3px);
}

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

/* Professional badge colors */
.bg-soft-primary { background-color: rgba(59, 130, 246, 0.1); }
.text-primary { color: #3b82f6 !important; }
.bg-soft-success { background-color: rgba(34, 197, 94, 0.1); }
.text-success { color: #22c55e !important; }
.bg-soft-info { background-color: rgba(6, 182, 212, 0.1); }
.text-info { color: #06b6d4 !important; }
.bg-soft-warning { background-color: rgba(245, 158, 11, 0.1); }
.text-warning { color: #f59e0b !important; }
.bg-soft-danger { background-color: rgba(239, 68, 68, 0.1); }
.text-danger { color: #ef4444 !important; }
.bg-soft-secondary { background-color: rgba(107, 114, 128, 0.1); }
.text-secondary { color: #6b7280 !important; }

/* 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;
}

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

/* 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;
    }
    
    .topbar-spacer {
        height: 60px; /* Reduced height for mobile */
    }
}

@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;
    }
    
    .navbar-header {
        height: 60px;
    }
    
    .topbar-spacer {
        height: 60px;
    }
}

/* 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;
}

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

.header-item:hover img {
    transform: scale(1.1);
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}

/* Role-specific styling enhancements */
.role-doctor { border-left: 3px solid #22c55e; }
.role-nurse { border-left: 3px solid #06b6d4; }
.role-receptionist { border-left: 3px solid #8b5cf6; }
.role-lab-technician { border-left: 3px solid #f59e0b; }
.role-admin { border-left: 3px solid #ef4444; }

/* Enhanced hover effects */
.dropdown-item:hover {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
    color: white;
    transform: translateX(3px);
    box-shadow: 0 4px 15px rgba(59, 130, 246, 0.2);
}

/* Notification badge pulse animation */
@keyframes healthcarePulse {
    0% { 
        transform: scale(1);
        box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
    }
    70% {
        transform: scale(1.05);
        box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
    }
    100% {
        transform: scale(1);
        box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
    }
}

.topbar-badge {
    animation: healthcarePulse 2s infinite;
}

/* Enhanced search result styling */
.search-result-item {
    transition: all 0.2s ease;
    border-left: 3px solid transparent;
}

.search-result-item:hover {
    border-left-color: #3b82f6;
    background: linear-gradient(90deg, rgba(59, 130, 246, 0.05) 0%, transparent 100%);
}

/* Medical icons styling */
.medical-icon {
    width: 20px;
    height: 20px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    font-size: 12px;
}

.medical-icon.doctor { background: rgba(34, 197, 94, 0.1); color: #22c55e; }
.medical-icon.nurse { background: rgba(6, 182, 212, 0.1); color: #06b6d4; }
.medical-icon.lab { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
.medical-icon.admin { background: rgba(107, 114, 128, 0.1); color: #6b7280; }

/* Improve text readability */
.text-white-50 {
    color: rgba(255, 255, 255, 0.8) !important;
}

/* Professional color adjustments */
.bg-primary {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%) !important;
}

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

/* Enhanced topbar items spacing */
.header-item {
    margin-left: 0.5rem;
}

.header-item:first-child {
    margin-left: 0;
}

/* Ensure proper spacing and alignment */
.d-flex.align-items-center {
    height: 100%;
}

/* Fix for dropdown positioning */
.dropdown-menu-end {
    --bs-position: end;
}

.dropdown-menu-lg {
    min-width: 20rem;
}

/* Print styles for medical records */
@media print {
    #page-topbar,
    .topbar-spacer {
        display: none !important;
    }
    
    .main-content {
        margin-top: 0 !important;
        padding-top: 0 !important;
    }
}

/* Dark mode compatibility */
@media (prefers-color-scheme: dark) {
    .search-input {
        background: rgba(0, 0, 0, 0.3);
        border-color: rgba(255, 255, 255, 0.1);
    }
    
    .dropdown-menu {
        background: #1f2937;
        color: #f9fafb;
    }
    
    .dropdown-header {
        background: #374151;
        color: #d1d5db;
    }
}

/* Accessibility improvements */
.sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
}

/* Focus management for keyboard navigation */
.dropdown-item:focus,
.search-input:focus,
.btn:focus {
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
    outline: none;
}

/* High contrast mode support */
@media (prefers-contrast: high) {
    .search-input {
        border: 2px solid white;
    }
    
    .btn-ghost-secondary {
        border: 2px solid white;
    }
    
    .dropdown-item:hover {
        background: #000;
        color: #fff;
    }
}

/* Reduced motion support */
@media (prefers-reduced-motion: reduce) {
    * {
        animation-duration: 0.01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.01ms !important;
    }
    
    .topbar-badge {
        animation: none;
    }
}

/* Enhanced visual feedback */
.btn-icon:active {
    transform: scale(0.95);
}

.dropdown-item:active {
    transform: translateX(5px);
}

/* Improved dropdown positioning */
.dropdown-menu-end[data-bs-popper] {
    right: 0;
    left: auto;
}

/* Better visual hierarchy */
.navbar-brand-box {
    display: flex;
    align-items: center;
    height: 100%;
}

/* Professional healthcare branding */
.logo-professional {
    filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
}

/* Smooth page transitions */
.page-wrapper {
    transition: margin-left 0.3s ease;
}

/* Enhanced notification system */
.notification-count {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
    border: 2px solid white;
    box-shadow: 0 2px 8px rgba(239, 68, 68, 0.3);
}

/* Professional spacing system */
.topbar-spacing {
    padding: 0.75rem 1.5rem;
}

/* Ensure consistent button heights */
.btn-topbar {
    height: 40px;
    width: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* Enhanced mobile experience */
@media (max-width: 576px) {
    .navbar-header {
        padding: 0 0.75rem;
    }
    
    .header-item {
        margin-left: 0.25rem;
    }
    
    .topbar-user .btn {
        padding: 6px 12px;
    }
}

/* Professional loading states */
.loading-state {
    opacity: 0.7;
    pointer-events: none;
    filter: grayscale(20%);
}

/* Enhanced user experience indicators */
.online-indicator {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 12px;
    height: 12px;
    background: #22c55e;
    border: 2px solid white;
    border-radius: 50%;
    animation: pulse 2s infinite;
}

/* Professional notification styling */
.notification-professional {
    border-left: 4px solid #3b82f6;
    background: linear-gradient(90deg, rgba(59, 130, 246, 0.05) 0%, transparent 100%);
}

/* Consistent icon sizing */
.topbar-icon {
    font-size: 20px;
    line-height: 1;
}

/* Professional form elements */
.form-control-topbar {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: white;
    border-radius: 20px;
}

.form-control-topbar::placeholder {
    color: rgba(255, 255, 255, 0.6);
}

.form-control-topbar:focus {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.4);
    color: white;
    box-shadow: 0 0 0 0.2rem rgba(255, 255, 255, 0.25);
}
</style>