<?php
/**
 * Menu Configuration - Healthcare EMR System
 * Define different menu structures for different user roles
 */

/**
 * Get menu configuration based on user role
 */
function getMenuConfig($userRole = 'guest') {
    
    // Common menu items for all logged-in users
    $commonMenus = [
        [
            'title' => 'Main Menu',
            'type' => 'header'
        ],
        [
            'title' => 'Dashboard',
            'icon' => 'ph-chart-line',
            'url' => 'index.php',
            'type' => 'link'
        ]
    ];
    
    // Role-specific menu configurations
    $roleMenus = [
        'Super Admin' => [
            // User Management
            [
                'title' => 'User Management',
                'type' => 'header'
            ],
            [
                'title' => 'Users & Staff',
                'icon' => 'ph-users',
                'type' => 'dropdown',
                'id' => 'userMenu',
                'items' => [
                    ['title' => 'View All Users', 'url' => 'list_users.php'],
                    ['title' => 'Add User/Staff', 'url' => 'add_user.php'],
                    ['title' => 'User Roles & Permissions', 'url' => 'user_roles.php'],
                    ['title' => 'Staff Performance', 'url' => 'staff_performance.php'],
                    ['title' => 'Access Control', 'url' => 'access_control.php']
                ]
            ],
            [
                'title' => 'Doctors',
                'icon' => 'ph-stethoscope',
                'type' => 'dropdown',
                'id' => 'doctorsMenu',
                'items' => [
                    ['title' => 'View All Doctors', 'url' => 'list_doctors.php'],
                    ['title' => 'Add Doctor', 'url' => 'add_doctor.php'],
                    ['title' => 'Doctor Schedules', 'url' => 'doctor_schedules.php'],
                    ['title' => 'Commission Settings', 'url' => 'doctor_commissions.php'],
                    ['title' => 'Performance Reports', 'url' => 'doctor_performance.php']
                ]
            ],
            [
                'title' => 'Nursing Staff',
                'icon' => 'ph-heart',
                'type' => 'dropdown',
                'id' => 'nursesMenu',
                'items' => [
                    ['title' => 'View All Nurses', 'url' => 'list_nurses.php'],
                    ['title' => 'Add Nurse', 'url' => 'add_nurse.php'],
                    ['title' => 'Nursing Schedules', 'url' => 'nurse_schedules.php'],
                    ['title' => 'Shift Management', 'url' => 'shift_management.php']
                ]
            ],
            
            // Patient Management
            [
                'title' => 'Patient Management',
                'type' => 'header'
            ],
            [
                'title' => 'Patients',
                'icon' => 'ph-user-circle',
                'type' => 'dropdown',
                'id' => 'patientMenu',
                'items' => [
                    ['title' => 'View All Patients', 'url' => 'list_patients.php'],
                    ['title' => 'Register New Patient', 'url' => 'register_patient.php'],
                    ['title' => 'Patient Search', 'url' => 'patient_search.php'],
                    ['title' => 'Patient Records', 'url' => 'patient_records.php'],
                    ['title' => 'Medical History', 'url' => 'medical_history.php'],
                    ['title' => 'Patient Demographics', 'url' => 'patient_demographics.php']
                ]
            ],
            [
                'title' => 'Patient Visits',
                'icon' => 'ph-calendar-check',
                'type' => 'dropdown',
                'id' => 'visitsMenu',
                'items' => [
                    ['title' => 'All Visits', 'url' => 'list_visits.php'],
                    ['title' => 'Register Visit', 'url' => 'register_visit.php'],
                    ['title' => 'Visit Queue', 'url' => 'visit_queue.php'],
                    ['title' => 'Visit History', 'url' => 'visit_history.php'],
                    ['title' => 'Emergency Visits', 'url' => 'emergency_visits.php']
                ]
            ],
            
            // Clinical Operations
            [
                'title' => 'Clinical Operations',
                'type' => 'header'
            ],
            [
                'title' => 'Consultations',
                'icon' => 'ph-chat-circle-dots',
                'type' => 'dropdown',
                'id' => 'consultationsMenu',
                'items' => [
                    ['title' => 'All Consultations', 'url' => 'list_consultations.php'],
                    ['title' => 'Active Consultations', 'url' => 'active_consultations.php'],
                    ['title' => 'Consultation Queue', 'url' => 'consultation_queue.php'],
                    ['title' => 'Consultation Reports', 'url' => 'consultation_reports.php'],
                    ['title' => 'Follow-up Management', 'url' => 'followup_management.php']
                ]
            ],
            [
                'title' => 'Procedures',
                'icon' => 'ph-syringe',
                'type' => 'dropdown',
                'id' => 'proceduresMenu',
                'items' => [
                    ['title' => 'All Procedures', 'url' => 'list_procedures.php'],
                    ['title' => 'Procedure Types', 'url' => 'procedure_types.php'],
                    ['title' => 'Scheduled Procedures', 'url' => 'scheduled_procedures.php'],
                    ['title' => 'Procedure History', 'url' => 'procedure_history.php'],
                    ['title' => 'Minor Surgery Log', 'url' => 'surgery_log.php']
                ]
            ],
            
            // Laboratory Management
            [
                'title' => 'Laboratory Management',
                'type' => 'header'
            ],
            [
                'title' => 'Lab Orders',
                'icon' => 'ph-test-tube',
                'type' => 'dropdown',
                'id' => 'labOrdersMenu',
                'items' => [
                    ['title' => 'All Lab Orders', 'url' => 'list_lab_orders.php'],
                    ['title' => 'Pending Orders', 'url' => 'pending_lab_orders.php'],
                    ['title' => 'In Progress', 'url' => 'inprogress_lab_orders.php'],
                    ['title' => 'Completed Orders', 'url' => 'completed_lab_orders.php'],
                    ['title' => 'Lab Queue', 'url' => 'lab_queue.php']
                ]
            ],
            [
                'title' => 'Lab Tests & Results',
                'icon' => 'ph-flask',
                'type' => 'dropdown',
                'id' => 'labTestsMenu',
                'items' => [
                    ['title' => 'Test Types', 'url' => 'lab_test_types.php'],
                    ['title' => 'Test Results', 'url' => 'lab_results.php'],
                    ['title' => 'Test Categories', 'url' => 'test_categories.php'],
                    ['title' => 'Reference Ranges', 'url' => 'reference_ranges.php'],
                    ['title' => 'Lab Reports', 'url' => 'lab_reports.php']
                ]
            ],
            
            // Financial Management
            [
                'title' => 'Financial Management',
                'type' => 'header'
            ],
            [
                'title' => 'Billing & Invoicing',
                'icon' => 'ph-receipt',
                'type' => 'dropdown',
                'id' => 'billingMenu',
                'items' => [
                    ['title' => 'All Invoices', 'url' => 'list_invoices.php'],
                    ['title' => 'Create Invoice', 'url' => 'create_invoice.php'],
                    ['title' => 'Pending Invoices', 'url' => 'pending_invoices.php'],
                    ['title' => 'Overdue Invoices', 'url' => 'overdue_invoices.php'],
                    ['title' => 'Invoice Items', 'url' => 'invoice_items.php']
                ]
            ],
            [
                'title' => 'Payments',
                'icon' => 'ph-credit-card',
                'type' => 'dropdown',
                'id' => 'paymentsMenu',
                'items' => [
                    ['title' => 'All Payments', 'url' => 'list_payments.php'],
                    ['title' => 'Record Payment', 'url' => 'record_payment.php'],
                    ['title' => 'MPesa Payments', 'url' => 'mpesa_payments.php'],
                    ['title' => 'Payment Methods', 'url' => 'payment_methods.php'],
                    ['title' => 'Payment Reports', 'url' => 'payment_reports.php'],
                    ['title' => 'Daily Collections', 'url' => 'daily_collections.php']
                ]
            ],
            [
                'title' => 'Commission Management',
                'icon' => 'ph-percent',
                'type' => 'dropdown',
                'id' => 'commissionsMenu',
                'items' => [
                    ['title' => 'Commission Calculations', 'url' => 'commission_calculations.php'],
                    ['title' => 'Doctor Commissions', 'url' => 'doctor_commissions.php'],
                    ['title' => 'Lab Commissions', 'url' => 'lab_commissions.php'],
                    ['title' => 'Commission Payments', 'url' => 'commission_payments.php'],
                    ['title' => 'Commission Reports', 'url' => 'commission_reports.php']
                ]
            ],
            
            // Revenue & Credit Scoring
            [
                'title' => 'Revenue & Credit',
                'type' => 'header'
            ],
            [
                'title' => 'Revenue Tracking',
                'icon' => 'ph-trending-up',
                'type' => 'dropdown',
                'id' => 'revenueMenu',
                'items' => [
                    ['title' => 'Daily Revenue', 'url' => 'daily_revenue.php'],
                    ['title' => 'Monthly Revenue', 'url' => 'monthly_revenue.php'],
                    ['title' => 'Revenue by Service', 'url' => 'revenue_by_service.php'],
                    ['title' => 'Revenue Analysis', 'url' => 'revenue_analysis.php'],
                    ['title' => 'Profit Margins', 'url' => 'profit_margins.php']
                ]
            ],
            [
                'title' => 'Credit Scoring',
                'icon' => 'ph-chart-line-up',
                'type' => 'dropdown',
                'id' => 'creditMenu',
                'items' => [
                    ['title' => 'Facility Credit Score', 'url' => 'facility_credit_score.php'],
                    ['title' => 'Credit History', 'url' => 'credit_history.php'],
                    ['title' => 'Score Calculation', 'url' => 'calculate_credit_score.php'],
                    ['title' => 'Credit Reports', 'url' => 'credit_reports.php']
                ]
            ],
            [
                'title' => 'Facility Loans',
                'icon' => 'ph-bank',
                'type' => 'dropdown',
                'id' => 'loansMenu',
                'items' => [
                    ['title' => 'Loan Applications', 'url' => 'facility_loan_applications.php'],
                    ['title' => 'Apply for Loan', 'url' => 'apply_facility_loan.php'],
                    ['title' => 'Active Loans', 'url' => 'active_facility_loans.php'],
                    ['title' => 'Loan Payments', 'url' => 'facility_loan_payments.php'],
                    ['title' => 'Loan Calculator', 'url' => 'loan_calculator.php']
                ]
            ],
            
            // Reports & Analytics
            [
                'title' => 'Reports & Analytics',
                'type' => 'header'
            ],
            [
                'title' => 'Clinical Reports',
                'icon' => 'ph-chart-bar',
                'type' => 'dropdown',
                'id' => 'clinicalReportsMenu',
                'items' => [
                    ['title' => 'Patient Statistics', 'url' => 'patient_statistics.php'],
                    ['title' => 'Consultation Reports', 'url' => 'consultation_reports.php'],
                    ['title' => 'Procedure Reports', 'url' => 'procedure_reports.php'],
                    ['title' => 'Lab Reports', 'url' => 'lab_statistics.php'],
                    ['title' => 'Disease Patterns', 'url' => 'disease_patterns.php']
                ]
            ],
            [
                'title' => 'Financial Reports',
                'icon' => 'ph-calculator',
                'type' => 'dropdown',
                'id' => 'financialReportsMenu',
                'items' => [
                    ['title' => 'Revenue Reports', 'url' => 'revenue_reports.php'],
                    ['title' => 'Payment Reports', 'url' => 'payment_reports.php'],
                    ['title' => 'Outstanding Balances', 'url' => 'outstanding_balances.php'],
                    ['title' => 'Commission Reports', 'url' => 'commission_reports.php'],
                    ['title' => 'Financial Summary', 'url' => 'financial_summary.php']
                ]
            ],
            [
                'title' => 'Performance Reports',
                'icon' => 'ph-trophy',
                'type' => 'dropdown',
                'id' => 'performanceReportsMenu',
                'items' => [
                    ['title' => 'Doctor Performance', 'url' => 'doctor_performance_report.php'],
                    ['title' => 'Department Performance', 'url' => 'department_performance.php'],
                    ['title' => 'Service Utilization', 'url' => 'service_utilization.php'],
                    ['title' => 'Patient Satisfaction', 'url' => 'patient_satisfaction.php'],
                    ['title' => 'Operational Metrics', 'url' => 'operational_metrics.php']
                ]
            ],
            
            // Communications
            [
                'title' => 'Communications',
                'type' => 'header'
            ],
            [
                'title' => 'Patient Communication',
                'icon' => 'ph-chat-circle',
                'type' => 'dropdown',
                'id' => 'communicationMenu',
                'items' => [
                    ['title' => 'SMS Management', 'url' => 'sms_management.php'],
                    ['title' => 'Email Management', 'url' => 'email_management.php'],
                    ['title' => 'Appointment Reminders', 'url' => 'appointment_reminders.php'],
                    ['title' => 'Result Notifications', 'url' => 'result_notifications.php'],
                    ['title' => 'Bulk Messaging', 'url' => 'bulk_messaging.php'],
                    ['title' => 'Communication Templates', 'url' => 'communication_templates.php']
                ]
            ],
            
            // System Administration
            [
                'title' => 'System Administration',
                'type' => 'header'
            ],
            [
                'title' => 'Facility Management',
                'icon' => 'ph-hospital',
                'type' => 'dropdown',
                'id' => 'facilityMenu',
                'items' => [
                    ['title' => 'Branch Management', 'url' => 'branch_management.php'],
                    ['title' => 'Facility Settings', 'url' => 'facility_settings.php'],
                    ['title' => 'Department Setup', 'url' => 'department_setup.php'],
                    ['title' => 'Equipment Management', 'url' => 'equipment_management.php']
                ]
            ],
            [
                'title' => 'System Settings',
                'icon' => 'ph-gear',
                'type' => 'dropdown',
                'id' => 'settingsMenu',
                'items' => [
                    ['title' => 'System Configuration', 'url' => 'system_settings.php'],
                    ['title' => 'MPesa Configuration', 'url' => 'mpesa_config.php'],
                    ['title' => 'Email Configuration', 'url' => 'email_config.php'],
                    ['title' => 'SMS Configuration', 'url' => 'sms_config.php'],
                    ['title' => 'Backup & Restore', 'url' => 'backup_restore.php']
                ]
            ],
            [
                'title' => 'Audit & Logs',
                'icon' => 'ph-shield-check',
                'type' => 'dropdown',
                'id' => 'auditMenu',
                'items' => [
                    ['title' => 'Activity Logs', 'url' => 'activity_logs.php'],
                    ['title' => 'User Activity', 'url' => 'user_activity.php'],
                    ['title' => 'System Logs', 'url' => 'system_logs.php'],
                    ['title' => 'Security Logs', 'url' => 'security_logs.php'],
                    ['title' => 'Data Audit', 'url' => 'data_audit.php']
                ]
            ]
        ],
        
        'Hospital Admin' => [
            // Patient Management
            [
                'title' => 'Patient Management',
                'type' => 'header'
            ],
            [
                'title' => 'Patients',
                'icon' => 'ph-user-circle',
                'type' => 'dropdown',
                'id' => 'patientMenu',
                'items' => [
                    ['title' => 'View All Patients', 'url' => 'list_patients.php'],
                    ['title' => 'Register New Patient', 'url' => 'register_patient.php'],
                    ['title' => 'Patient Search', 'url' => 'patient_search.php'],
                    ['title' => 'Patient Records', 'url' => 'patient_records.php']
                ]
            ],
            [
                'title' => 'Patient Visits',
                'icon' => 'ph-calendar-check',
                'type' => 'dropdown',
                'id' => 'visitsMenu',
                'items' => [
                    ['title' => 'All Visits', 'url' => 'list_visits.php'],
                    ['title' => 'Register Visit', 'url' => 'register_visit.php'],
                    ['title' => 'Visit Queue', 'url' => 'visit_queue.php'],
                    ['title' => 'Visit History', 'url' => 'visit_history.php']
                ]
            ],
            
            // Clinical Operations
            [
                'title' => 'Clinical Operations',
                'type' => 'header'
            ],
            [
                'title' => 'Consultations',
                'icon' => 'ph-chat-circle-dots',
                'type' => 'dropdown',
                'id' => 'consultationsMenu',
                'items' => [
                    ['title' => 'All Consultations', 'url' => 'list_consultations.php'],
                    ['title' => 'Active Consultations', 'url' => 'active_consultations.php'],
                    ['title' => 'Consultation Queue', 'url' => 'consultation_queue.php'],
                    ['title' => 'Consultation Reports', 'url' => 'consultation_reports.php']
                ]
            ],
            [
                'title' => 'Lab Management',
                'icon' => 'ph-test-tube',
                'type' => 'dropdown',
                'id' => 'labMenu',
                'items' => [
                    ['title' => 'Lab Orders', 'url' => 'list_lab_orders.php'],
                    ['title' => 'Lab Results', 'url' => 'lab_results.php'],
                    ['title' => 'Lab Queue', 'url' => 'lab_queue.php'],
                    ['title' => 'Lab Reports', 'url' => 'lab_reports.php']
                ]
            ],
            
            // Financial Management
            [
                'title' => 'Financial Management',
                'type' => 'header'
            ],
            [
                'title' => 'Billing & Payments',
                'icon' => 'ph-credit-card',
                'type' => 'dropdown',
                'id' => 'billingMenu',
                'items' => [
                    ['title' => 'All Payments', 'url' => 'list_payments.php'],
                    ['title' => 'Record Payment', 'url' => 'record_payment.php'],
                    ['title' => 'Daily Collections', 'url' => 'daily_collections.php'],
                    ['title' => 'Outstanding Balances', 'url' => 'outstanding_balances.php']
                ]
            ],
            [
                'title' => 'Revenue Reports',
                'icon' => 'ph-chart-bar',
                'type' => 'dropdown',
                'id' => 'revenueMenu',
                'items' => [
                    ['title' => 'Daily Revenue', 'url' => 'daily_revenue.php'],
                    ['title' => 'Monthly Revenue', 'url' => 'monthly_revenue.php'],
                    ['title' => 'Revenue Analysis', 'url' => 'revenue_analysis.php']
                ]
            ]
        ],
        
        'Doctor' => [
            // Clinical Work
            [
                'title' => 'Clinical Work',
                'type' => 'header'
            ],
            [
                'title' => 'My Consultations',
                'icon' => 'ph-chat-circle-dots',
                'type' => 'dropdown',
                'id' => 'myConsultationsMenu',
                'items' => [
                    ['title' => 'Active Consultations', 'url' => 'my_active_consultations.php'],
                    ['title' => 'Consultation Queue', 'url' => 'my_consultation_queue.php'],
                    ['title' => 'Completed Today', 'url' => 'my_completed_consultations.php'],
                    ['title' => 'Consultation History', 'url' => 'my_consultation_history.php']
                ]
            ],
            [
                'title' => 'My Patients',
                'icon' => 'ph-user-circle',
                'type' => 'dropdown',
                'id' => 'myPatientsMenu',
                'items' => [
                    ['title' => 'Current Patients', 'url' => 'my_current_patients.php'],
                    ['title' => 'Patient History', 'url' => 'my_patient_history.php'],
                    ['title' => 'Follow-up Patients', 'url' => 'my_followup_patients.php'],
                    ['title' => 'Search Patients', 'url' => 'doctor_patient_search.php']
                ]
            ],
            
            // Orders & Referrals
            [
                'title' => 'Orders & Referrals',
                'type' => 'header'
            ],
            [
                'title' => 'Lab Orders',
                'icon' => 'ph-test-tube',
                'type' => 'dropdown',
                'id' => 'myLabOrdersMenu',
                'items' => [
                    ['title' => 'My Lab Orders', 'url' => 'my_lab_orders.php'],
                    ['title' => 'Order Lab Tests', 'url' => 'order_lab_tests.php'],
                    ['title' => 'Pending Results', 'url' => 'my_pending_lab_results.php'],
                    ['title' => 'Lab Results Review', 'url' => 'my_lab_results.php']
                ]
            ],
            [
                'title' => 'Procedures',
                'icon' => 'ph-syringe',
                'type' => 'dropdown',
                'id' => 'myProceduresMenu',
                'items' => [
                    ['title' => 'My Procedures', 'url' => 'my_procedures.php'],
                    ['title' => 'Schedule Procedure', 'url' => 'schedule_procedure.php'],
                    ['title' => 'Procedure History', 'url' => 'my_procedure_history.php']
                ]
            ],
            
            // Performance & Earnings
            [
                'title' => 'Performance & Earnings',
                'type' => 'header'
            ],
            [
                'title' => 'My Performance',
                'icon' => 'ph-chart-line',
                'type' => 'dropdown',
                'id' => 'myPerformanceMenu',
                'items' => [
                    ['title' => 'Daily Statistics', 'url' => 'my_daily_stats.php'],
                    ['title' => 'Monthly Performance', 'url' => 'my_monthly_performance.php'],
                    ['title' => 'Patient Feedback', 'url' => 'my_patient_feedback.php']
                ]
            ],
            [
                'title' => 'My Earnings',
                'icon' => 'ph-money',
                'type' => 'dropdown',
                'id' => 'myEarningsMenu',
                'items' => [
                    ['title' => 'Commission Summary', 'url' => 'my_commission_summary.php'],
                    ['title' => 'Monthly Earnings', 'url' => 'my_monthly_earnings.php'],
                    ['title' => 'Payment History', 'url' => 'my_commission_payments.php']
                ]
            ]
        ],
        
        'Nurse' => [
            // Patient Care
            [
                'title' => 'Patient Care',
                'type' => 'header'
            ],
            [
                'title' => 'Patient Management',
                'icon' => 'ph-user-circle',
                'type' => 'dropdown',
                'id' => 'nursePatientMenu',
                'items' => [
                    ['title' => 'Patient List', 'url' => 'nurse_patient_list.php'],
                    ['title' => 'Vital Signs', 'url' => 'record_vital_signs.php'],
                    ['title' => 'Patient Triage', 'url' => 'patient_triage.php'],
                    ['title' => 'Patient Handover', 'url' => 'patient_handover.php']
                ]
            ],
            [
                'title' => 'Procedures',
                'icon' => 'ph-syringe',
                'type' => 'dropdown',
                'id' => 'nurseProceduresMenu',
                'items' => [
                    ['title' => 'My Procedures', 'url' => 'nurse_procedures.php'],
                    ['title' => 'Injections', 'url' => 'nurse_injections.php'],
                    ['title' => 'Wound Dressing', 'url' => 'wound_dressing.php'],
                    ['title' => 'Medication Administration', 'url' => 'medication_admin.php']
                ]
            ],
            
            // Documentation
            [
                'title' => 'Documentation',
                'type' => 'header'
            ],
            [
                'title' => 'Nursing Notes',
                'icon' => 'ph-notebook',
                'type' => 'dropdown',
                'id' => 'nursingNotesMenu',
                'items' => [
                    ['title' => 'Patient Notes', 'url' => 'nursing_notes.php'],
                    ['title' => 'Shift Reports', 'url' => 'shift_reports.php'],
                    ['title' => 'Care Plans', 'url' => 'care_plans.php']
                ]
            ]
        ],
        
        'Receptionist' => [
            // Front Office
            [
                'title' => 'Front Office',
                'type' => 'header'
            ],
            [
                'title' => 'Patient Registration',
                'icon' => 'ph-user-plus',
                'type' => 'dropdown',
                'id' => 'registrationMenu',
                'items' => [
                    ['title' => 'Register New Patient', 'url' => 'register_patient.php'],
                    ['title' => 'Register Visit', 'url' => 'register_visit.php'],
                    ['title' => 'Patient Search', 'url' => 'patient_search.php'],
                    ['title' => 'Update Patient Info', 'url' => 'update_patient.php']
                ]
            ],
            [
                'title' => 'Visit Management',
                'icon' => 'ph-calendar-check',
                'type' => 'dropdown',
                'id' => 'visitManagementMenu',
                'items' => [
                    ['title' => 'Today\'s Visits', 'url' => 'todays_visits.php'],
                    ['title' => 'Visit Queue', 'url' => 'visit_queue.php'],
                    ['title' => 'Waiting Patients', 'url' => 'waiting_patients.php'],
                    ['title' => 'Visit History', 'url' => 'visit_history.php']
                ]
            ],
            
            // Billing Support
            [
                'title' => 'Billing Support',
                'type' => 'header'
            ],
            [
                'title' => 'Payment Processing',
                'icon' => 'ph-credit-card',
                'type' => 'dropdown',
                'id' => 'paymentProcessingMenu',
                'items' => [
                    ['title' => 'Record Payment', 'url' => 'record_payment.php'],
                    ['title' => 'Payment Methods', 'url' => 'payment_methods.php'],
                    ['title' => 'MPesa Payments', 'url' => 'mpesa_payments.php'],
                    ['title' => 'Payment Receipts', 'url' => 'payment_receipts.php'],
                    ['title' => 'Daily Collections', 'url' => 'daily_collections.php']
                ]
            ],
            [
                'title' => 'Billing Support',
                'icon' => 'ph-receipt',
                'type' => 'dropdown',
                'id' => 'billingSupportMenu',
                'items' => [
                    ['title' => 'Generate Invoice', 'url' => 'generate_invoice.php'],
                    ['title' => 'Payment Inquiry', 'url' => 'payment_inquiry.php'],
                    ['title' => 'Outstanding Balances', 'url' => 'outstanding_balances.php'],
                    ['title' => 'Payment Plans', 'url' => 'payment_plans.php']
                ]
            ]
        ],
        
        'Lab Technician' => [
            // Laboratory Work
            [
                'title' => 'Laboratory Work',
                'type' => 'header'
            ],
            [
                'title' => 'Lab Orders',
                'icon' => 'ph-test-tube',
                'type' => 'dropdown',
                'id' => 'labOrdersMenu',
                'items' => [
                    ['title' => 'Pending Orders', 'url' => 'pending_lab_orders.php'],
                    ['title' => 'In Progress Orders', 'url' => 'inprogress_lab_orders.php'],
                    ['title' => 'Sample Collection', 'url' => 'sample_collection.php'],
                    ['title' => 'Order Queue', 'url' => 'lab_order_queue.php']
                ]
            ],
            [
                'title' => 'Test Results',
                'icon' => 'ph-flask',
                'type' => 'dropdown',
                'id' => 'testResultsMenu',
                'items' => [
                    ['title' => 'Enter Results', 'url' => 'enter_lab_results.php'],
                    ['title' => 'Pending Results', 'url' => 'pending_lab_results.php'],
                    ['title' => 'Completed Tests', 'url' => 'completed_lab_tests.php'],
                    ['title' => 'Quality Control', 'url' => 'lab_quality_control.php']
                ]
            ],
            
            // Lab Management
            [
                'title' => 'Lab Management',
                'type' => 'header'
            ],
            [
                'title' => 'Test Management',
                'icon' => 'ph-list-checks',
                'type' => 'dropdown',
                'id' => 'testManagementMenu',
                'items' => [
                    ['title' => 'Test Types', 'url' => 'lab_test_types.php'],
                    ['title' => 'Reference Ranges', 'url' => 'reference_ranges.php'],
                    ['title' => 'Test Categories', 'url' => 'test_categories.php']
                ]
            ],
            [
                'title' => 'Lab Reports',
                'icon' => 'ph-chart-bar',
                'type' => 'dropdown',
                'id' => 'labReportsMenu',
                'items' => [
                    ['title' => 'Daily Lab Report', 'url' => 'daily_lab_report.php'],
                    ['title' => 'Test Statistics', 'url' => 'lab_test_statistics.php'],
                    ['title' => 'My Performance', 'url' => 'lab_tech_performance.php']
                ]
            ]
        ],
        
        'Lab Manager' => [
            // Laboratory Management
            [
                'title' => 'Laboratory Management',
                'type' => 'header'
            ],
            [
                'title' => 'Lab Operations',
                'icon' => 'ph-test-tube',
                'type' => 'dropdown',
                'id' => 'labOperationsMenu',
                'items' => [
                    ['title' => 'All Lab Orders', 'url' => 'all_lab_orders.php'],
                    ['title' => 'Lab Performance', 'url' => 'lab_performance.php'],
                    ['title' => 'Technician Management', 'url' => 'lab_technician_management.php'],
                    ['title' => 'Equipment Management', 'url' => 'lab_equipment.php'],
                    ['title' => 'Quality Assurance', 'url' => 'lab_quality_assurance.php']
                ]
            ],
            [
                'title' => 'Lab Analytics',
                'icon' => 'ph-chart-line',
                'type' => 'dropdown',
                'id' => 'labAnalyticsMenu',
                'items' => [
                    ['title' => 'Lab Revenue', 'url' => 'lab_revenue.php'],
                    ['title' => 'Test Volume Analysis', 'url' => 'test_volume_analysis.php'],
                    ['title' => 'Turnaround Times', 'url' => 'lab_turnaround_times.php'],
                    ['title' => 'Lab Efficiency', 'url' => 'lab_efficiency.php']
                ]
            ]
        ],
        
        'Billing Clerk' => [
            // Billing Operations
            [
                'title' => 'Billing Operations',
                'type' => 'header'
            ],
            [
                'title' => 'Invoice Management',
                'icon' => 'ph-receipt',
                'type' => 'dropdown',
                'id' => 'invoiceManagementMenu',
                'items' => [
                    ['title' => 'All Invoices', 'url' => 'all_invoices.php'],
                    ['title' => 'Create Invoice', 'url' => 'create_invoice.php'],
                    ['title' => 'Pending Invoices', 'url' => 'pending_invoices.php'],
                    ['title' => 'Overdue Invoices', 'url' => 'overdue_invoices.php'],
                    ['title' => 'Invoice Reports', 'url' => 'invoice_reports.php']
                ]
            ],
            [
                'title' => 'Payment Management',
                'icon' => 'ph-credit-card',
                'type' => 'dropdown',
                'id' => 'paymentManagementMenu',
                'items' => [
                    ['title' => 'Record Payments', 'url' => 'record_payments.php'],
                    ['title' => 'Payment History', 'url' => 'payment_history.php'],
                    ['title' => 'MPesa Reconciliation', 'url' => 'mpesa_reconciliation.php'],
                    ['title' => 'Payment Reports', 'url' => 'payment_reports.php'],
                    ['title' => 'Outstanding Balances', 'url' => 'outstanding_balances_report.php']
                ]
            ],
            
            // Financial Reports
            [
                'title' => 'Financial Reports',
                'type' => 'header'
            ],
            [
                'title' => 'Revenue Reports',
                'icon' => 'ph-chart-bar',
                'type' => 'dropdown',
                'id' => 'revenueReportsMenu',
                'items' => [
                    ['title' => 'Daily Revenue', 'url' => 'daily_revenue_report.php'],
                    ['title' => 'Monthly Revenue', 'url' => 'monthly_revenue_report.php'],
                    ['title' => 'Revenue by Service', 'url' => 'revenue_by_service_report.php'],
                    ['title' => 'Commission Reports', 'url' => 'commission_reports.php']
                ]
            ]
        ]
    ];
    
    // Account menu (common for all roles)
    $accountMenu = [
        [
            'title' => 'My Account',
            'type' => 'header'
        ],
        [
            'title' => 'My Profile',
            'icon' => 'ph-user',
            'url' => 'profile.php',
            'type' => 'link'
        ],
        [
            'title' => 'Change Password',
            'icon' => 'ph-lock-key',
            'url' => 'change_password.php',
            'type' => 'link'
        ],
        [
            'title' => 'Notifications',
            'icon' => 'ph-bell',
            'url' => 'notifications.php',
            'type' => 'link'
        ],
        [
            'title' => 'Logout',
            'icon' => 'ph-sign-out',
            'url' => 'logout.php',
            'type' => 'link',
            'class' => 'text-danger'
        ]
    ];
    
    // Combine menus
    $menu = $commonMenus;
    
    if (isset($roleMenus[$userRole])) {
        $menu = array_merge($menu, $roleMenus[$userRole]);
    }
    
    $menu = array_merge($menu, $accountMenu);
    
    return $menu;
}

/**
 * Get current page name for active menu highlighting
 */
function getCurrentPage() {
    return basename($_SERVER['PHP_SELF']);
}

/**
 * Check if menu item is active
 */
function isMenuActive($url, $currentPage = null) {
    if ($currentPage === null) {
        $currentPage = getCurrentPage();
    }
    
    return $currentPage === $url;
}

/**
 * Check if dropdown has active item
 */
function hasActiveItem($items, $currentPage = null) {
    if ($currentPage === null) {
        $currentPage = getCurrentPage();
    }
    
    foreach ($items as $item) {
        if (isset($item['url']) && $currentPage === $item['url']) {
            return true;
        }
    }
    
    return false;
}

/**
 * Get quick action items for dashboard based on user role
 */
function getQuickActions($userRole) {
    $quickActions = [
        'Super Admin' => [
            ['title' => 'Register Patient', 'url' => 'register_patient.php', 'icon' => 'ph-user-plus', 'color' => 'primary'],
            ['title' => 'Register Visit', 'url' => 'register_visit.php', 'icon' => 'ph-calendar-plus', 'color' => 'success'],
            ['title' => 'Record Payment', 'url' => 'record_payment.php', 'icon' => 'ph-credit-card', 'color' => 'info'],
            ['title' => 'Lab Orders', 'url' => 'pending_lab_orders.php', 'icon' => 'ph-test-tube', 'color' => 'warning'],
            ['title' => 'Daily Revenue', 'url' => 'daily_revenue.php', 'icon' => 'ph-chart-bar', 'color' => 'danger'],
            ['title' => 'Credit Score', 'url' => 'facility_credit_score.php', 'icon' => 'ph-chart-line-up', 'color' => 'secondary']
        ],
        'Hospital Admin' => [
            ['title' => 'Register Patient', 'url' => 'register_patient.php', 'icon' => 'ph-user-plus', 'color' => 'primary'],
            ['title' => 'Register Visit', 'url' => 'register_visit.php', 'icon' => 'ph-calendar-plus', 'color' => 'success'],
            ['title' => 'Record Payment', 'url' => 'record_payment.php', 'icon' => 'ph-credit-card', 'color' => 'info'],
            ['title' => 'Daily Revenue', 'url' => 'daily_revenue.php', 'icon' => 'ph-chart-bar', 'color' => 'warning']
        ],
        'Doctor' => [
            ['title' => 'Active Consultations', 'url' => 'my_active_consultations.php', 'icon' => 'ph-chat-circle-dots', 'color' => 'primary'],
            ['title' => 'Order Lab Tests', 'url' => 'order_lab_tests.php', 'icon' => 'ph-test-tube', 'color' => 'success'],
            ['title' => 'Schedule Procedure', 'url' => 'schedule_procedure.php', 'icon' => 'ph-syringe', 'color' => 'info'],
            ['title' => 'My Performance', 'url' => 'my_daily_stats.php', 'icon' => 'ph-chart-line', 'color' => 'warning'],
            ['title' => 'My Earnings', 'url' => 'my_commission_summary.php', 'icon' => 'ph-money', 'color' => 'success']
        ],
        'Nurse' => [
            ['title' => 'Patient List', 'url' => 'nurse_patient_list.php', 'icon' => 'ph-user-circle', 'color' => 'primary'],
            ['title' => 'Record Vitals', 'url' => 'record_vital_signs.php', 'icon' => 'ph-heart', 'color' => 'success'],
            ['title' => 'Procedures', 'url' => 'nurse_procedures.php', 'icon' => 'ph-syringe', 'color' => 'info'],
            ['title' => 'Nursing Notes', 'url' => 'nursing_notes.php', 'icon' => 'ph-notebook', 'color' => 'warning']
        ],
        'Receptionist' => [
            ['title' => 'Register Patient', 'url' => 'register_patient.php', 'icon' => 'ph-user-plus', 'color' => 'primary'],
            ['title' => 'Register Visit', 'url' => 'register_visit.php', 'icon' => 'ph-calendar-plus', 'color' => 'success'],
            ['title' => 'Record Payment', 'url' => 'record_payment.php', 'icon' => 'ph-credit-card', 'color' => 'info'],
            ['title' => 'Patient Search', 'url' => 'patient_search.php', 'icon' => 'ph-magnifying-glass', 'color' => 'warning']
        ],
        'Lab Technician' => [
            ['title' => 'Pending Orders', 'url' => 'pending_lab_orders.php', 'icon' => 'ph-test-tube', 'color' => 'primary'],
            ['title' => 'Enter Results', 'url' => 'enter_lab_results.php', 'icon' => 'ph-flask', 'color' => 'success'],
            ['title' => 'Sample Collection', 'url' => 'sample_collection.php', 'icon' => 'ph-syringe', 'color' => 'info'],
            ['title' => 'Lab Queue', 'url' => 'lab_order_queue.php', 'icon' => 'ph-queue', 'color' => 'warning']
        ],
        'Lab Manager' => [
            ['title' => 'Lab Operations', 'url' => 'all_lab_orders.php', 'icon' => 'ph-test-tube', 'color' => 'primary'],
            ['title' => 'Lab Performance', 'url' => 'lab_performance.php', 'icon' => 'ph-chart-line', 'color' => 'success'],
            ['title' => 'Quality Assurance', 'url' => 'lab_quality_assurance.php', 'icon' => 'ph-shield-check', 'color' => 'info'],
            ['title' => 'Lab Revenue', 'url' => 'lab_revenue.php', 'icon' => 'ph-money', 'color' => 'warning']
        ],
        'Billing Clerk' => [
            ['title' => 'Create Invoice', 'url' => 'create_invoice.php', 'icon' => 'ph-receipt', 'color' => 'primary'],
            ['title' => 'Record Payment', 'url' => 'record_payments.php', 'icon' => 'ph-credit-card', 'color' => 'success'],
            ['title' => 'MPesa Reconciliation', 'url' => 'mpesa_reconciliation.php', 'icon' => 'ph-device-mobile', 'color' => 'info'],
            ['title' => 'Daily Revenue', 'url' => 'daily_revenue_report.php', 'icon' => 'ph-chart-bar', 'color' => 'warning']
        ]
    ];
    
    return $quickActions[$userRole] ?? [];
}

/**
 * Get notification counts for user role
 */
function getNotificationCounts($userRole, $userId = null) {
    // This would typically connect to database to get real counts
    // For now, returning sample structure
    $notifications = [
        'Super Admin' => [
            'pending_visits' => 0,
            'pending_lab_orders' => 0,
            'overdue_payments' => 0,
            'system_alerts' => 0,
            'total' => 0
        ],
        'Hospital Admin' => [
            'pending_visits' => 0,
            'pending_lab_orders' => 0,
            'overdue_payments' => 0,
            'total' => 0
        ],
        'Doctor' => [
            'consultation_queue' => 0,
            'pending_lab_results' => 0,
            'follow_up_patients' => 0,
            'total' => 0
        ],
        'Nurse' => [
            'pending_procedures' => 0,
            'patient_alerts' => 0,
            'total' => 0
        ],
        'Receptionist' => [
            'waiting_patients' => 0,
            'payment_pending' => 0,
            'total' => 0
        ],
        'Lab Technician' => [
            'pending_tests' => 0,
            'urgent_tests' => 0,
            'total' => 0
        ],
        'Lab Manager' => [
            'pending_approvals' => 0,
            'quality_alerts' => 0,
            'total' => 0
        ],
        'Billing Clerk' => [
            'pending_invoices' => 0,
            'payment_verification' => 0,
            'total' => 0
        ]
    ];
    
    return $notifications[$userRole] ?? ['total' => 0];
}

/**
 * Get role-based dashboard widgets
 */
function getDashboardWidgets($userRole) {
    $widgets = [
        'Super Admin' => [
            'total_patients',
            'todays_visits',
            'active_consultations',
            'pending_lab_orders',
            'daily_revenue',
            'monthly_revenue',
            'facility_credit_score',
            'outstanding_balances',
            'doctor_performance',
            'lab_performance',
            'recent_activities',
            'system_alerts'
        ],
        'Hospital Admin' => [
            'total_patients',
            'todays_visits',
            'active_consultations',
            'daily_revenue',
            'monthly_revenue',
            'outstanding_balances',
            'recent_activities'
        ],
        'Doctor' => [
            'my_consultation_queue',
            'my_patients_today',
            'my_pending_lab_results',
            'my_monthly_earnings',
            'my_performance_stats',
            'recent_consultations'
        ],
        'Nurse' => [
            'my_patients',
            'pending_procedures',
            'vital_signs_pending',
            'shift_summary'
        ],
        'Receptionist' => [
            'todays_registrations',
            'waiting_patients',
            'payment_collection',
            'recent_visits'
        ],
        'Lab Technician' => [
            'pending_lab_orders',
            'urgent_tests',
            'completed_today',
            'my_performance'
        ],
        'Lab Manager' => [
            'lab_orders_summary',
            'technician_performance',
            'lab_revenue',
            'quality_metrics'
        ],
        'Billing Clerk' => [
            'daily_collections',
            'pending_invoices',
            'payment_methods_summary',
            'outstanding_balances'
        ]
    ];
    
    return $widgets[$userRole] ?? [];
}

/**
 * Check if user has permission for specific menu item
 */
function hasMenuPermission($userRole, $menuItem, $userId = null) {
    // Define role-based permissions
    $permissions = [
        'Super Admin' => ['*'], // Full access
        'Hospital Admin' => [
            // Patient management
            'list_patients.php', 'register_patient.php', 'patient_search.php', 'patient_records.php',
            'list_visits.php', 'register_visit.php', 'visit_queue.php', 'visit_history.php',
            // Clinical operations
            'list_consultations.php', 'active_consultations.php', 'consultation_queue.php', 'consultation_reports.php',
            'list_lab_orders.php', 'lab_results.php', 'lab_queue.php', 'lab_reports.php',
            // Financial management
            'list_payments.php', 'record_payment.php', 'daily_collections.php', 'outstanding_balances.php',
            'daily_revenue.php', 'monthly_revenue.php', 'revenue_analysis.php'
        ],
        'Doctor' => [
            // Consultation and patient management
            'my_active_consultations.php', 'my_consultation_queue.php', 'my_completed_consultations.php', 'my_consultation_history.php',
            'my_current_patients.php', 'my_patient_history.php', 'my_followup_patients.php', 'doctor_patient_search.php',
            // Lab orders and procedures
            'my_lab_orders.php', 'order_lab_tests.php', 'my_pending_lab_results.php', 'my_lab_results.php',
            'my_procedures.php', 'schedule_procedure.php', 'my_procedure_history.php',
            // Performance and earnings
            'my_daily_stats.php', 'my_monthly_performance.php', 'my_patient_feedback.php',
            'my_commission_summary.php', 'my_monthly_earnings.php', 'my_commission_payments.php'
        ],
        'Nurse' => [
            // Patient care
            'nurse_patient_list.php', 'record_vital_signs.php', 'patient_triage.php', 'patient_handover.php',
            'nurse_procedures.php', 'nurse_injections.php', 'wound_dressing.php', 'medication_admin.php',
            // Documentation
            'nursing_notes.php', 'shift_reports.php', 'care_plans.php'
        ],
        'Receptionist' => [
            // Front office
            'register_patient.php', 'register_visit.php', 'patient_search.php', 'update_patient.php',
            'todays_visits.php', 'visit_queue.php', 'waiting_patients.php', 'visit_history.php',
            // Billing support
            'record_payment.php', 'payment_methods.php', 'mpesa_payments.php', 'payment_receipts.php', 'daily_collections.php',
            'generate_invoice.php', 'payment_inquiry.php', 'outstanding_balances.php', 'payment_plans.php'
        ],
        'Lab Technician' => [
            // Laboratory work
            'pending_lab_orders.php', 'inprogress_lab_orders.php', 'sample_collection.php', 'lab_order_queue.php',
            'enter_lab_results.php', 'pending_lab_results.php', 'completed_lab_tests.php', 'lab_quality_control.php',
            // Lab management
            'lab_test_types.php', 'reference_ranges.php', 'test_categories.php',
            'daily_lab_report.php', 'lab_test_statistics.php', 'lab_tech_performance.php'
        ],
        'Lab Manager' => [
            // Laboratory management
            'all_lab_orders.php', 'lab_performance.php', 'lab_technician_management.php', 'lab_equipment.php', 'lab_quality_assurance.php',
            'lab_revenue.php', 'test_volume_analysis.php', 'lab_turnaround_times.php', 'lab_efficiency.php'
        ],
        'Billing Clerk' => [
            // Billing operations
            'all_invoices.php', 'create_invoice.php', 'pending_invoices.php', 'overdue_invoices.php', 'invoice_reports.php',
            'record_payments.php', 'payment_history.php', 'mpesa_reconciliation.php', 'payment_reports.php', 'outstanding_balances_report.php',
            // Financial reports
            'daily_revenue_report.php', 'monthly_revenue_report.php', 'revenue_by_service_report.php', 'commission_reports.php'
        ]
    ];
    
    // Super Admin has access to everything
    if ($userRole === 'Super Admin') {
        return true;
    }
    
    // Check if user role has permission for this menu item
    $rolePermissions = $permissions[$userRole] ?? [];
    
    return in_array($menuItem, $rolePermissions);
}

/**
 * Get breadcrumb based on current page
 */
function getBreadcrumb($currentPage) {
    $breadcrumbs = [
        // Patient Management
        'list_patients.php' => ['Dashboard', 'Patients'],
        'register_patient.php' => ['Dashboard', 'Patients', 'Register Patient'],
        'patient_search.php' => ['Dashboard', 'Patients', 'Search Patient'],
        
        // Patient Visits
        'list_visits.php' => ['Dashboard', 'Patient Visits'],
        'register_visit.php' => ['Dashboard', 'Visits', 'Register Visit'],
        'visit_queue.php' => ['Dashboard', 'Visits', 'Visit Queue'],
        
        // Consultations
        'list_consultations.php' => ['Dashboard', 'Consultations'],
        'my_active_consultations.php' => ['Dashboard', 'My Consultations', 'Active'],
        'consultation_queue.php' => ['Dashboard', 'Consultations', 'Queue'],
        
        // Laboratory
        'list_lab_orders.php' => ['Dashboard', 'Lab Orders'],
        'pending_lab_orders.php' => ['Dashboard', 'Lab', 'Pending Orders'],
        'enter_lab_results.php' => ['Dashboard', 'Lab', 'Enter Results'],
        
        // Billing & Payments
        'record_payment.php' => ['Dashboard', 'Payments', 'Record Payment'],
        'list_payments.php' => ['Dashboard', 'Payments'],
        'create_invoice.php' => ['Dashboard', 'Billing', 'Create Invoice'],
        
        // Reports
        'daily_revenue.php' => ['Dashboard', 'Reports', 'Daily Revenue'],
        'facility_credit_score.php' => ['Dashboard', 'Credit', 'Facility Score'],
        
        // Default
        'index.php' => ['Dashboard']
    ];
    
    return $breadcrumbs[$currentPage] ?? ['Dashboard'];
}

/**
 * Get menu items that require notifications/badges
 */
function getMenuNotifications($userRole, $userId = null) {
    // This would connect to database to get actual counts
    $notifications = [
        'Super Admin' => [
            'visit_queue.php' => 5,                  // 5 patients waiting
            'pending_lab_orders.php' => 12,         // 12 pending lab orders
            'outstanding_balances.php' => 8,        // 8 overdue payments
        ],
        'Hospital Admin' => [
            'visit_queue.php' => 5,                  // 5 patients waiting
            'pending_lab_orders.php' => 12,         // 12 pending lab orders
            'outstanding_balances.php' => 8,        // 8 overdue payments
        ],
        'Doctor' => [
            'my_consultation_queue.php' => 3,       // 3 patients in queue
            'my_pending_lab_results.php' => 6,      // 6 pending results
            'my_followup_patients.php' => 4,        // 4 follow-up patients
        ],
        'Nurse' => [
            'nurse_patient_list.php' => 8,          // 8 patients assigned
            'nurse_procedures.php' => 5,            // 5 pending procedures
        ],
        'Receptionist' => [
            'waiting_patients.php' => 7,            // 7 patients waiting
            'todays_visits.php' => 15,              // 15 visits today
        ],
        'Lab Technician' => [
            'pending_lab_orders.php' => 10,         // 10 pending orders
            'inprogress_lab_orders.php' => 5,       // 5 in progress
        ],
        'Lab Manager' => [
            'all_lab_orders.php' => 15,             // 15 total orders
            'lab_quality_assurance.php' => 2,       // 2 quality issues
        ],
        'Billing Clerk' => [
            'pending_invoices.php' => 8,            // 8 pending invoices
            'mpesa_reconciliation.php' => 4,        // 4 unreconciled payments
        ]
    ];
    
    return $notifications[$userRole] ?? [];
}

/**
 * Generate menu HTML with role-based permissions
 */
function renderMenu($userRole, $userId = null) {
    $menuConfig = getMenuConfig($userRole);
    $currentPage = getCurrentPage();
    $notifications = getMenuNotifications($userRole, $userId);
    
    $html = '';
    
    foreach ($menuConfig as $item) {
        if ($item['type'] === 'header') {
            $html .= '<li class="menu-title"><span data-key="t-menu">' . htmlspecialchars($item['title']) . '</span></li>';
        } elseif ($item['type'] === 'link') {
            // Check permission
            if (!hasMenuPermission($userRole, $item['url'], $userId)) {
                continue;
            }
            
            $isActive = isMenuActive($item['url'], $currentPage);
            $badgeHtml = '';
            
            // Add notification badge if exists
            if (isset($notifications[$item['url']]) && $notifications[$item['url']] > 0) {
                $badgeHtml = '<span class="badge rounded-pill bg-success float-end">' . $notifications[$item['url']] . '</span>';
            }
            
            $html .= '<li class="nav-item">';
            $html .= '<a class="nav-link menu-link' . ($isActive ? ' active' : '') . '" href="' . htmlspecialchars($item['url']) . '">';
            $html .= '<i class="' . htmlspecialchars($item['icon']) . '"></i> ';
            $html .= '<span data-key="t-' . strtolower(str_replace(' ', '-', $item['title'])) . '">' . htmlspecialchars($item['title']) . '</span>';
            $html .= $badgeHtml;
            $html .= '</a></li>';
            
        } elseif ($item['type'] === 'dropdown') {
            // Filter dropdown items based on permissions
            $allowedItems = array_filter($item['items'], function($subItem) use ($userRole, $userId) {
                return hasMenuPermission($userRole, $subItem['url'], $userId);
            });
            
            // Skip dropdown if no allowed items
            if (empty($allowedItems)) {
                continue;
            }
            
            $hasActiveSubItem = hasActiveItem($allowedItems, $currentPage);
            $dropdownBadge = '';
            
            // Calculate total notifications for dropdown
            $totalNotifications = 0;
            foreach ($allowedItems as $subItem) {
                if (isset($notifications[$subItem['url']])) {
                    $totalNotifications += $notifications[$subItem['url']];
                }
            }
            
            if ($totalNotifications > 0) {
                $dropdownBadge = '<span class="badge rounded-pill bg-success float-end">' . $totalNotifications . '</span>';
            }
            
            $html .= '<li class="nav-item">';
            $html .= '<a class="nav-link menu-link' . ($hasActiveSubItem ? ' active' : '') . '" href="#' . $item['id'] . '" data-bs-toggle="collapse" role="button">';
            $html .= '<i class="' . htmlspecialchars($item['icon']) . '"></i> ';
            $html .= '<span data-key="t-' . strtolower(str_replace(' ', '-', $item['title'])) . '">' . htmlspecialchars($item['title']) . '</span>';
            $html .= $dropdownBadge;
            $html .= '</a>';
            
            $html .= '<div class="collapse menu-dropdown' . ($hasActiveSubItem ? ' show' : '') . '" id="' . $item['id'] . '">';
            $html .= '<ul class="nav nav-sm flex-column">';
            
            foreach ($allowedItems as $subItem) {
                $isSubActive = isMenuActive($subItem['url'], $currentPage);
                $subBadgeHtml = '';
                
                if (isset($notifications[$subItem['url']]) && $notifications[$subItem['url']] > 0) {
                    $subBadgeHtml = '<span class="badge rounded-pill bg-success float-end">' . $notifications[$subItem['url']] . '</span>';
                }
                
                $html .= '<li class="nav-item">';
                $html .= '<a href="' . htmlspecialchars($subItem['url']) . '" class="nav-link' . ($isSubActive ? ' active' : '') . '">';
                $html .= htmlspecialchars($subItem['title']);
                $html .= $subBadgeHtml;
                $html .= '</a></li>';
            }
            
            $html .= '</ul></div></li>';
        }
    }
    
    return $html;
}

/**
 * Get healthcare-specific dashboard statistics
 */
function getDashboardStats($userRole, $userId = null) {
    // This would connect to database to get real statistics
    // Sample structure for different roles
    $stats = [
        'Super Admin' => [
            'patients_today' => ['value' => 25, 'label' => 'Patients Today', 'icon' => 'ph-user-circle', 'color' => 'primary'],
            'consultations_today' => ['value' => 18, 'label' => 'Consultations Today', 'icon' => 'ph-chat-circle-dots', 'color' => 'success'],
            'lab_orders_pending' => ['value' => 12, 'label' => 'Pending Lab Orders', 'icon' => 'ph-test-tube', 'color' => 'warning'],
            'revenue_today' => ['value' => 'KES 45,000', 'label' => 'Today\'s Revenue', 'icon' => 'ph-money', 'color' => 'info'],
            'outstanding_balance' => ['value' => 'KES 120,000', 'label' => 'Outstanding Balance', 'icon' => 'ph-credit-card', 'color' => 'danger'],
            'credit_score' => ['value' => 750, 'label' => 'Facility Credit Score', 'icon' => 'ph-chart-line-up', 'color' => 'secondary']
        ],
        'Doctor' => [
            'my_patients_today' => ['value' => 8, 'label' => 'My Patients Today', 'icon' => 'ph-user-circle', 'color' => 'primary'],
            'consultations_completed' => ['value' => 5, 'label' => 'Consultations Completed', 'icon' => 'ph-check-circle', 'color' => 'success'],
            'pending_lab_results' => ['value' => 3, 'label' => 'Pending Lab Results', 'icon' => 'ph-test-tube', 'color' => 'warning'],
            'monthly_earnings' => ['value' => 'KES 85,000', 'label' => 'Monthly Earnings', 'icon' => 'ph-money', 'color' => 'info']
        ],
        'Receptionist' => [
            'registrations_today' => ['value' => 12, 'label' => 'Registrations Today', 'icon' => 'ph-user-plus', 'color' => 'primary'],
            'visits_today' => ['value' => 25, 'label' => 'Visits Today', 'icon' => 'ph-calendar-check', 'color' => 'success'],
            'payments_collected' => ['value' => 'KES 35,000', 'label' => 'Payments Collected', 'icon' => 'ph-credit-card', 'color' => 'info'],
            'waiting_patients' => ['value' => 7, 'label' => 'Patients Waiting', 'icon' => 'ph-clock', 'color' => 'warning']
        ],
        'Lab Technician' => [
            'tests_pending' => ['value' => 15, 'label' => 'Tests Pending', 'icon' => 'ph-test-tube', 'color' => 'warning'],
            'tests_completed' => ['value' => 8, 'label' => 'Tests Completed Today', 'icon' => 'ph-check-circle', 'color' => 'success'],
            'urgent_tests' => ['value' => 3, 'label' => 'Urgent Tests', 'icon' => 'ph-lightning', 'color' => 'danger'],
            'samples_collected' => ['value' => 12, 'label' => 'Samples Collected', 'icon' => 'ph-flask', 'color' => 'info']
        ]
    ];
    
    return $stats[$userRole] ?? [];
}

/**
 * Get healthcare workflow statuses
 */
function getWorkflowStatuses() {
    return [
        'patient_registration' => ['Active', 'Inactive'],
        'visit_status' => ['Registered', 'In Consultation', 'Completed', 'Cancelled'],
        'consultation_status' => ['In Progress', 'Completed', 'Cancelled'],
        'lab_order_status' => ['Pending', 'Sample Collected', 'In Progress', 'Completed', 'Cancelled'],
        'procedure_status' => ['Scheduled', 'In Progress', 'Completed', 'Cancelled'],
        'payment_status' => ['Pending', 'Completed', 'Failed', 'Reversed'],
        'invoice_status' => ['Draft', 'Sent', 'Paid', 'Partially Paid', 'Overdue', 'Cancelled']
    ];
}

/**
 * Get payment methods available in the system
 */
function getPaymentMethods() {
    return [
        'CASH' => 'Cash',
        'CARD' => 'Card',
        'MOBILE_MONEY' => 'Mobile Money (M-Pesa)',
        'BANK_TRANSFER' => 'Bank Transfer',
        'CHEQUE' => 'Cheque',
        'INSURANCE' => 'Insurance'
    ];
}

/**
 * Get medical specializations
 */
function getMedicalSpecializations() {
    return [
        'General Medicine',
        'Internal Medicine',
        'Pediatrics',
        'Obstetrics & Gynecology',
        'Surgery',
        'Orthopedics',
        'Cardiology',
        'Dermatology',
        'ENT (Ear, Nose, Throat)',
        'Ophthalmology',
        'Psychiatry',
        'Radiology',
        'Anesthesiology',
        'Emergency Medicine',
        'Family Medicine'
    ];
}

/**
 * Get lab test categories
 */
function getLabTestCategories() {
    return [
        'HEMATOLOGY' => 'Hematology',
        'BIOCHEMISTRY' => 'Biochemistry',
        'MICROBIOLOGY' => 'Microbiology',
        'PARASITOLOGY' => 'Parasitology',
        'SEROLOGY' => 'Serology',
        'HISTOPATHOLOGY' => 'Histopathology',
        'RADIOLOGY' => 'Radiology'
    ];
}

/**
 * Get procedure categories
 */
function getProcedureCategories() {
    return [
        'INJECTION' => 'Injection',
        'DRESSING' => 'Dressing',
        'SURGICAL' => 'Surgical',
        'DIAGNOSTIC' => 'Diagnostic',
        'THERAPEUTIC' => 'Therapeutic'
    ];
}

/**
 * Get commission calculation settings
 */
function getCommissionSettings() {
    return [
        'doctor_default_rate' => 20.00,      // 20% default commission for doctors
        'lab_default_rate' => 15.00,         // 15% default commission for lab
        'mpesa_paybill_lab' => '400300',     // M-Pesa paybill for lab payments
        'mpesa_paybill_doctor' => '400301',  // M-Pesa paybill for doctor payments
    ];
}

/**
 * Get credit scoring parameters
 */
function getCreditScoringParameters() {
    return [
        'min_revenue_excellent' => 500000,   // Monthly revenue for excellent score (800+)
        'min_revenue_good' => 300000,        // Monthly revenue for good score (700+)
        'min_revenue_fair' => 100000,        // Monthly revenue for fair score (600+)
        'min_revenue_poor' => 50000,         // Monthly revenue for poor score (500+)
        'growth_rate_bonus' => 10,           // Growth rate above 10% gets bonus points
        'growth_rate_penalty' => -10,       // Growth rate below -10% gets penalty
        'min_credit_score_loan' => 600,     // Minimum credit score for loan eligibility
        'max_loan_multiplier_low' => 1.5,   // Max loan = 1.5x monthly revenue for high risk
        'max_loan_multiplier_medium' => 3.0, // Max loan = 3x monthly revenue for medium risk
        'max_loan_multiplier_low_risk' => 5.0 // Max loan = 5x monthly revenue for low risk
    ];
}

/**
 * Get system configuration defaults
 */
function getSystemDefaults() {
    return [
        'default_currency' => 'KES',
        'consultation_fee_default' => 2000.00,
        'appointment_slot_duration' => 30, // minutes
        'lab_result_retention_days' => 365,
        'session_timeout_minutes' => 120,
        'sms_sender_name' => 'HEALTHCARE',
        'company_name' => 'HealthCare Management System',
        'company_email' => 'info@healthcare.co.ke',
        'company_phone' => '+254-700-000-000'
    ];
}
?>