<?php
/**
 * Caregiver Management System - Complete Menu Configuration
 * Professional caregiving and health services navigation system
 * 
 * @author Caregiver Management Team
 * @version 2.0
 * @since 2025
 */

/**
 * Get user's assigned pages from database
 */
function getUserAssignedPages($conn, $userId) {
    if (!$conn || !$userId) {
        return ['role' => 'guest', 'pages' => []];
    }
    
    $sql = "SELECT u.role_id, ur.role_name, rp.resource_type 
            FROM users u 
            INNER JOIN user_roles ur ON u.role_id = ur.role_id 
            LEFT JOIN role_permissions rp ON u.role_id = rp.role_id 
            WHERE u.user_id = ? AND u.status = 'active' AND rp.is_active = 1";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $assignedPages = [];
    $userRole = 'guest';
    
    while ($row = $result->fetch_assoc()) {
        if ($userRole === 'guest') {
            $userRole = $row['role_name'];
        }
        if ($row['resource_type']) {
            $assignedPages[] = $row['resource_type'];
        }
    }
    
    return [
        'role' => $userRole,
        'pages' => $assignedPages
    ];
}

/**
 * Complete caregiver system menu configuration
 */
function getMenuConfig($userRole = 'guest', $assignedPages = [], $conn = null, $userId = null) {
    
    // Get fresh data if available
    if ($conn && $userId) {
        $userData = getUserAssignedPages($conn, $userId);
        $userRole = $userData['role'];
        $assignedPages = $userData['pages'];
    }
    
    // Super Admin gets everything
    if ($userRole === 'Super Admin' || $userRole === 'Admin') {
        $assignedPages = ['*'];
    }
    
    // Common menu items for all users
    $commonMenus = [
        [
            'title' => 'Main',
            'type' => 'header'
        ],
        [
            'title' => 'Dashboard',
            'icon' => 'bx-home-circle',
            'url' => 'index.php',
            'type' => 'link'
        ]
    ];
    
    // Complete role-specific menus for caregiving business
    $roleMenus = [
        'Admin' => [
            [
                'title' => 'User Management',
                'type' => 'header'
            ],
            [
                'title' => 'Users & Roles',
                'icon' => 'bx-group',
                'type' => 'dropdown',
                'id' => 'usersMenu',
                'items' => [
                    ['title' => 'All Users', 'url' => 'users.php'],
                    ['title' => 'Create User', 'url' => 'create_user.php'],
                    ['title' => 'User Roles', 'url' => 'manage_roles.php'],
                    ['title' => 'Permissions', 'url' => 'permissions.php'],
                    ['title' => 'User Activity', 'url' => 'user_activity.php']
                ]
            ],
            [
                'title' => 'Caregiver Management',
                'type' => 'header'
            ],
            [
                'title' => 'Caregivers',
                'icon' => 'bx-user-circle',
                'type' => 'dropdown',
                'id' => 'caregiversMenu',
                'items' => [
                    ['title' => 'All Caregivers', 'url' => 'caregivers_list.php'],
                    ['title' => 'Add Caregiver', 'url' => 'add_caregiver.php'],
                    ['title' => 'Caregiver Search', 'url' => 'caregiver_search.php'],
                    ['title' => 'Availability Calendar', 'url' => 'caregiver_availability.php'],
                    ['title' => 'Performance Reports', 'url' => 'caregiver_performance.php']
                ]
            ],
            [
                'title' => 'Certifications',
                'icon' => 'bx-certification',
                'type' => 'dropdown',
                'id' => 'certificationsMenu',
                'items' => [
                    ['title' => 'All Certifications', 'url' => 'certifications.php'],
                    ['title' => 'Manage Certifications', 'url' => 'manage_certifications.php'],
                    ['title' => 'Expiring Certifications', 'url' => 'expiring_certifications.php'],
                    ['title' => 'Certification Types', 'url' => 'certification_types.php']
                ]
            ],
            [
                'title' => 'Skills Management',
                'icon' => 'bx-star',
                'type' => 'dropdown',
                'id' => 'skillsMenu',
                'items' => [
                    ['title' => 'All Skills', 'url' => 'skills.php'],
                    ['title' => 'Skill Categories', 'url' => 'skill_categories.php'],
                    ['title' => 'Skill Verification', 'url' => 'skill_verification.php']
                ]
            ],
            [
                'title' => 'Client Management',
                'type' => 'header'
            ],
            [
                'title' => 'Clients',
                'icon' => 'bx-user-plus',
                'type' => 'dropdown',
                'id' => 'clientsMenu',
                'items' => [
                    ['title' => 'All Clients', 'url' => 'clients.php'],
                    ['title' => 'Add Client', 'url' => 'add_client.php'],
                    ['title' => 'Client Search', 'url' => 'client_search.php'],
                    ['title' => 'Client Analytics', 'url' => 'client_analytics.php'],
                    ['title' => 'Risk Assessment', 'url' => 'risk_assessment.php']
                ]
            ],
            [
                'title' => 'Care Plans',
                'icon' => 'bx-clinic',
                'type' => 'dropdown',
                'id' => 'carePlansMenu',
                'items' => [
                    ['title' => 'All Care Plans', 'url' => 'care_plans.php'],
                    ['title' => 'Create Care Plan', 'url' => 'create_care_plan.php'],
                    ['title' => 'Care Plan Tasks', 'url' => 'care_plan_tasks.php'],
                    ['title' => 'Medical Requirements', 'url' => 'medical_requirements.php'],
                    ['title' => 'Care Plan Templates', 'url' => 'care_plan_templates.php']
                ]
            ],
            [
                'title' => 'Contracts',
                'icon' => 'bx-file',
                'type' => 'dropdown',
                'id' => 'contractsMenu',
                'items' => [
                    ['title' => 'All Contracts', 'url' => 'contracts.php'],
                    ['title' => 'Create Contract', 'url' => 'create_contract.php'],
                    ['title' => 'Expiring Contracts', 'url' => 'expiring_contracts.php'],
                    ['title' => 'Contract Renewals', 'url' => 'contract_renewals.php'],
                    ['title' => 'Contract Templates', 'url' => 'contract_templates.php']
                ]
            ],
            [
                'title' => 'Scheduling',
                'type' => 'header'
            ],
            [
                'title' => 'Schedule Management',
                'icon' => 'bx-calendar',
                'type' => 'dropdown',
                'id' => 'schedulingMenu',
                'items' => [
                    ['title' => 'Calendar View', 'url' => 'schedule_calendar.php'],
                    ['title' => 'Create Schedule', 'url' => 'create_schedule.php'],
                    ['title' => 'All Schedules', 'url' => 'schedules.php'],
                    ['title' => 'Conflict Resolution', 'url' => 'schedule_conflicts.php'],
                    ['title' => 'Bulk Scheduling', 'url' => 'bulk_scheduling.php'],
                    ['title' => 'Schedule Templates', 'url' => 'schedule_templates.php']
                ]
            ],
            [
                'title' => 'Attendance',
                'icon' => 'bx-time',
                'type' => 'dropdown',
                'id' => 'attendanceMenu',
                'items' => [
                    ['title' => 'Attendance Records', 'url' => 'attendance_records.php'],
                    ['title' => 'No Shows', 'url' => 'no_shows.php'],
                    ['title' => 'Late Arrivals', 'url' => 'late_arrivals.php'],
                    ['title' => 'Overtime Report', 'url' => 'overtime_report.php']
                ]
            ],
            [
                'title' => 'Financial Management',
                'type' => 'header'
            ],
            [
                'title' => 'Invoicing',
                'icon' => 'bx-receipt',
                'type' => 'dropdown',
                'id' => 'invoicingMenu',
                'items' => [
                    ['title' => 'All Invoices', 'url' => 'invoices.php'],
                    ['title' => 'Generate Invoice', 'url' => 'generate_invoice.php'],
                    ['title' => 'Draft Invoices', 'url' => 'draft_invoices.php'],
                    ['title' => 'Outstanding Invoices', 'url' => 'outstanding_invoices.php'],
                    ['title' => 'Overdue Invoices', 'url' => 'overdue_invoices.php'],
                    ['title' => 'Invoice Templates', 'url' => 'invoice_templates.php']
                ]
            ],
            [
                'title' => 'Payments',
                'icon' => 'bx-money',
                'type' => 'dropdown',
                'id' => 'paymentsMenu',
                'items' => [
                    ['title' => 'All Payments', 'url' => 'payments.php'],
                    ['title' => 'Process Payment', 'url' => 'process_payment.php'],
                    ['title' => 'Payment History', 'url' => 'payment_history.php'],
                    ['title' => 'Refunds', 'url' => 'refunds.php'],
                    ['title' => 'Payment Methods', 'url' => 'payment_methods.php']
                ]
            ],
            [
                'title' => 'Financial Reports',
                'icon' => 'bx-line-chart',
                'type' => 'dropdown',
                'id' => 'financialReportsMenu',
                'items' => [
                    ['title' => 'Revenue Dashboard', 'url' => 'revenue_dashboard.php'],
                    ['title' => 'Accounts Receivable', 'url' => 'accounts_receivable.php'],
                    ['title' => 'Profit & Loss', 'url' => 'profit_loss.php'],
                    ['title' => 'Tax Reports', 'url' => 'tax_reports.php']
                ]
            ],
            [
                'title' => 'Operations',
                'type' => 'header'
            ],
            [
                'title' => 'Incidents',
                'icon' => 'bx-error',
                'type' => 'dropdown',
                'id' => 'incidentsMenu',
                'items' => [
                    ['title' => 'All Incidents', 'url' => 'incidents.php'],
                    ['title' => 'Report Incident', 'url' => 'report_incident.php'],
                    ['title' => 'Open Incidents', 'url' => 'open_incidents.php'],
                    ['title' => 'Incident Analytics', 'url' => 'incident_analytics.php']
                ]
            ],
            [
                'title' => 'Quality Assessments',
                'icon' => 'bx-check-shield',
                'type' => 'dropdown',
                'id' => 'qualityMenu',
                'items' => [
                    ['title' => 'All Assessments', 'url' => 'quality_assessments.php'],
                    ['title' => 'Create Assessment', 'url' => 'create_assessment.php'],
                    ['title' => 'Assessment Reports', 'url' => 'assessment_reports.php'],
                    ['title' => 'Client Feedback', 'url' => 'client_feedback.php']
                ]
            ],
            [
                'title' => 'Documents',
                'icon' => 'bx-folder',
                'type' => 'dropdown',
                'id' => 'documentsMenu',
                'items' => [
                    ['title' => 'All Documents', 'url' => 'documents.php'],
                    ['title' => 'Upload Document', 'url' => 'upload_document.php'],
                    ['title' => 'Expiring Documents', 'url' => 'expiring_documents.php'],
                    ['title' => 'Document Categories', 'url' => 'document_categories.php']
                ]
            ],
            [
                'title' => 'Communications',
                'icon' => 'bx-message-dots',
                'type' => 'dropdown',
                'id' => 'communicationsMenu',
                'items' => [
                    ['title' => 'Communication Log', 'url' => 'communication_log.php'],
                    ['title' => 'Send Message', 'url' => 'send_message.php'],
                    ['title' => 'Email Templates', 'url' => 'email_templates.php'],
                    ['title' => 'SMS Templates', 'url' => 'sms_templates.php']
                ]
            ],
            [
                'title' => 'Compliance & Security',
                'type' => 'header'
            ],
            [
                'title' => 'Compliance',
                'icon' => 'bx-shield',
                'type' => 'dropdown',
                'id' => 'complianceMenu',
                'items' => [
                    ['title' => 'Regulatory Requirements', 'url' => 'regulatory_requirements.php'],
                    ['title' => 'Compliance Dashboard', 'url' => 'compliance_dashboard.php'],
                    ['title' => 'Privacy Requests', 'url' => 'privacy_requests.php'],
                    ['title' => 'Data Retention', 'url' => 'data_retention.php']
                ]
            ],
            [
                'title' => 'Security',
                'icon' => 'bx-lock-alt',
                'type' => 'dropdown',
                'id' => 'securityMenu',
                'items' => [
                    ['title' => 'Security Incidents', 'url' => 'security_incidents.php'],
                    ['title' => 'Access Violations', 'url' => 'access_violations.php'],
                    ['title' => 'Audit Logs', 'url' => 'audit_logs.php'],
                    ['title' => 'Active Sessions', 'url' => 'active_sessions.php']
                ]
            ],
            [
                'title' => 'Reports & Analytics',
                'type' => 'header'
            ],
            [
                'title' => 'Reports',
                'icon' => 'bx-bar-chart-alt-2',
                'type' => 'dropdown',
                'id' => 'reportsMenu',
                'items' => [
                    ['title' => 'Report Dashboard', 'url' => 'report_dashboard.php'],
                    ['title' => 'Custom Reports', 'url' => 'custom_reports.php'],
                    ['title' => 'Report Templates', 'url' => 'report_templates.php'],
                    ['title' => 'Scheduled Reports', 'url' => 'scheduled_reports.php'],
                    ['title' => 'Performance Metrics', 'url' => 'performance_metrics.php']
                ]
            ],
            [
                'title' => 'System Administration',
                'type' => 'header'
            ],
            [
                'title' => 'System Settings',
                'icon' => 'bx-cog',
                'type' => 'dropdown',
                'id' => 'systemSettingsMenu',
                'items' => [
                    ['title' => 'General Settings', 'url' => 'system_settings.php'],
                    ['title' => 'Company Profile', 'url' => 'company_profile.php'],
                    ['title' => 'Email Configuration', 'url' => 'email_settings.php'],
                    ['title' => 'SMS Configuration', 'url' => 'sms_settings.php'],
                    ['title' => 'Backup & Restore', 'url' => 'backup_restore.php']
                ]
            ],
            [
                'title' => 'Integrations',
                'icon' => 'bx-plug',
                'type' => 'dropdown',
                'id' => 'integrationsMenu',
                'items' => [
                    ['title' => 'All Integrations', 'url' => 'integrations.php'],
                    ['title' => 'Calendar Sync', 'url' => 'calendar_sync.php'],
                    ['title' => 'Accounting Software', 'url' => 'accounting_integration.php'],
                    ['title' => 'Payment Gateway', 'url' => 'payment_gateway.php']
                ]
            ]
        ],
        
        'Caregiver' => [
            [
                'title' => 'My Work',
                'type' => 'header'
            ],
            [
                'title' => 'My Schedule',
                'icon' => 'bx-calendar',
                'type' => 'dropdown',
                'id' => 'myScheduleMenu',
                'items' => [
                    ['title' => 'Today\'s Schedule', 'url' => 'my_schedule_today.php'],
                    ['title' => 'Weekly Schedule', 'url' => 'my_schedule_week.php'],
                    ['title' => 'Monthly Schedule', 'url' => 'my_schedule_month.php'],
                    ['title' => 'Schedule History', 'url' => 'my_schedule_history.php']
                ]
            ],
            [
                'title' => 'Attendance',
                'icon' => 'bx-time-five',
                'type' => 'dropdown',
                'id' => 'myAttendanceMenu',
                'items' => [
                    ['title' => 'Clock In/Out', 'url' => 'clock_inout.php'],
                    ['title' => 'My Timesheet', 'url' => 'my_timesheet.php'],
                    ['title' => 'Attendance History', 'url' => 'my_attendance_history.php']
                ]
            ],
            [
                'title' => 'Clients',
                'type' => 'header'
            ],
            [
                'title' => 'My Clients',
                'icon' => 'bx-user-pin',
                'type' => 'dropdown',
                'id' => 'myClientsMenu',
                'items' => [
                    ['title' => 'Active Clients', 'url' => 'my_clients.php'],
                    ['title' => 'Client Care Plans', 'url' => 'my_client_care_plans.php'],
                    ['title' => 'Task Completion', 'url' => 'task_completion.php'],
                    ['title' => 'Client Notes', 'url' => 'client_notes.php']
                ]
            ],
            [
                'title' => 'Documentation',
                'type' => 'header'
            ],
            [
                'title' => 'My Documents',
                'icon' => 'bx-file',
                'type' => 'dropdown',
                'id' => 'myDocumentsMenu',
                'items' => [
                    ['title' => 'My Certifications', 'url' => 'my_certifications.php'],
                    ['title' => 'Upload Document', 'url' => 'upload_my_document.php'],
                    ['title' => 'Document Status', 'url' => 'my_document_status.php']
                ]
            ],
            [
                'title' => 'Performance',
                'type' => 'header'
            ],
            [
                'title' => 'My Performance',
                'icon' => 'bx-trophy',
                'type' => 'dropdown',
                'id' => 'myPerformanceMenu',
                'items' => [
                    ['title' => 'Performance Dashboard', 'url' => 'my_performance.php'],
                    ['title' => 'Quality Assessments', 'url' => 'my_assessments.php'],
                    ['title' => 'Training & Development', 'url' => 'my_training.php']
                ]
            ],
            [
                'title' => 'Communication',
                'icon' => 'bx-message',
                'url' => 'my_messages.php',
                'type' => 'link'
            ]
        ],
        
        'Client' => [
            [
                'title' => 'My Care',
                'type' => 'header'
            ],
            [
                'title' => 'My Care Plan',
                'icon' => 'bx-clinic',
                'type' => 'dropdown',
                'id' => 'myCarePlanMenu',
                'items' => [
                    ['title' => 'Care Plan Overview', 'url' => 'my_care_plan.php'],
                    ['title' => 'Care Tasks', 'url' => 'my_care_tasks.php'],
                    ['title' => 'Medical Information', 'url' => 'my_medical_info.php']
                ]
            ],
            [
                'title' => 'My Caregivers',
                'icon' => 'bx-user-circle',
                'type' => 'dropdown',
                'id' => 'myCaregiversMenu',
                'items' => [
                    ['title' => 'Assigned Caregivers', 'url' => 'my_caregivers.php'],
                    ['title' => 'Caregiver Schedule', 'url' => 'caregiver_schedule.php'],
                    ['title' => 'Rate Caregiver', 'url' => 'rate_caregiver.php']
                ]
            ],
            [
                'title' => 'Billing',
                'type' => 'header'
            ],
            [
                'title' => 'My Invoices',
                'icon' => 'bx-receipt',
                'type' => 'dropdown',
                'id' => 'myInvoicesMenu',
                'items' => [
                    ['title' => 'All Invoices', 'url' => 'my_invoices.php'],
                    ['title' => 'Make Payment', 'url' => 'make_payment.php'],
                    ['title' => 'Payment History', 'url' => 'my_payment_history.php'],
                    ['title' => 'Billing Summary', 'url' => 'my_billing_summary.php']
                ]
            ],
            [
                'title' => 'My Information',
                'type' => 'header'
            ],
            [
                'title' => 'My Documents',
                'icon' => 'bx-folder',
                'url' => 'my_documents.php',
                'type' => 'link'
            ],
            [
                'title' => 'Emergency Contacts',
                'icon' => 'bx-phone',
                'url' => 'emergency_contacts.php',
                'type' => 'link'
            ],
            [
                'title' => 'Communication',
                'icon' => 'bx-message',
                'url' => 'my_messages.php',
                'type' => 'link'
            ]
        ],
        
        'Accountant' => [
            [
                'title' => 'Financial Management',
                'type' => 'header'
            ],
            [
                'title' => 'Invoicing',
                'icon' => 'bx-receipt',
                'type' => 'dropdown',
                'id' => 'accountantInvoicingMenu',
                'items' => [
                    ['title' => 'All Invoices', 'url' => 'invoices.php'],
                    ['title' => 'Generate Invoice', 'url' => 'generate_invoice.php'],
                    ['title' => 'Draft Invoices', 'url' => 'draft_invoices.php'],
                    ['title' => 'Outstanding Invoices', 'url' => 'outstanding_invoices.php'],
                    ['title' => 'Overdue Invoices', 'url' => 'overdue_invoices.php']
                ]
            ],
            [
                'title' => 'Payments',
                'icon' => 'bx-money',
                'type' => 'dropdown',
                'id' => 'accountantPaymentsMenu',
                'items' => [
                    ['title' => 'All Payments', 'url' => 'payments.php'],
                    ['title' => 'Process Payment', 'url' => 'process_payment.php'],
                    ['title' => 'Payment History', 'url' => 'payment_history.php'],
                    ['title' => 'Refunds', 'url' => 'refunds.php']
                ]
            ],
            [
                'title' => 'Financial Reports',
                'icon' => 'bx-line-chart',
                'type' => 'dropdown',
                'id' => 'accountantReportsMenu',
                'items' => [
                    ['title' => 'Revenue Dashboard', 'url' => 'revenue_dashboard.php'],
                    ['title' => 'Accounts Receivable', 'url' => 'accounts_receivable.php'],
                    ['title' => 'Profit & Loss', 'url' => 'profit_loss.php'],
                    ['title' => 'Cash Flow', 'url' => 'cash_flow.php'],
                    ['title' => 'Tax Reports', 'url' => 'tax_reports.php'],
                    ['title' => 'Expense Reports', 'url' => 'expense_reports.php']
                ]
            ],
            [
                'title' => 'Payroll',
                'icon' => 'bx-wallet',
                'type' => 'dropdown',
                'id' => 'payrollMenu',
                'items' => [
                    ['title' => 'Payroll Dashboard', 'url' => 'payroll_dashboard.php'],
                    ['title' => 'Process Payroll', 'url' => 'process_payroll.php'],
                    ['title' => 'Payroll History', 'url' => 'payroll_history.php'],
                    ['title' => 'Overtime Report', 'url' => 'overtime_report.php']
                ]
            ],
            [
                'title' => 'Reconciliation',
                'icon' => 'bx-calculator',
                'url' => 'bank_reconciliation.php',
                'type' => 'link'
            ]
        ],
        
        'Super Admin' => [
            [
                'title' => 'Super Admin',
                'type' => 'header'
            ],
            [
                'title' => 'System Health',
                'icon' => 'bx-pulse',
                'url' => 'system_health.php',
                'type' => 'link'
            ],
            [
                'title' => 'Database Management',
                'icon' => 'bx-data',
                'type' => 'dropdown',
                'id' => 'databaseMenu',
                'items' => [
                    ['title' => 'Database Status', 'url' => 'database_status.php'],
                    ['title' => 'Backup Now', 'url' => 'backup_now.php'],
                    ['title' => 'Restore Database', 'url' => 'restore_database.php'],
                    ['title' => 'Optimize Tables', 'url' => 'optimize_tables.php']
                ]
            ]
        ]
    ];
    
    // Account menu (common for all roles)
    $accountMenu = [
        [
            'title' => 'Account',
            'type' => 'header'
        ],
        [
            'title' => 'My Profile',
            'icon' => 'bx-user',
            'url' => 'profile.php',
            'type' => 'link'
        ],
        [
            'title' => 'Notifications',
            'icon' => 'bx-bell',
            'url' => 'notifications.php',
            'type' => 'link'
        ],
        [
            'title' => 'Reminders',
            'icon' => 'bx-alarm',
            'url' => 'reminders.php',
            'type' => 'link'
        ],
        [
            'title' => 'Change Password',
            'icon' => 'bx-lock-alt',
            'url' => 'change_password.php',
            'type' => 'link'
        ],
        [
            'title' => 'Help & Support',
            'icon' => 'bx-help-circle',
            'url' => 'help_support.php',
            'type' => 'link'
        ],
        [
            'title' => 'Logout',
            'icon' => 'bx-log-out',
            'url' => 'logout.php',
            'type' => 'link',
            'class' => 'text-danger'
        ]
    ];
    
    // Combine menus
    $menu = $commonMenus;
    
    // Super Admin gets Admin menus plus their own
    if ($userRole === 'Super Admin') {
        if (isset($roleMenus['Admin'])) {
            $menu = array_merge($menu, $roleMenus['Admin']);
        }
        if (isset($roleMenus['Super Admin'])) {
            $menu = array_merge($menu, $roleMenus['Super Admin']);
        }
    } elseif (isset($roleMenus[$userRole])) {
        $menu = array_merge($menu, $roleMenus[$userRole]);
    }
    
    $menu = array_merge($menu, $accountMenu);
    
    // Apply access control filtering
    if ($userRole !== 'Super Admin' && $userRole !== 'Admin' && !empty($assignedPages) && !in_array('*', $assignedPages)) {
        $menu = filterMenuByAssignedPages($menu, $assignedPages);
    }
    
    return $menu;
}

/**
 * Filter menu based on assigned pages
 */
function filterMenuByAssignedPages($menu, $assignedPages) {
    $filteredMenu = [];
    $currentSection = null;
    $sectionItems = [];
    
    // Always allowed pages
    $alwaysAllowed = [
        'index.php', 'profile.php', 'change_password.php', 'logout.php',
        'notifications.php', 'reminders.php', 'help_support.php'
    ];
    
    foreach ($menu as $item) {
        if ($item['type'] === 'header') {
            if ($currentSection !== null && !empty($sectionItems)) {
                $filteredMenu[] = $currentSection;
                $filteredMenu = array_merge($filteredMenu, $sectionItems);
            }
            $currentSection = $item;
            $sectionItems = [];
        } elseif ($item['type'] === 'link') {
            if (in_array($item['url'], $alwaysAllowed) || in_array($item['url'], $assignedPages)) {
                $sectionItems[] = $item;
            }
        } elseif ($item['type'] === 'dropdown') {
            $filteredItems = [];
            foreach ($item['items'] as $subItem) {
                if (in_array($subItem['url'], $assignedPages) || in_array($subItem['url'], $alwaysAllowed)) {
                    $filteredItems[] = $subItem;
                }
            }
            if (!empty($filteredItems)) {
                $item['items'] = $filteredItems;
                $sectionItems[] = $item;
            }
        }
    }
    
    if ($currentSection !== null && !empty($sectionItems)) {
        $filteredMenu[] = $currentSection;
        $filteredMenu = array_merge($filteredMenu, $sectionItems);
    }
    
    return $filteredMenu;
}

/**
 * Get caregiver-specific notifications count
 */
function getNotificationCount($conn, $userId) {
    $notifications = [
        'schedules' => 0, 'certifications' => 0, 'contracts' => 0,
        'invoices' => 0, 'incidents' => 0, 'assessments' => 0, 'reminders' => 0
    ];
    
    if (!$conn || !$userId) return $notifications;
    
    try {
        $queries = [
            'schedules' => "SELECT COUNT(*) as count FROM schedules WHERE shift_date = CURDATE() AND status IN ('scheduled', 'confirmed')",
            'certifications' => "SELECT COUNT(*) as count FROM caregiver_certifications WHERE expiry_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) AND expiry_date >= CURDATE() AND status = 'active'",
            'contracts' => "SELECT COUNT(*) as count FROM client_contracts WHERE end_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) AND end_date >= CURDATE() AND status = 'active'",
            'invoices' => "SELECT COUNT(*) as count FROM invoices WHERE status IN ('sent', 'partial_payment', 'overdue') AND due_date < CURDATE()",
            'incidents' => "SELECT COUNT(*) as count FROM incidents WHERE status IN ('reported', 'investigating', 'action_required')",
            'assessments' => "SELECT COUNT(*) as count FROM quality_assessments WHERE status IN ('draft', 'action_required')",
            'reminders' => "SELECT COUNT(*) as count FROM reminders WHERE reminder_date = CURDATE() AND is_active = 1 AND status = 'pending'"
        ];
        
        foreach ($queries as $key => $sql) {
            $result = $conn->query($sql);
            if ($result) {
                $notifications[$key] = $result->fetch_assoc()['count'];
            }
        }
    } catch (Exception $e) {
        error_log("Error getting notifications: " . $e->getMessage());
    }
    
    return $notifications;
}

/**
 * Get menu with notification badges
 */
function getMenuWithNotifications($userRole, $userId = null, $conn = null) {
    $notifications = getNotificationCount($conn, $userId);
    $menuConfig = getMenuConfig($userRole, [], $conn, $userId);
    
    foreach ($menuConfig as &$item) {
        if ($item['type'] === 'dropdown') {
            $badges = [
                'schedulingMenu' => ['schedules', 'bg-primary'],
                'myScheduleMenu' => ['schedules', 'bg-primary'],
                'certificationsMenu' => ['certifications', 'bg-warning'],
                'myDocumentsMenu' => ['certifications', 'bg-warning'],
                'contractsMenu' => ['contracts', 'bg-info'],
                'invoicingMenu' => ['invoices', 'bg-danger'],
                'accountantInvoicingMenu' => ['invoices', 'bg-danger'],
                'myInvoicesMenu' => ['invoices', 'bg-danger'],
                'incidentsMenu' => ['incidents', 'bg-danger'],
                'qualityMenu' => ['assessments', 'bg-success'],
                'myPerformanceMenu' => ['assessments', 'bg-success']
            ];
            
            if (isset($badges[$item['id']])) {
                list($notifKey, $badgeClass) = $badges[$item['id']];
                if ($notifications[$notifKey] > 0) {
                    $item['badge'] = $notifications[$notifKey];
                    $item['badge_class'] = $badgeClass;
                }
            }
        } elseif ($item['type'] === 'link' && isset($item['url'])) {
            if ($item['url'] === 'reminders.php' && $notifications['reminders'] > 0) {
                $item['badge'] = $notifications['reminders'];
                $item['badge_class'] = 'bg-warning';
            }
        }
    }
    
    return $menuConfig;
}

/**
 * Main menu rendering function
 */
function renderMenu($userRole, $userId = null, $conn = null, $debug = false) {
    $assignedPages = [];
    if ($conn && $userId) {
        $userData = getUserAssignedPages($conn, $userId);
        $assignedPages = $userData['pages'];
        if ($debug) {
            echo "<!-- DEBUG: User Role: $userRole -->";
            echo "<!-- DEBUG: Assigned Pages: " . json_encode($assignedPages) . " -->";
        }
    }
    
    $menuConfig = getMenuConfig($userRole, $assignedPages, $conn, $userId);
    $currentPage = getCurrentPage();
    $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') {
            $isActive = isMenuActive($item['url'], $currentPage);
            $classAttr = isset($item['class']) ? ' ' . $item['class'] : '';
            $html .= '<li class="nav-item">';
            $html .= '<a class="nav-link menu-link' . ($isActive ? ' active' : '') . $classAttr . '" 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>';
            if (isset($item['badge']) && $item['badge'] > 0) {
                $badgeClass = $item['badge_class'] ?? 'bg-primary';
                $html .= '<span class="badge ' . $badgeClass . ' ms-auto">' . $item['badge'] . '</span>';
            }
            $html .= '</a></li>';
        } elseif ($item['type'] === 'dropdown') {
            $hasActiveSubItem = hasActiveItem($item['items'], $currentPage);
            $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>';
            if (isset($item['badge']) && $item['badge'] > 0) {
                $badgeClass = $item['badge_class'] ?? 'bg-primary';
                $html .= '<span class="badge ' . $badgeClass . ' ms-auto">' . $item['badge'] . '</span>';
            }
            $html .= '</a>';
            $html .= '<div class="collapse menu-dropdown' . ($hasActiveSubItem ? ' show' : '') . '" id="' . $item['id'] . '">';
            $html .= '<ul class="nav nav-sm flex-column">';
            foreach ($item['items'] as $subItem) {
                $isSubActive = isMenuActive($subItem['url'], $currentPage);
                $html .= '<li class="nav-item">';
                $html .= '<a href="' . htmlspecialchars($subItem['url']) . '" class="nav-link' . ($isSubActive ? ' active' : '') . '">';
                $html .= htmlspecialchars($subItem['title']);
                $html .= '</a></li>';
            }
            $html .= '</ul></div></li>';
        }
    }
    
    return $html;
}

/**
 * Enhanced menu rendering with notifications
 */
function renderMenuWithNotifications($userRole, $userId = null, $conn = null, $debug = false) {
    $menuConfig = getMenuWithNotifications($userRole, $userId, $conn);
    $currentPage = getCurrentPage();
    $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') {
            $isActive = isMenuActive($item['url'], $currentPage);
            $classAttr = isset($item['class']) ? ' ' . $item['class'] : '';
            $html .= '<li class="nav-item">';
            $html .= '<a class="nav-link menu-link' . ($isActive ? ' active' : '') . $classAttr . '" 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>';
            if (isset($item['badge']) && $item['badge'] > 0) {
                $badgeClass = $item['badge_class'] ?? 'bg-primary';
                $html .= '<span class="badge ' . $badgeClass . ' ms-auto">' . $item['badge'] . '</span>';
            }
            $html .= '</a></li>';
        } elseif ($item['type'] === 'dropdown') {
            $hasActiveSubItem = hasActiveItem($item['items'], $currentPage);
            $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>';
            if (isset($item['badge']) && $item['badge'] > 0) {
                $badgeClass = $item['badge_class'] ?? 'bg-primary';
                $html .= '<span class="badge ' . $badgeClass . ' ms-auto">' . $item['badge'] . '</span>';
            }
            $html .= '</a>';
            $html .= '<div class="collapse menu-dropdown' . ($hasActiveSubItem ? ' show' : '') . '" id="' . $item['id'] . '">';
            $html .= '<ul class="nav nav-sm flex-column">';
            foreach ($item['items'] as $subItem) {
                $isSubActive = isMenuActive($subItem['url'], $currentPage);
                $html .= '<li class="nav-item">';
                $html .= '<a href="' . htmlspecialchars($subItem['url']) . '" class="nav-link' . ($isSubActive ? ' active' : '') . '">';
                $html .= htmlspecialchars($subItem['title']);
                $html .= '</a></li>';
            }
            $html .= '</ul></div></li>';
        }
    }
    
    return $html;
}

/**
 * Helper functions
 */
function getCurrentPage() {
    return basename($_SERVER['PHP_SELF']);
}

function isMenuActive($url, $currentPage = null) {
    if ($currentPage === null) {
        $currentPage = getCurrentPage();
    }
    return $currentPage === $url;
}

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 actions for dashboard
 */
function getQuickActions($userRole, $assignedPages = []) {
    $allQuickActions = [
        'Admin' => [
            ['title' => 'Create Schedule', 'url' => 'create_schedule.php', 'icon' => 'bx-calendar', 'color' => 'primary'],
            ['title' => 'Add Client', 'url' => 'add_client.php', 'icon' => 'bx-user-plus', 'color' => 'success'],
            ['title' => 'Add Caregiver', 'url' => 'add_caregiver.php', 'icon' => 'bx-user-circle', 'color' => 'info'],
            ['title' => 'Generate Invoice', 'url' => 'generate_invoice.php', 'icon' => 'bx-receipt', 'color' => 'warning'],
            ['title' => 'Create Care Plan', 'url' => 'create_care_plan.php', 'icon' => 'bx-clinic', 'color' => 'danger'],
            ['title' => 'Reports', 'url' => 'report_dashboard.php', 'icon' => 'bx-bar-chart-alt-2', 'color' => 'secondary']
        ],
        'Caregiver' => [
            ['title' => 'Clock In/Out', 'url' => 'clock_inout.php', 'icon' => 'bx-time', 'color' => 'primary'],
            ['title' => 'Today\'s Schedule', 'url' => 'my_schedule_today.php', 'icon' => 'bx-calendar-event', 'color' => 'success'],
            ['title' => 'My Clients', 'url' => 'my_clients.php', 'icon' => 'bx-user-pin', 'color' => 'info'],
            ['title' => 'Complete Tasks', 'url' => 'task_completion.php', 'icon' => 'bx-check-circle', 'color' => 'warning'],
            ['title' => 'My Timesheet', 'url' => 'my_timesheet.php', 'icon' => 'bx-spreadsheet', 'color' => 'danger'],
            ['title' => 'Messages', 'url' => 'my_messages.php', 'icon' => 'bx-message', 'color' => 'secondary']
        ],
        'Client' => [
            ['title' => 'My Care Plan', 'url' => 'my_care_plan.php', 'icon' => 'bx-clinic', 'color' => 'primary'],
            ['title' => 'Caregiver Schedule', 'url' => 'caregiver_schedule.php', 'icon' => 'bx-calendar', 'color' => 'success'],
            ['title' => 'My Invoices', 'url' => 'my_invoices.php', 'icon' => 'bx-receipt', 'color' => 'info'],
            ['title' => 'Make Payment', 'url' => 'make_payment.php', 'icon' => 'bx-money', 'color' => 'warning'],
            ['title' => 'Messages', 'url' => 'my_messages.php', 'icon' => 'bx-message', 'color' => 'danger'],
            ['title' => 'Emergency Contacts', 'url' => 'emergency_contacts.php', 'icon' => 'bx-phone', 'color' => 'secondary']
        ],
        'Accountant' => [
            ['title' => 'Revenue Dashboard', 'url' => 'revenue_dashboard.php', 'icon' => 'bx-trending-up', 'color' => 'primary'],
            ['title' => 'Generate Invoice', 'url' => 'generate_invoice.php', 'icon' => 'bx-receipt', 'color' => 'success'],
            ['title' => 'Process Payment', 'url' => 'process_payment.php', 'icon' => 'bx-money', 'color' => 'info'],
            ['title' => 'Outstanding Invoices', 'url' => 'outstanding_invoices.php', 'icon' => 'bx-time', 'color' => 'warning'],
            ['title' => 'Financial Reports', 'url' => 'profit_loss.php', 'icon' => 'bx-line-chart', 'color' => 'danger'],
            ['title' => 'Process Payroll', 'url' => 'process_payroll.php', 'icon' => 'bx-wallet', 'color' => 'secondary']
        ],
        'Super Admin' => [
            ['title' => 'System Health', 'url' => 'system_health.php', 'icon' => 'bx-pulse', 'color' => 'primary'],
            ['title' => 'User Management', 'url' => 'users.php', 'icon' => 'bx-group', 'color' => 'success'],
            ['title' => 'Security Dashboard', 'url' => 'security_incidents.php', 'icon' => 'bx-shield', 'color' => 'info'],
            ['title' => 'Audit Logs', 'url' => 'audit_logs.php', 'icon' => 'bx-data', 'color' => 'warning'],
            ['title' => 'System Settings', 'url' => 'system_settings.php', 'icon' => 'bx-cog', 'color' => 'danger'],
            ['title' => 'Backup & Restore', 'url' => 'backup_restore.php', 'icon' => 'bx-save', 'color' => 'secondary']
        ]
    ];
    
    $roleActions = $allQuickActions[$userRole] ?? [];
    
    if ($userRole !== 'Super Admin' && $userRole !== 'Admin' && !empty($assignedPages) && !in_array('*', $assignedPages)) {
        $roleActions = array_filter($roleActions, function($action) use ($assignedPages) {
            return in_array($action['url'], $assignedPages);
        });
    }
    
    return $roleActions;
}

/**
 * Get dashboard statistics
 */
function getDashboardStats($conn, $userId, $userRole) {
    $stats = [
        'caregivers_active' => 0, 'clients_active' => 0, 'schedules_today' => 0,
        'revenue_month' => 0, 'pending_invoices' => 0, 'expiring_certs' => 0,
        'open_incidents' => 0, 'quality_score' => 0
    ];
    
    if (!$conn) return $stats;
    
    try {
        $queries = [
            'caregivers_active' => "SELECT COUNT(*) as count FROM caregivers WHERE is_active = 1",
            'clients_active' => "SELECT COUNT(*) as count FROM clients WHERE status = 'active'",
            'schedules_today' => "SELECT COUNT(*) as count FROM schedules WHERE shift_date = CURDATE()",
            'revenue_month' => "SELECT COALESCE(SUM(total_amount), 0) as total FROM invoices WHERE MONTH(invoice_date) = MONTH(CURDATE()) AND YEAR(invoice_date) = YEAR(CURDATE()) AND status = 'paid'",
            'pending_invoices' => "SELECT COUNT(*) as count FROM invoices WHERE status IN ('sent', 'partial_payment', 'overdue')",
            'expiring_certs' => "SELECT COUNT(*) as count FROM caregiver_certifications WHERE expiry_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) AND status = 'active'",
            'open_incidents' => "SELECT COUNT(*) as count FROM incidents WHERE status IN ('reported', 'investigating', 'action_required')"
        ];
        
        foreach ($queries as $key => $sql) {
            $result = $conn->query($sql);
            if ($result) {
                $row = $result->fetch_assoc();
                $stats[$key] = $row['count'] ?? $row['total'] ?? 0;
            }
        }
        
        $sql = "SELECT AVG(overall_rating) as avg_score FROM quality_assessments WHERE assessment_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
        $result = $conn->query($sql);
        if ($result) {
            $row = $result->fetch_assoc();
            $stats['quality_score'] = $row['avg_score'] ? round($row['avg_score'], 1) : 0;
        }
    } catch (Exception $e) {
        error_log("Error getting dashboard stats: " . $e->getMessage());
    }
    
    return $stats;
}

/**
 * Get breadcrumb navigation
 */
function getBreadcrumb($currentPage, $menuConfig = null) {
    if (!$menuConfig) {
        return [['title' => 'Dashboard', 'url' => 'index.php']];
    }
    
    $breadcrumb = [['title' => 'Dashboard', 'url' => 'index.php']];
    
    foreach ($menuConfig as $item) {
        if ($item['type'] === 'link' && $item['url'] === $currentPage) {
            $breadcrumb[] = ['title' => $item['title'], 'url' => null];
            break;
        } elseif ($item['type'] === 'dropdown') {
            foreach ($item['items'] as $subItem) {
                if ($subItem['url'] === $currentPage) {
                    $breadcrumb[] = ['title' => $item['title'], 'url' => null];
                    $breadcrumb[] = ['title' => $subItem['title'], 'url' => null];
                    break 2;
                }
            }
        }
    }
    
    return $breadcrumb;
}

/**
 * Check if user has access to specific page
 */
function hasPageAccess($userId, $pageUrl, $conn) {
    if (!$conn || !$userId) return false;
    
    try {
        $sql = "SELECT ur.role_name FROM users u 
                INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                WHERE u.user_id = ? AND u.status = 'active'";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) return false;
        
        $user = $result->fetch_assoc();
        if ($user['role_name'] === 'Super Admin' || $user['role_name'] === 'Admin') {
            return true;
        }
        
        $userData = getUserAssignedPages($conn, $userId);
        $assignedPages = $userData['pages'];
        $alwaysAllowed = ['index.php', 'profile.php', 'change_password.php', 'logout.php', 'notifications.php', 'reminders.php', 'help_support.php'];
        
        return in_array($pageUrl, $alwaysAllowed) || in_array($pageUrl, $assignedPages);
    } catch (Exception $e) {
        error_log("Error checking page access: " . $e->getMessage());
        return false;
    }
}

/**
 * Format currency
 */
function formatCurrency($amount, $currency = 'USD') {
    $symbols = ['USD' => '$', 'EUR' => 'â‚¬', 'GBP' => 'Â£', 'KES' => 'KSh ', 'UGX' => 'USh ', 'TZS' => 'TSh '];
    $symbol = $symbols[$currency] ?? $currency . ' ';
    return $symbol . number_format($amount, 2);
}

/**
 * Get system health status
 */
function getSystemHealth($conn) {
    $health = ['database' => 'healthy', 'schedules' => 'healthy', 'certifications' => 'healthy', 'invoices' => 'healthy', 'overall' => 'healthy'];
    
    if (!$conn) {
        $health['database'] = 'error';
        $health['overall'] = 'error';
        return $health;
    }
    
    try {
        $checks = [
            'schedules' => ["SELECT COUNT(*) as count FROM schedules WHERE shift_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)", 0, 'warning'],
            'certifications' => ["SELECT COUNT(*) as count FROM caregiver_certifications WHERE expiry_date < CURDATE() AND status = 'active'", 0, 'error'],
            'invoices' => ["SELECT COUNT(*) as count FROM invoices WHERE due_date < DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND status IN ('sent', 'overdue')", 10, 'warning']
        ];
        
        foreach ($checks as $key => $check) {
            $result = $conn->query($check[0]);
            if ($result) {
                $count = $result->fetch_assoc()['count'];
                if (($check[1] == 0 && $count == 0) || ($check[1] > 0 && $count > $check[1])) {
                    $health[$key] = $check[2];
                }
            }
        }
        
        $statuses = array_values($health);
        if (in_array('error', $statuses)) {
            $health['overall'] = 'error';
        } elseif (in_array('warning', $statuses)) {
            $health['overall'] = 'warning';
        }
    } catch (Exception $e) {
        error_log("Error checking system health: " . $e->getMessage());
        $health['overall'] = 'error';
    }
    
    return $health;
}

/**
 * Log menu access
 */
function logMenuAccess($conn, $userId, $menuItem, $ipAddress = null) {
    if (!$conn || !$userId) return false;
    
    try {
        $ip = $ipAddress ?: ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
        $sql = "INSERT INTO audit_log (user_id, action_type, entity_type, description, ip_address, created_at) 
                VALUES (?, 'ACCESS', 'menu', ?, ?, NOW())";
        $stmt = $conn->prepare($sql);
        $description = json_encode(['menu_item' => $menuItem, 'timestamp' => date('Y-m-d H:i:s')]);
        $stmt->bind_param("iss", $userId, $description, $ip);
        return $stmt->execute();
    } catch (Exception $e) {
        error_log("Error logging menu access: " . $e->getMessage());
        return false;
    }
}

/**
 * Get role-based homepage content
 */
function getRoleHomepageContent($userRole) {
    $content = [
        'Admin' => [
            'welcome_message' => 'Welcome to the Caregiver Management System',
            'description' => 'Manage caregivers, clients, schedules, and all aspects of your caregiving operations.',
            'key_features' => ['Complete caregiver and client management', 'Advanced scheduling with conflict resolution', 'Automated invoicing and payment tracking', 'Comprehensive reporting and analytics', 'Compliance and security monitoring']
        ],
        'Caregiver' => [
            'welcome_message' => 'Welcome to Your Caregiver Portal',
            'description' => 'View your schedules, manage client care, and track your performance.',
            'key_features' => ['View your daily and weekly schedules', 'Clock in/out and track attendance', 'Access client care plans and tasks', 'Submit task completions and notes', 'View your performance metrics']
        ],
        'Client' => [
            'welcome_message' => 'Welcome to Your Care Portal',
            'description' => 'Access your care information, view schedules, and manage your account.',
            'key_features' => ['View your care plan and services', 'See assigned caregiver schedules', 'Access invoices and make payments', 'Communicate with your care team', 'Update your medical information']
        ],
        'Accountant' => [
            'welcome_message' => 'Welcome to Financial Management',
            'description' => 'Manage invoicing, payments, and financial reporting.',
            'key_features' => ['Generate and manage invoices', 'Process payments and refunds', 'View financial reports and analytics', 'Handle payroll processing', 'Monitor accounts receivable']
        ],
        'Super Admin' => [
            'welcome_message' => 'System Administration Dashboard',
            'description' => 'Full system access for configuration, security, and monitoring.',
            'key_features' => ['Complete system administration', 'User and role management', 'Security and compliance monitoring', 'System settings and configuration', 'Audit logs and activity tracking']
        ]
    ];
    
    return $content[$userRole] ?? $content['Admin'];
}

/**
 * Validate menu structure
 */
function validateMenuStructure($menuConfig) {
    $errors = [];
    
    foreach ($menuConfig as $index => $item) {
        if (!isset($item['type'])) {
            $errors[] = "Item at index $index missing 'type ' field";
        }
        
        if ($item['type'] === 'link' || $item['type'] === 'dropdown') {
            if (!isset($item['title'])) {
                $errors[] = "Item at index $index missing 'title' field";
            }
            if (!isset($item['icon'])) {
                $errors[] = "Item at index $index missing 'icon' field";
            }
        }
        
        if ($item['type'] === 'link' && !isset($item['url'])) {
            $errors[] = "Link item at index $index missing 'url' field";
        }
        
        if ($item['type'] === 'dropdown') {
            if (!isset($item['id'])) {
                $errors[] = "Dropdown at index $index missing 'id' field";
            }
            if (!isset($item['items']) || !is_array($item['items'])) {
                $errors[] = "Dropdown at index $index missing or invalid 'items' array";
            }
        }
    }
    
    return ['valid' => empty($errors), 'errors' => $errors];
}

/**
 * Export menu configuration as JSON
 */
function exportMenuConfigJSON($userRole, $conn = null, $userId = null) {
    $menuConfig = getMenuConfig($userRole, [], $conn, $userId);
    return json_encode($menuConfig, JSON_PRETTY_PRINT);
}

/**
 * Get role-based permissions
 */
function getRolePermissions($conn, $roleId) {
    if (!$conn || !$roleId) return [];
    
    $permissions = [];
    
    try {
        $sql = "SELECT resource_type, permission_type 
                FROM role_permissions 
                WHERE role_id = ? AND is_active = 1";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $roleId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            if (!isset($permissions[$row['resource_type']])) {
                $permissions[$row['resource_type']] = [];
            }
            $permissions[$row['resource_type']][] = $row['permission_type'];
        }
    } catch (Exception $e) {
        error_log("Error getting role permissions: " . $e->getMessage());
    }
    
    return $permissions;
}

/**
 * Check specific permission
 */
function hasPermission($conn, $userId, $resource, $permissionType) {
    if (!$conn || !$userId) return false;
    
    try {
        $sql = "SELECT COUNT(*) as count
                FROM users u
                INNER JOIN role_permissions rp ON u.role_id = rp.role_id
                WHERE u.user_id = ? AND rp.resource_type = ? AND rp.permission_type = ? 
                AND rp.is_active = 1 AND u.status = 'active'";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iss", $userId, $resource, $permissionType);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        return $row['count'] > 0;
    } catch (Exception $e) {
        error_log("Error checking permission: " . $e->getMessage());
        return false;
    }
}

/**
 * Get caregiver-specific dashboard widgets
 */
function getCaregiverWidgets($conn, $userId) {
    $widgets = ['today_schedules' => [], 'pending_tasks' => 0, 'hours_this_week' => 0, 'upcoming_clients' => []];
    
    if (!$conn || !$userId) return $widgets;
    
    try {
        $sql = "SELECT caregiver_id FROM caregivers WHERE user_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) return $widgets;
        
        $caregiver = $result->fetch_assoc();
        $caregiverId = $caregiver['caregiver_id'];
        
        // Today's schedules
        $sql = "SELECT s.*, 
                       JSON_UNQUOTE(JSON_EXTRACT(c.personal_info, '$.first_name')) as client_first_name,
                       JSON_UNQUOTE(JSON_EXTRACT(c.personal_info, '$.last_name')) as client_last_name
                FROM schedules s
                INNER JOIN clients c ON s.client_id = c.client_id
                WHERE s.caregiver_id = ? AND s.shift_date = CURDATE()
                ORDER BY s.start_time";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $caregiverId);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $widgets['today_schedules'][] = $row;
        }
        
        // Pending tasks
        $sql = "SELECT COUNT(*) as count
                FROM schedule_task_completions stc
                INNER JOIN schedules s ON stc.schedule_id = s.schedule_id
                WHERE s.caregiver_id = ? AND stc.completion_status = 'pending' AND s.shift_date = CURDATE()";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $caregiverId);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $widgets['pending_tasks'] = $row['count'];
        
        // Hours this week
        $sql = "SELECT COALESCE(SUM(total_hours), 0) as total
                FROM schedules
                WHERE caregiver_id = ? AND YEARWEEK(shift_date, 1) = YEARWEEK(CURDATE(), 1) AND status = 'completed'";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $caregiverId);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $widgets['hours_this_week'] = $row['total'];
    } catch (Exception $e) {
        error_log("Error getting caregiver widgets: " . $e->getMessage());
    }
    
    return $widgets;
}

/**
 * Get client-specific dashboard widgets
 */
function getClientWidgets($conn, $userId) {
    $widgets = ['next_visit' => null, 'assigned_caregiver' => null, 'pending_invoices' => 0, 'care_plan_status' => null];
    
    if (!$conn || !$userId) return $widgets;
    
    try {
        $sql = "SELECT client_id FROM clients WHERE user_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) return $widgets;
        
        $client = $result->fetch_assoc();
        $clientId = $client['client_id'];
        
        // Next visit
        $sql = "SELECT s.*, 
                       JSON_UNQUOTE(JSON_EXTRACT(cg.personal_info, '$.first_name')) as caregiver_first_name,
                       JSON_UNQUOTE(JSON_EXTRACT(cg.personal_info, '$.last_name')) as caregiver_last_name
                FROM schedules s
                INNER JOIN caregivers cg ON s.caregiver_id = cg.caregiver_id
                WHERE s.client_id = ? AND s.shift_date >= CURDATE() AND s.status IN ('scheduled', 'confirmed')
                ORDER BY s.shift_date, s.start_time LIMIT 1";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $clientId);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $widgets['next_visit'] = $result->fetch_assoc();
        }
        
        // Pending invoices
        $sql = "SELECT COUNT(*) as count FROM invoices WHERE client_id = ? AND status IN ('sent', 'partial_payment', 'overdue')";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $clientId);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $widgets['pending_invoices'] = $row['count'];
        
        // Active care plan
        $sql = "SELECT * FROM care_plans WHERE client_id = ? AND status = 'active' ORDER BY start_date DESC LIMIT 1";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $clientId);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $widgets['care_plan_status'] = $result->fetch_assoc();
        }
    } catch (Exception $e) {
        error_log("Error getting client widgets: " . $e->getMessage());
    }
    
    return $widgets;
}

/**
 * Get upcoming reminders for user
 */
function getUpcomingReminders($conn, $userId, $userRole, $limit = 5) {
    if (!$conn || !$userId) return [];
    
    $reminders = [];
    
    try {
        $targetType = match($userRole) {
            'Caregiver' => 'caregiver',
            'Client' => 'client',
            'Admin', 'Super Admin', 'Accountant' => 'admin',
            default => 'admin'
        };
        
        $sql = "SELECT * FROM reminders 
                WHERE (target_type = ? OR target_type = 'all_staff')
                AND reminder_date >= CURDATE() AND is_active = 1 AND status = 'pending'
                ORDER BY reminder_date ASC, reminder_time ASC LIMIT ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $targetType, $limit);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $reminders[] = $row;
        }
    } catch (Exception $e) {
        error_log("Error getting reminders: " . $e->getMessage());
    }
    
    return $reminders;
}

/**
 * Get recent activities for dashboard
 */
function getRecentActivities($conn, $userId, $userRole, $limit = 10) {
    if (!$conn || !$userId) return [];
    
    $activities = [];
    
    try {
        if ($userRole === 'Caregiver') {
            $sql = "SELECT s.schedule_id, s.shift_date, s.start_time, s.end_time, s.status,
                           JSON_UNQUOTE(JSON_EXTRACT(c.personal_info, '$.first_name')) as client_first_name,
                           JSON_UNQUOTE(JSON_EXTRACT(c.personal_info, '$.last_name')) as client_last_name
                    FROM schedules s
                    INNER JOIN caregivers cg ON s.caregiver_id = cg.caregiver_id
                    INNER JOIN clients c ON s.client_id = c.client_id
                    WHERE cg.user_id = ? ORDER BY s.shift_date DESC, s.start_time DESC LIMIT ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ii", $userId, $limit);
        } elseif ($userRole === 'Client') {
            $sql = "SELECT s.schedule_id, s.shift_date, s.start_time, s.end_time, s.status,
                           JSON_UNQUOTE(JSON_EXTRACT(cg.personal_info, '$.first_name')) as caregiver_first_name,
                           JSON_UNQUOTE(JSON_EXTRACT(cg.personal_info, '$.last_name')) as caregiver_last_name
                    FROM schedules s
                    INNER JOIN clients c ON s.client_id = c.client_id
                    INNER JOIN caregivers cg ON s.caregiver_id = cg.caregiver_id
                    WHERE c.user_id = ? ORDER BY s.shift_date DESC, s.start_time DESC LIMIT ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ii", $userId, $limit);
        } else {
            $sql = "SELECT user_id, action_type, entity_type, description, created_at
                    FROM audit_log WHERE status = 'SUCCESS' ORDER BY created_at DESC LIMIT ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $limit);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $activities[] = $row;
        }
    } catch (Exception $e) {
        error_log("Error getting activities: " . $e->getMessage());
    }
    
    return $activities;
}

/**
 * Get menu item count
 */
function getMenuItemCount($menuConfig) {
    $count = 0;
    foreach ($menuConfig as $item) {
        if ($item['type'] === 'link') {
            $count++;
        } elseif ($item['type'] === 'dropdown' && isset($item['items'])) {
            $count += count($item['items']);
        }
    }
    return $count;
}

/**
 * Search menu items
 */
function searchMenuItems($menuConfig, $searchTerm) {
    $results = [];
    $searchTerm = strtolower($searchTerm);
    
    foreach ($menuConfig as $item) {
        if ($item['type'] === 'link') {
            if (strpos(strtolower($item['title']), $searchTerm) !== false) {
                $results[] = [
                    'title' => $item['title'],
                    'url' => $item['url'],
                    'icon' => $item['icon'],
                    'type' => 'link'
                ];
            }
        } elseif ($item['type'] === 'dropdown' && isset($item['items'])) {
            foreach ($item['items'] as $subItem) {
                if (strpos(strtolower($subItem['title']), $searchTerm) !== false) {
                    $results[] = [
                        'title' => $subItem['title'],
                        'url' => $subItem['url'],
                        'parent' => $item['title'],
                        'icon' => $item['icon'],
                        'type' => 'dropdown-item'
                    ];
                }
            }
        }
    }
    
    return $results;
}

/**
 * Get menu structure as array (for API responses)
 */
function getMenuStructureArray($userRole, $conn = null, $userId = null) {
    $menuConfig = getMenuConfig($userRole, [], $conn, $userId);
    $structure = [];
    
    foreach ($menuConfig as $item) {
        if ($item['type'] === 'header') {
            $structure[] = [
                'type' => 'section',
                'title' => $item['title'],
                'items' => []
            ];
        } elseif ($item['type'] === 'link') {
            $lastIndex = count($structure) - 1;
            if ($lastIndex >= 0 && $structure[$lastIndex]['type'] === 'section') {
                $structure[$lastIndex]['items'][] = [
                    'type' => 'link',
                    'title' => $item['title'],
                    'url' => $item['url'],
                    'icon' => $item['icon']
                ];
            }
        } elseif ($item['type'] === 'dropdown') {
            $lastIndex = count($structure) - 1;
            if ($lastIndex >= 0 && $structure[$lastIndex]['type'] === 'section') {
                $structure[$lastIndex]['items'][] = [
                    'type' => 'dropdown',
                    'title' => $item['title'],
                    'icon' => $item['icon'],
                    'id' => $item['id'],
                    'items' => $item['items']
                ];
            }
        }
    }
    
    return $structure;
}

/**
 * Render breadcrumb HTML
 */
function renderBreadcrumb($breadcrumb) {
    $html = '<nav aria-label="breadcrumb"><ol class="breadcrumb">';
    
    $count = count($breadcrumb);
    foreach ($breadcrumb as $index => $item) {
        $isLast = ($index === $count - 1);
        
        if ($isLast) {
            $html .= '<li class="breadcrumb-item active" aria-current="page">' . htmlspecialchars($item['title']) . '</li>';
        } else {
            $html .= '<li class="breadcrumb-item">';
            if (isset($item['url'])) {
                $html .= '<a href="' . htmlspecialchars($item['url']) . '">' . htmlspecialchars($item['title']) . '</a>';
            } else {
                $html .= htmlspecialchars($item['title']);
            }
            $html .= '</li>';
        }
    }
    
    $html .= '</ol></nav>';
    return $html;
}

/**
 * Get menu statistics
 */
function getMenuStatistics($menuConfig) {
    $stats = [
        'total_items' => 0,
        'links' => 0,
        'dropdowns' => 0,
        'sections' => 0,
        'dropdown_items' => 0
    ];
    
    foreach ($menuConfig as $item) {
        if ($item['type'] === 'header') {
            $stats['sections']++;
        } elseif ($item['type'] === 'link') {
            $stats['links']++;
            $stats['total_items']++;
        } elseif ($item['type'] === 'dropdown') {
            $stats['dropdowns']++;
            $stats['total_items']++;
            if (isset($item['items'])) {
                $stats['dropdown_items'] += count($item['items']);
                $stats['total_items'] += count($item['items']);
            }
        }
    }
    
    return $stats;
}

/**
 * Check if menu has specific item
 */
function menuHasItem($menuConfig, $url) {
    foreach ($menuConfig as $item) {
        if ($item['type'] === 'link' && $item['url'] === $url) {
            return true;
        } elseif ($item['type'] === 'dropdown' && isset($item['items'])) {
            foreach ($item['items'] as $subItem) {
                if ($subItem['url'] === $url) {
                    return true;
                }
            }
        }
    }
    return false;
}

/**
 * Get all menu URLs
 */
function getAllMenuUrls($menuConfig) {
    $urls = [];
    foreach ($menuConfig as $item) {
        if ($item['type'] === 'link') {
            $urls[] = $item['url'];
        } elseif ($item['type'] === 'dropdown' && isset($item['items'])) {
            foreach ($item['items'] as $subItem) {
                $urls[] = $subItem['url'];
            }
        }
    }
    return array_unique($urls);
}

/**
 * Generate sitemap from menu
 */
function generateSitemap($menuConfig, $baseUrl = '') {
    $urls = getAllMenuUrls($menuConfig);
    $sitemap = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    
    foreach ($urls as $url) {
        $sitemap .= '  <url>' . "\n";
        $sitemap .= '    <loc>' . htmlspecialchars($baseUrl . $url) . '</loc>' . "\n";
        $sitemap .= '    <changefreq>weekly</changefreq>' . "\n";
        $sitemap .= '    <priority>0.8</priority>' . "\n";
        $sitemap .= '  </url>' . "\n";
    }
    
    $sitemap .= '</urlset>';
    return $sitemap;
}

/**
 * Cache menu configuration
 */
function cacheMenuConfig($userRole, $menuConfig, $cacheDir = 'cache/') {
    if (!is_dir($cacheDir)) {
        mkdir($cacheDir, 0755, true);
    }
    
    $cacheFile = $cacheDir . 'menu_' . strtolower(str_replace(' ', '_', $userRole)) . '.json';
    $cacheData = [
        'cached_at' => date('Y-m-d H:i:s'),
        'menu' => $menuConfig
    ];
    
    return file_put_contents($cacheFile, json_encode($cacheData, JSON_PRETTY_PRINT));
}

/**
 * Load cached menu configuration
 */
function loadCachedMenuConfig($userRole, $cacheDir = 'cache/', $maxAge = 3600) {
    $cacheFile = $cacheDir . 'menu_' . strtolower(str_replace(' ', '_', $userRole)) . '.json';
    
    if (!file_exists($cacheFile)) {
        return null;
    }
    
    $fileAge = time() - filemtime($cacheFile);
    if ($fileAge > $maxAge) {
        return null;
    }
    
    $cacheData = json_decode(file_get_contents($cacheFile), true);
    return $cacheData['menu'] ?? null;
}

/**
 * Clear menu cache
 */
function clearMenuCache($cacheDir = 'cache/') {
    if (!is_dir($cacheDir)) {
        return true;
    }
    
    $files = glob($cacheDir . 'menu_*.json');
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file);
        }
    }
    
    return true;
}
?>