<?php
/**
 * Cargo Management System - Complete Menu Configuration
 * Professional freight and logistics navigation system
 * 
 * @author Cargo 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, rpp.page_name 
            FROM users u 
            INNER JOIN user_roles ur ON u.role_id = ur.role_id 
            LEFT JOIN role_page_permissions rpp ON u.role_id = rpp.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();
    
    $assignedPages = [];
    $userRole = 'guest';
    
    while ($row = $result->fetch_assoc()) {
        if ($userRole === 'guest') {
            $userRole = $row['role_name'];
        }
        if ($row['page_name']) {
            $assignedPages[] = $row['page_name'];
        }
    }
    
    return [
        'role' => $userRole,
        'pages' => $assignedPages
    ];
}

/**
 * Complete cargo 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'];
    }
    
    // Administrator gets everything
    if ($userRole === 'Administrator') {
        $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 cargo business
    $roleMenus = [
        'Customer Service' => [
            [
                'title' => 'Customer Management',
                'type' => 'header'
            ],
            [
                'title' => 'Customers',
                'icon' => 'bx-group',
                'type' => 'dropdown',
                'id' => 'customersMenu',
                'items' => [
                    ['title' => 'Add Customer', 'url' => 'add_customer.php'],
                    ['title' => 'Customer Search', 'url' => 'customer_search.php'],
                    ['title' => 'Customer List', 'url' => 'customers.php'],
                    ['title' => 'Customer Profile', 'url' => 'customer_profile.php']
                ]
            ],
            [
                'title' => 'Shipment Operations',
                'type' => 'header'
            ],
            [
                'title' => 'Shipments',
                'icon' => 'bx-package',
                'type' => 'dropdown',
                'id' => 'shipmentsMenu',
                'items' => [
                    ['title' => 'New Shipment', 'url' => 'create_shipment.php'],
                    ['title' => 'Track Shipment', 'url' => 'track_shipment.php'],
                    ['title' => 'Shipment List', 'url' => 'shipments.php'],
                    ['title' => 'Delivery Status', 'url' => 'delivery_status.php'],
                    ['title' => 'Rate Calculator', 'url' => 'rate_calculator.php']
                ]
            ],
            [
                'title' => 'Billing & Payments',
                'type' => 'header'
            ],
            [
                'title' => 'Invoicing',
                'icon' => 'bx-receipt',
                'type' => 'dropdown',
                'id' => 'invoicingMenu',
                'items' => [
                    ['title' => 'Generate Invoice', 'url' => 'generate_invoice.php'],
                    ['title' => 'Process Payment', 'url' => 'process_payment.php'],
                    ['title' => 'Payment History', 'url' => 'payment_history.php'],
                    ['title' => 'Credit Notes', 'url' => 'credit_notes.php']
                ]
            ]
        ],
        
        'Warehouse Staff' => [
            [
                'title' => 'Warehouse Operations',
                'type' => 'header'
            ],
            [
                'title' => 'Manifest Management',
                'icon' => 'bx-list-ul',
                'type' => 'dropdown',
                'id' => 'manifestsMenu',
                'items' => [
                    ['title' => 'Create Manifest', 'url' => 'create_manifest.php'],
                    ['title' => 'Pending Manifests', 'url' => 'pending_manifests.php'],
                    ['title' => 'Active Manifests', 'url' => 'active_manifests.php'],
                    ['title' => 'Manifest History', 'url' => 'manifests.php'],
                    ['title' => 'Manifest Reports', 'url' => 'manifest_reports.php']
                ]
            ],
            [
                'title' => 'Inventory Control',
                'icon' => 'bx-store',
                'type' => 'dropdown',
                'id' => 'inventoryMenu',
                'items' => [
                    ['title' => 'Stock Overview', 'url' => 'stock_overview.php'],
                    ['title' => 'Receive Goods', 'url' => 'receive_goods.php'],
                    ['title' => 'Dispatch Goods', 'url' => 'dispatch_goods.php'],
                    ['title' => 'Stock Movements', 'url' => 'stock_movements.php'],
                    ['title' => 'Warehouse Capacity', 'url' => 'warehouse_capacity.php']
                ]
            ],
            [
                'title' => 'Package Tracking',
                'icon' => 'bx-current-location',
                'type' => 'dropdown',
                'id' => 'trackingMenu',
                'items' => [
                    ['title' => 'Update Status', 'url' => 'update_shipment_status.php'],
                    ['title' => 'Scan Packages', 'url' => 'scan_packages.php'],
                    ['title' => 'Package Lookup', 'url' => 'package_lookup.php'],
                    ['title' => 'Damage Reports', 'url' => 'damage_reports.php']
                ]
            ]
        ],
        
        'Driver' => [
            [
                'title' => 'Delivery Operations',
                'type' => 'header'
            ],
            [
                'title' => 'My Deliveries',
                'icon' => 'bx-truck',
                'type' => 'dropdown',
                'id' => 'deliveriesMenu',
                'items' => [
                    ['title' => 'Today\'s Deliveries', 'url' => 'todays_deliveries.php'],
                    ['title' => 'Delivery Routes', 'url' => 'delivery_routes.php'],
                    ['title' => 'Completed Deliveries', 'url' => 'completed_deliveries.php'],
                    ['title' => 'Failed Deliveries', 'url' => 'failed_deliveries.php'],
                    ['title' => 'Delivery History', 'url' => 'delivery_history.php']
                ]
            ],
            [
                'title' => 'Proof of Delivery',
                'icon' => 'bx-check-circle',
                'type' => 'dropdown',
                'id' => 'podMenu',
                'items' => [
                    ['title' => 'Submit POD', 'url' => 'submit_pod.php'],
                    ['title' => 'POD Gallery', 'url' => 'pod_gallery.php'],
                    ['title' => 'Signature Capture', 'url' => 'signature_capture.php']
                ]
            ],
            [
                'title' => 'Vehicle Management',
                'icon' => 'bx-car',
                'type' => 'dropdown',
                'id' => 'vehicleMenu',
                'items' => [
                    ['title' => 'Vehicle Status', 'url' => 'vehicle_status.php'],
                    ['title' => 'Fuel Log', 'url' => 'fuel_log.php'],
                    ['title' => 'Maintenance Log', 'url' => 'maintenance_log.php'],
                    ['title' => 'Vehicle Inspection', 'url' => 'vehicle_inspection.php']
                ]
            ]
        ],
        
        'Operations Manager' => [
            [
                'title' => 'Fleet Management',
                'type' => 'header'
            ],
            [
                'title' => 'Vehicle Fleet',
                'icon' => 'bx-car',
                'type' => 'dropdown',
                'id' => 'fleetMenu',
                'items' => [
                    ['title' => 'Vehicle List', 'url' => 'vehicles.php'],
                    ['title' => 'Add Vehicle', 'url' => 'add_vehicle.php'],
                    ['title' => 'Vehicle Assignments', 'url' => 'vehicle_assignments.php'],
                    ['title' => 'Fleet Performance', 'url' => 'fleet_performance.php'],
                    ['title' => 'Maintenance Schedule', 'url' => 'maintenance_schedule.php']
                ]
            ],
            [
                'title' => 'Driver Management',
                'icon' => 'bx-group',
                'type' => 'dropdown',
                'id' => 'driversMenu',
                'items' => [
                    ['title' => 'Driver List', 'url' => 'drivers.php'],
                    ['title' => 'Add Driver', 'url' => 'add_driver.php'],
                    ['title' => 'Driver Performance', 'url' => 'driver_performance.php'],
                    ['title' => 'License Management', 'url' => 'license_management.php'],
                    ['title' => 'Driver Schedules', 'url' => 'driver_schedules.php']
                ]
            ],
            [
                'title' => 'Route & Logistics',
                'type' => 'header'
            ],
            [
                'title' => 'Route Planning',
                'icon' => 'bx-map',
                'type' => 'dropdown',
                'id' => 'routesMenu',
                'items' => [
                    ['title' => 'Route Management', 'url' => 'routes.php'],
                    ['title' => 'Route Optimization', 'url' => 'route_optimization.php'],
                    ['title' => 'Scheduled Runs', 'url' => 'scheduled_runs.php'],
                    ['title' => 'Route Performance', 'url' => 'route_performance.php']
                ]
            ],
            [
                'title' => 'Warehouse Operations',
                'icon' => 'bx-buildings',
                'type' => 'dropdown',
                'id' => 'warehousesMenu',
                'items' => [
                    ['title' => 'Warehouse List', 'url' => 'warehouses.php'],
                    ['title' => 'Capacity Planning', 'url' => 'capacity_planning.php'],
                    ['title' => 'Manifest Control', 'url' => 'manifest_control.php'],
                    ['title' => 'Warehouse Reports', 'url' => 'warehouse_reports.php']
                ]
            ],
            [
                'title' => 'Service Management',
                'icon' => 'bx-cog',
                'type' => 'dropdown',
                'id' => 'servicesMenu',
                'items' => [
                    ['title' => 'Service Types', 'url' => 'service_types.php'],
                    ['title' => 'Rate Management', 'url' => 'rate_management.php'],
                    ['title' => 'Location Management', 'url' => 'locations.php'],
                    ['title' => 'Zone Management', 'url' => 'zones.php']
                ]
            ],
            [
                'title' => 'Analytics & Reports',
                'type' => 'header'
            ],
            [
                'title' => 'Operations Analytics',
                'icon' => 'bx-bar-chart',
                'type' => 'dropdown',
                'id' => 'analyticsMenu',
                'items' => [
                    ['title' => 'Operations Dashboard', 'url' => 'operations_dashboard.php'],
                    ['title' => 'Performance Metrics', 'url' => 'performance_metrics.php'],
                    ['title' => 'Route Analysis', 'url' => 'route_analysis.php'],
                    ['title' => 'Efficiency Reports', 'url' => 'efficiency_reports.php']
                ]
            ]
        ],
        
        'Finance Manager' => [
            [
                'title' => 'Financial Overview',
                'type' => 'header'
            ],
            [
                'title' => 'Revenue Management',
                'icon' => 'bx-trending-up',
                'type' => 'dropdown',
                'id' => 'revenueMenu',
                'items' => [
                    ['title' => 'Revenue Dashboard', 'url' => 'revenue_dashboard.php'],
                    ['title' => 'Daily Revenue', 'url' => 'daily_revenue.php'],
                    ['title' => 'Monthly Reports', 'url' => 'monthly_reports.php'],
                    ['title' => 'Profit Analysis', 'url' => 'profit_analysis.php'],
                    ['title' => 'Revenue Forecasting', 'url' => 'revenue_forecasting.php']
                ]
            ],
            [
                'title' => 'Invoice Management',
                'icon' => 'bx-receipt',
                'type' => 'dropdown',
                'id' => 'invoiceManagementMenu',
                'items' => [
                    ['title' => 'All Invoices', 'url' => 'invoices.php'],
                    ['title' => 'Generate Invoice', 'url' => 'generate_invoice.php'],
                    ['title' => 'Outstanding Invoices', 'url' => 'outstanding_invoices.php'],
                    ['title' => 'Invoice Templates', 'url' => 'invoice_templates.php'],
                    ['title' => 'Recurring Invoices', 'url' => 'recurring_invoices.php']
                ]
            ],
            [
                'title' => 'Payment Processing',
                'icon' => 'bx-money',
                'type' => 'dropdown',
                'id' => 'paymentsMenu',
                'items' => [
                    ['title' => 'Payment Dashboard', 'url' => 'payment_dashboard.php'],
                    ['title' => 'Process Payments', 'url' => 'process_payments.php'],
                    ['title' => 'Payment History', 'url' => 'payment_history.php'],
                    ['title' => 'Payment Methods', 'url' => 'payment_methods.php'],
                    ['title' => 'Bank Reconciliation', 'url' => 'bank_reconciliation.php']
                ]
            ],
            [
                'title' => 'Financial Reports',
                'icon' => 'bx-chart-line',
                'type' => 'dropdown',
                'id' => 'financialReportsMenu',
                'items' => [
                    ['title' => 'P&L Statement', 'url' => 'profit_loss.php'],
                    ['title' => 'Cash Flow', 'url' => 'cash_flow.php'],
                    ['title' => 'Accounts Receivable', 'url' => 'accounts_receivable.php'],
                    ['title' => 'Tax Reports', 'url' => 'tax_reports.php']
                ]
            ]
        ],
        
        'Customs Officer' => [
            [
                'title' => 'Customs Operations',
                'type' => 'header'
            ],
            [
                'title' => 'Declaration Management',
                'icon' => 'bx-file-blank',
                'type' => 'dropdown',
                'id' => 'declarationsMenu',
                'items' => [
                    ['title' => 'Pending Declarations', 'url' => 'pending_declarations.php'],
                    ['title' => 'Process Declaration', 'url' => 'process_declaration.php'],
                    ['title' => 'Declaration History', 'url' => 'declarations.php'],
                    ['title' => 'Customs Clearance', 'url' => 'customs_clearance.php'],
                    ['title' => 'Declaration Reports', 'url' => 'declaration_reports.php']
                ]
            ],
            [
                'title' => 'Commodity Management',
                'icon' => 'bx-package',
                'type' => 'dropdown',
                'id' => 'commoditiesMenu',
                'items' => [
                    ['title' => 'Commodity List', 'url' => 'commodities.php'],
                    ['title' => 'HS Code Search', 'url' => 'hs_code_search.php'],
                    ['title' => 'Restricted Items', 'url' => 'restricted_items.php'],
                    ['title' => 'Duty Calculator', 'url' => 'duty_calculator.php'],
                    ['title' => 'Tariff Management', 'url' => 'tariff_management.php']
                ]
            ],
            [
                'title' => 'International Trade',
                'icon' => 'bx-world',
                'type' => 'dropdown',
                'id' => 'tradeMenu',
                'items' => [
                    ['title' => 'Trade Agreements', 'url' => 'trade_agreements.php'],
                    ['title' => 'Certificate of Origin', 'url' => 'certificate_origin.php'],
                    ['title' => 'Export Documentation', 'url' => 'export_documentation.php']
                ]
            ]
        ],
        
        'Administrator' => [
            [
                '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' => 'Customer Management',
                'type' => 'header'
            ],
            [
                'title' => 'Customer Administration',
                'icon' => 'bx-user-circle',
                'type' => 'dropdown',
                'id' => 'customerAdminMenu',
                'items' => [
                    ['title' => 'All Customers', 'url' => 'customers.php'],
                    ['title' => 'Add Customer', 'url' => 'add_customer.php'],
                    ['title' => 'Customer Analytics', 'url' => 'customer_analytics.php'],
                    ['title' => 'Credit Management', 'url' => 'credit_management.php'],
                    ['title' => 'Customer Segments', 'url' => 'customer_segments.php']
                ]
            ],
            [
                'title' => 'Cargo Operations',
                'type' => 'header'
            ],
            [
                'title' => 'Shipment Management',
                'icon' => 'bx-package',
                'type' => 'dropdown',
                'id' => 'shipmentAdminMenu',
                'items' => [
                    ['title' => 'All Shipments', 'url' => 'shipments.php'],
                    ['title' => 'Create Shipment', 'url' => 'create_shipment.php'],
                    ['title' => 'Shipment Analytics', 'url' => 'shipment_analytics.php'],
                    ['title' => 'Service Configuration', 'url' => 'service_types.php'],
                    ['title' => 'Rate Card Management', 'url' => 'rate_cards.php'],
                    ['title' => 'Bulk Operations', 'url' => 'bulk_operations.php']
                ]
            ],
            [
                'title' => 'Fleet & Logistics',
                'icon' => 'bx-truck',
                'type' => 'dropdown',
                'id' => 'fleetAdminMenu',
                'items' => [
                    ['title' => 'Vehicle Management', 'url' => 'vehicles.php'],
                    ['title' => 'Driver Management', 'url' => 'drivers.php'],
                    ['title' => 'Route Management', 'url' => 'routes.php'],
                    ['title' => 'Warehouse Management', 'url' => 'warehouses.php'],
                    ['title' => 'Fleet Analytics', 'url' => 'fleet_analytics.php']
                ]
            ],
            [
                'title' => 'International Operations',
                'icon' => 'bx-world',
                'type' => 'dropdown',
                'id' => 'internationalMenu',
                'items' => [
                    ['title' => 'Customs Management', 'url' => 'customs_declarations.php'],
                    ['title' => 'Commodity Database', 'url' => 'commodities.php'],
                    ['title' => 'Countries & Zones', 'url' => 'countries_zones.php'],
                    ['title' => 'Location Network', 'url' => 'locations.php'],
                    ['title' => 'Trade Compliance', 'url' => 'trade_compliance.php']
                ]
            ],
            [
                'title' => 'Financial Administration',
                'type' => 'header'
            ],
            [
                'title' => 'Financial Management',
                'icon' => 'bx-trending-up',
                'type' => 'dropdown',
                'id' => 'financeAdminMenu',
                'items' => [
                    ['title' => 'Revenue Dashboard', 'url' => 'revenue_dashboard.php'],
                    ['title' => 'Invoice Management', 'url' => 'invoices.php'],
                    ['title' => 'Payment Processing', 'url' => 'payments.php'],
                    ['title' => 'Financial Reports', 'url' => 'financial_reports.php'],
                    ['title' => 'Charge Configuration', 'url' => 'charge_types.php'],
                    ['title' => 'Tax Settings', 'url' => 'tax_settings.php']
                ]
            ],
            [
                'title' => 'System Administration',
                'type' => 'header'
            ],
            [
                'title' => 'System Settings',
                'icon' => 'bx-cog',
                'type' => 'dropdown',
                'id' => 'systemMenu',
                'items' => [
                    ['title' => 'General Settings', 'url' => 'system_settings.php'],
                    ['title' => 'Company Profile', 'url' => 'company_settings.php'],
                    ['title' => 'Email Configuration', 'url' => 'email_settings.php'],
                    ['title' => 'Security Settings', 'url' => 'security_settings.php'],
                    ['title' => 'API Management', 'url' => 'api_management.php']
                ]
            ],
            [
                'title' => 'Monitoring & Logs',
                'icon' => 'bx-data',
                'type' => 'dropdown',
                'id' => 'monitoringMenu',
                'items' => [
                    ['title' => 'System Health', 'url' => 'system_health.php'],
                    ['title' => 'Activity Logs', 'url' => 'activity_logs.php'],
                    ['title' => 'Error Logs', 'url' => 'error_logs.php'],
                    ['title' => 'Performance Monitor', 'url' => 'performance_monitor.php'],
                    ['title' => 'Backup & Restore', 'url' => 'backup_restore.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' => '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;
    
    if (isset($roleMenus[$userRole])) {
        $menu = array_merge($menu, $roleMenus[$userRole]);
    }
    
    $menu = array_merge($menu, $accountMenu);
    
    // Apply access control filtering
    if ($userRole !== 'Administrator' && !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',
        'help_support.php'
    ];
    
    foreach ($menu as $item) {
        if ($item['type'] === 'header') {
            // Process previous section
            if ($currentSection !== null && !empty($sectionItems)) {
                $filteredMenu[] = $currentSection;
                $filteredMenu = array_merge($filteredMenu, $sectionItems);
            }
            
            // Start new section
            $currentSection = $item;
            $sectionItems = [];
            
        } elseif ($item['type'] === 'link') {
            // Include core system links or assigned pages
            if (in_array($item['url'], $alwaysAllowed) || in_array($item['url'], $assignedPages)) {
                $sectionItems[] = $item;
            }
            
        } elseif ($item['type'] === 'dropdown') {
            // Filter dropdown items
            $filteredItems = [];
            
            foreach ($item['items'] as $subItem) {
                if (in_array($subItem['url'], $assignedPages) || in_array($subItem['url'], $alwaysAllowed)) {
                    $filteredItems[] = $subItem;
                }
            }
            
            // Only include dropdown if it has accessible items
            if (!empty($filteredItems)) {
                $item['items'] = $filteredItems;
                $sectionItems[] = $item;
            }
        }
    }
    
    // Process last section
    if ($currentSection !== null && !empty($sectionItems)) {
        $filteredMenu[] = $currentSection;
        $filteredMenu = array_merge($filteredMenu, $sectionItems);
    }
    
    return $filteredMenu;
}

/**
 * Get cargo-specific notifications count
 */
function getNotificationCount($conn, $userId) {
    $notifications = [
        'shipments' => 0,
        'manifests' => 0,
        'payments' => 0,
        'customs' => 0,
        'deliveries' => 0,
        'maintenance' => 0
    ];
    
    if (!$conn || !$userId) {
        return $notifications;
    }
    
    try {
        // Pending shipments (last 24 hours)
        $pending_shipments_sql = "SELECT COUNT(*) as count FROM shipments 
                                 WHERE status IN ('BOOKED', 'COLLECTED') 
                                 AND booking_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR)";
        $result = $conn->query($pending_shipments_sql);
        if ($result) {
            $notifications['shipments'] = $result->fetch_assoc()['count'];
        }
        
        // Pending manifests
        $pending_manifests_sql = "SELECT COUNT(*) as count FROM manifests 
                                 WHERE status IN ('DRAFT', 'CONFIRMED') 
                                 AND departure_date <= DATE_ADD(NOW(), INTERVAL 2 HOUR)";
        $result = $conn->query($pending_manifests_sql);
        if ($result) {
            $notifications['manifests'] = $result->fetch_assoc()['count'];
        }
        
        // Overdue payments
        $overdue_payments_sql = "SELECT COUNT(*) as count FROM invoices 
                               WHERE status IN ('SENT', 'OVERDUE') 
                               AND due_date < CURDATE()";
        $result = $conn->query($overdue_payments_sql);
        if ($result) {
            $notifications['payments'] = $result->fetch_assoc()['count'];
        }
        
        // Pending customs declarations
        $pending_customs_sql = "SELECT COUNT(*) as count FROM customs_declarations 
                              WHERE status = 'PENDING'";
        $result = $conn->query($pending_customs_sql);
        if ($result) {
            $notifications['customs'] = $result->fetch_assoc()['count'];
        }
        
        // Active deliveries
        $active_deliveries_sql = "SELECT COUNT(*) as count FROM shipments 
                                WHERE status = 'OUT_FOR_DELIVERY'";
        $result = $conn->query($active_deliveries_sql);
        if ($result) {
            $notifications['deliveries'] = $result->fetch_assoc()['count'];
        }
        
        // Overdue maintenance
        $overdue_maintenance_sql = "SELECT COUNT(*) as count FROM vehicles 
                                  WHERE status = 'MAINTENANCE' 
                                  OR license_expiry < DATE_ADD(CURDATE(), INTERVAL 30 DAY)
                                  OR insurance_expiry < DATE_ADD(CURDATE(), INTERVAL 30 DAY)";
        $result = $conn->query($overdue_maintenance_sql);
        if ($result) {
            $notifications['maintenance'] = $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);
    
    // Add notification badges to relevant menu items
    foreach ($menuConfig as &$item) {
        if ($item['type'] === 'dropdown') {
            switch ($item['id']) {
                case 'shipmentsMenu':
                case 'shipmentAdminMenu':
                    if ($notifications['shipments'] > 0) {
                        $item['badge'] = $notifications['shipments'];
                        $item['badge_class'] = 'bg-warning';
                    }
                    break;
                    
                case 'manifestsMenu':
                    if ($notifications['manifests'] > 0) {
                        $item['badge'] = $notifications['manifests'];
                        $item['badge_class'] = 'bg-info';
                    }
                    break;
                    
                case 'paymentsMenu':
                case 'invoicingMenu':
                case 'financeAdminMenu':
                    if ($notifications['payments'] > 0) {
                        $item['badge'] = $notifications['payments'];
                        $item['badge_class'] = 'bg-danger';
                    }
                    break;
                    
                case 'declarationsMenu':
                    if ($notifications['customs'] > 0) {
                        $item['badge'] = $notifications['customs'];
                        $item['badge_class'] = 'bg-primary';
                    }
                    break;
                    
                case 'deliveriesMenu':
                    if ($notifications['deliveries'] > 0) {
                        $item['badge'] = $notifications['deliveries'];
                        $item['badge_class'] = 'bg-success';
                    }
                    break;
                    
                case 'fleetMenu':
                case 'fleetAdminMenu':
                case 'vehicleMenu':
                    if ($notifications['maintenance'] > 0) {
                        $item['badge'] = $notifications['maintenance'];
                        $item['badge_class'] = 'bg-secondary';
                    }
                    break;
            }
        }
    }
    
    return $menuConfig;
}

/**
 * Main menu rendering function
 */
function renderMenu($userRole, $userId = null, $conn = null, $debug = false) {
    
    // Get assigned pages from database if connection provided
    $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>';
            $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>';
            $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>';
            $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>';
            
            // Add notification badge if exists
            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 based on user role
 */
function getQuickActions($userRole, $assignedPages = []) {
    $allQuickActions = [
        'Administrator' => [
            ['title' => 'Create Shipment', 'url' => 'create_shipment.php', 'icon' => 'bx-package', 'color' => 'primary'],
            ['title' => 'Add Customer', 'url' => 'add_customer.php', 'icon' => 'bx-user-plus', 'color' => 'success'],
            ['title' => 'Revenue Dashboard', 'url' => 'revenue_dashboard.php', 'icon' => 'bx-trending-up', 'color' => 'info'],
            ['title' => 'Fleet Management', 'url' => 'vehicles.php', 'icon' => 'bx-car', 'color' => 'warning'],
            ['title' => 'System Health', 'url' => 'system_health.php', 'icon' => 'bx-pulse', 'color' => 'danger'],
            ['title' => 'User Management', 'url' => 'users.php', 'icon' => 'bx-group', 'color' => 'secondary']
        ],
        'Operations Manager' => [
            ['title' => 'All Shipments', 'url' => 'shipments.php', 'icon' => 'bx-package', 'color' => 'primary'],
            ['title' => 'Route Planning', 'url' => 'route_optimization.php', 'icon' => 'bx-map', 'color' => 'success'],
            ['title' => 'Fleet Status', 'url' => 'vehicles.php', 'icon' => 'bx-car', 'color' => 'info'],
            ['title' => 'Performance Metrics', 'url' => 'performance_metrics.php', 'icon' => 'bx-bar-chart', 'color' => 'warning'],
            ['title' => 'Driver Management', 'url' => 'drivers.php', 'icon' => 'bx-group', 'color' => 'danger'],
            ['title' => 'Warehouse Control', 'url' => 'warehouses.php', 'icon' => 'bx-buildings', 'color' => 'secondary']
        ],
        'Customer Service' => [
            ['title' => 'New Shipment', 'url' => 'create_shipment.php', 'icon' => 'bx-package', 'color' => 'primary'],
            ['title' => 'Track Shipment', 'url' => 'track_shipment.php', 'icon' => 'bx-search-alt', 'color' => 'success'],
            ['title' => 'Customer Search', 'url' => 'customer_search.php', 'icon' => 'bx-search', 'color' => 'info'],
            ['title' => 'Generate Invoice', 'url' => 'generate_invoice.php', 'icon' => 'bx-receipt', 'color' => 'warning'],
            ['title' => 'Add Customer', 'url' => 'add_customer.php', 'icon' => 'bx-user-plus', 'color' => 'danger'],
            ['title' => 'Rate Calculator', 'url' => 'rate_calculator.php', 'icon' => 'bx-calculator', 'color' => 'secondary']
        ],
        'Warehouse Staff' => [
            ['title' => 'Create Manifest', 'url' => 'create_manifest.php', 'icon' => 'bx-list-ul', 'color' => 'primary'],
            ['title' => 'Update Status', 'url' => 'update_shipment_status.php', 'icon' => 'bx-refresh', 'color' => 'success'],
            ['title' => 'Receive Goods', 'url' => 'receive_goods.php', 'icon' => 'bx-down-arrow-circle', 'color' => 'info'],
            ['title' => 'Dispatch Goods', 'url' => 'dispatch_goods.php', 'icon' => 'bx-up-arrow-circle', 'color' => 'warning'],
            ['title' => 'Scan Packages', 'url' => 'scan_packages.php', 'icon' => 'bx-qr-scan', 'color' => 'danger'],
            ['title' => 'Stock Overview', 'url' => 'stock_overview.php', 'icon' => 'bx-store', 'color' => 'secondary']
        ],
        'Driver' => [
            ['title' => 'My Deliveries', 'url' => 'todays_deliveries.php', 'icon' => 'bx-truck', 'color' => 'primary'],
            ['title' => 'Delivery Routes', 'url' => 'delivery_routes.php', 'icon' => 'bx-map', 'color' => 'success'],
            ['title' => 'Proof of Delivery', 'url' => 'submit_pod.php', 'icon' => 'bx-check-circle', 'color' => 'info'],
            ['title' => 'Vehicle Status', 'url' => 'vehicle_status.php', 'icon' => 'bx-car', 'color' => 'warning'],
            ['title' => 'Fuel Log', 'url' => 'fuel_log.php', 'icon' => 'bx-gas-pump', 'color' => 'danger'],
            ['title' => 'Signature Capture', 'url' => 'signature_capture.php', 'icon' => 'bx-edit', 'color' => 'secondary']
        ],
        'Finance Manager' => [
            ['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 Payments', 'url' => 'process_payments.php', 'icon' => 'bx-money', 'color' => 'info'],
            ['title' => 'Financial Reports', 'url' => 'profit_loss.php', 'icon' => 'bx-chart-line', 'color' => 'warning'],
            ['title' => 'Outstanding Invoices', 'url' => 'outstanding_invoices.php', 'icon' => 'bx-time', 'color' => 'danger'],
            ['title' => 'Bank Reconciliation', 'url' => 'bank_reconciliation.php', 'icon' => 'bx-credit-card', 'color' => 'secondary']
        ],
        'Customs Officer' => [
            ['title' => 'Pending Declarations', 'url' => 'pending_declarations.php', 'icon' => 'bx-file-blank', 'color' => 'primary'],
            ['title' => 'Process Declaration', 'url' => 'process_declaration.php', 'icon' => 'bx-check-square', 'color' => 'success'],
            ['title' => 'HS Code Search', 'url' => 'hs_code_search.php', 'icon' => 'bx-search', 'color' => 'info'],
            ['title' => 'Restricted Items', 'url' => 'restricted_items.php', 'icon' => 'bx-block', 'color' => 'warning'],
            ['title' => 'Duty Calculator', 'url' => 'duty_calculator.php', 'icon' => 'bx-calculator', 'color' => 'danger'],
            ['title' => 'Customs Clearance', 'url' => 'customs_clearance.php', 'icon' => 'bx-check-shield', 'color' => 'secondary']
        ]
    ];
    
    $roleActions = $allQuickActions[$userRole] ?? [];
    
    // Filter quick actions based on assigned pages (unless Administrator)
    if ($userRole !== 'Administrator' && !empty($assignedPages) && !in_array('*', $assignedPages)) {
        $roleActions = array_filter($roleActions, function($action) use ($assignedPages) {
            return in_array($action['url'], $assignedPages);
        });
    }
    
    return $roleActions;
}

/**
 * Get cargo-specific statistics for dashboard widgets
 */
function getDashboardStats($conn, $userId, $userRole) {
    $stats = [
        'shipments_today' => 0,
        'pending_deliveries' => 0,
        'revenue_today' => 0,
        'active_vehicles' => 0,
        'customs_pending' => 0,
        'manifests_pending' => 0,
        'customers_active' => 0,
        'drivers_active' => 0
    ];
    
    if (!$conn) {
        return $stats;
    }
    
    try {
        // Shipments created today
        $shipments_today_sql = "SELECT COUNT(*) as count FROM shipments 
                               WHERE DATE(booking_date) = CURDATE()";
        $result = $conn->query($shipments_today_sql);
        if ($result) {
            $stats['shipments_today'] = $result->fetch_assoc()['count'];
        }
        
        // Pending deliveries
        $pending_deliveries_sql = "SELECT COUNT(*) as count FROM shipments 
                                  WHERE status IN ('BOOKED', 'COLLECTED', 'IN_TRANSIT', 'OUT_FOR_DELIVERY')";
        $result = $conn->query($pending_deliveries_sql);
        if ($result) {
            $stats['pending_deliveries'] = $result->fetch_assoc()['count'];
        }
        
        // Revenue today
        $revenue_today_sql = "SELECT COALESCE(SUM(total_charges), 0) as total FROM shipments 
                             WHERE DATE(booking_date) = CURDATE() AND payment_status = 'PAID'";
        $result = $conn->query($revenue_today_sql);
        if ($result) {
            $stats['revenue_today'] = $result->fetch_assoc()['total'];
        }
        
        // Active vehicles
        $active_vehicles_sql = "SELECT COUNT(*) as count FROM vehicles WHERE status = 'ACTIVE'";
        $result = $conn->query($active_vehicles_sql);
        if ($result) {
            $stats['active_vehicles'] = $result->fetch_assoc()['count'];
        }
        
        // Pending customs declarations
        $customs_pending_sql = "SELECT COUNT(*) as count FROM customs_declarations WHERE status = 'PENDING'";
        $result = $conn->query($customs_pending_sql);
        if ($result) {
            $stats['customs_pending'] = $result->fetch_assoc()['count'];
        }
        
        // Pending manifests
        $manifests_pending_sql = "SELECT COUNT(*) as count FROM manifests 
                                 WHERE status IN ('DRAFT', 'CONFIRMED')";
        $result = $conn->query($manifests_pending_sql);
        if ($result) {
            $stats['manifests_pending'] = $result->fetch_assoc()['count'];
        }
        
        // Active customers
        $customers_active_sql = "SELECT COUNT(*) as count FROM customers WHERE status = 'ACTIVE'";
        $result = $conn->query($customers_active_sql);
        if ($result) {
            $stats['customers_active'] = $result->fetch_assoc()['count'];
        }
        
        // Active drivers
        $drivers_active_sql = "SELECT COUNT(*) as count FROM drivers WHERE status = 'ACTIVE'";
        $result = $conn->query($drivers_active_sql);
        if ($result) {
            $stats['drivers_active'] = $result->fetch_assoc()['count'];
        }
        
    } catch (Exception $e) {
        error_log("Error getting dashboard stats: " . $e->getMessage());
    }
    
    return $stats;
}

/**
 * Get breadcrumb navigation for current page
 */
function getBreadcrumb($currentPage, $menuConfig = null) {
    if (!$menuConfig) {
        return [['title' => 'Dashboard', 'url' => 'index.php']];
    }
    
    $breadcrumb = [
        ['title' => 'Dashboard', 'url' => 'index.php']
    ];
    
    // Search through menu to find current page
    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 {
        // Get user role
        $role_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($role_sql);
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            return false;
        }
        
        $user = $result->fetch_assoc();
        
        // Administrator has access to everything
        if ($user['role_name'] === 'Administrator') {
            return true;
        }
        
        // Check if page is in allowed pages for this role
        $userData = getUserAssignedPages($conn, $userId);
        $assignedPages = $userData['pages'];
        
        // Always allowed pages
        $alwaysAllowed = ['index.php', 'profile.php', 'change_password.php', 'logout.php', 'notifications.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 for display
 */
function formatCurrency($amount, $currency = 'KES') {
    $symbol = match($currency) {
        'KES' => 'KSh ',
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£',
        'UGX' => 'USh ',
        'TZS' => 'TSh ',
        'RWF' => 'RF ',
        default => $currency . ' '
    };
    
    return $symbol . number_format($amount, 2);
}

/**
 * Get system health status
 */
function getSystemHealth($conn) {
    $health = [
        'database' => 'healthy',
        'shipments' => 'healthy',
        'payments' => 'healthy',
        'fleet' => 'healthy',
        'overall' => 'healthy'
    ];
    
    if (!$conn) {
        $health['database'] = 'error';
        $health['overall'] = 'error';
        return $health;
    }
    
    try {
        // Check recent shipment activity
        $recent_shipments_sql = "SELECT COUNT(*) as count FROM shipments 
                                WHERE booking_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR)";
        $result = $conn->query($recent_shipments_sql);
        if ($result) {
            $recent_count = $result->fetch_assoc()['count'];
            if ($recent_count == 0) {
                $health['shipments'] = 'warning';
            }
        }
        
        // Check overdue payments
        $overdue_sql = "SELECT COUNT(*) as count FROM invoices 
                       WHERE due_date < DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
                       AND status != 'PAID'";
        $result = $conn->query($overdue_sql);
        if ($result) {
            $overdue_count = $result->fetch_assoc()['count'];
            if ($overdue_count > 5) {
                $health['payments'] = 'warning';
            }
        }
        
        // Check vehicle maintenance
        $maintenance_sql = "SELECT COUNT(*) as count FROM vehicles 
                           WHERE status = 'MAINTENANCE' 
                           OR license_expiry < DATE_ADD(CURDATE(), INTERVAL 30 DAY)
                           OR insurance_expiry < DATE_ADD(CURDATE(), INTERVAL 30 DAY)";
        $result = $conn->query($maintenance_sql);
        if ($result) {
            $maintenance_count = $result->fetch_assoc()['count'];
            if ($maintenance_count > 0) {
                $health['fleet'] = 'warning';
            }
        }
        
        // Determine overall health
        $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 for audit purposes
 */
function logMenuAccess($conn, $userId, $menuItem, $ipAddress = null) {
    if (!$conn || !$userId) {
        return false;
    }
    
    try {
        $ip = $ipAddress ?: ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
        
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values, ip_address, logged_at) 
                   VALUES (?, 'ACCESS', 'menu', ?, ?, ?, NOW())";
        
        $stmt = $conn->prepare($log_sql);
        $details = json_encode(['menu_item' => $menuItem, 'timestamp' => date('Y-m-d H:i:s')]);
        $stmt->bind_param("isss", $userId, $menuItem, $details, $ip);
        
        return $stmt->execute();
        
    } catch (Exception $e) {
        error_log("Error logging menu access: " . $e->getMessage());
        return false;
    }
}
?>