<?php
/**
 * REVENDA - Complete Hotel Booking & PMS Platform
 * Main Router
 * @version 12.9.4
 *
 * CHANGELOG
 *  12.9.4 - Route-level module attribution (Phase B1)
 *         - Added 'module' => '<slug>' to every vendor/user route that
 *           belongs to a platform module. After this deploy, the module
 *           audit will show ~25 modules moving from BUILD to GATE. Once
 *           each page's vendorHasModule guard is added (Phase B2), they
 *           move from GATE to READY.
 *         - No route files renamed, added, or removed. No guard changes.
 *  12.9.3 - Module access enforcement
 *         - Added vendor-tour-guest-experience route (module: tour_guest_experience)
 *         - Added router-level module access check (block 6)
 *  12.9.2 - Route cleanup + missing user event routes
 *  12.9.1 - F&B module wiring (surgical, non-breaking)
 *  12.9.0 - MICE vendor ops + commission tracking
 *  12.8.0 - Planner identity system
 *  12.7.0 - MICE venue onboarding landing
 *  12.6.0 - MICE module fully wired (all dashboards)
 *  12.5.0 - MICE module public layer wired
 *  12.4.0 - CTO onboarding + curation pages registered
 *  12.3.0 - Tour Operators module fully wired (HOS extension)
 *  12.2.0 - Registered api-payment-webhook
 *  12.1.0 - Property claims system wired
 *  12.0.2 - Restored header.php / footer.php wrapping around every HTML page
 *  12.0.1 - Removed duplicate AIRecommender.php module (fatal: class already in ai.php)
 */

// ============================================
// ENVIRONMENT
// ============================================
define('ENVIRONMENT', 'production');
define('APP_VERSION', '12.9.4');
define('APP_START', microtime(true));

// ============================================
// ERROR HANDLING
// ============================================
if (ENVIRONMENT === 'development') {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
} else {
    error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING);
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    if (!is_dir(__DIR__ . '/logs')) @mkdir(__DIR__ . '/logs', 0755, true);
    ini_set('error_log', __DIR__ . '/logs/php-errors.log');
}

// ============================================
// OUTPUT BUFFERING
// ============================================
ob_start();

// ============================================
// ENVIRONMENT SETUP
// ============================================
date_default_timezone_set('UTC');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');

// ============================================
// CORE BOOTSTRAP
// ============================================
$basePath = __DIR__;

foreach (['config.php', 'database.php', 'functions.php'] as $f) {
    $path = $basePath . '/' . $f;
    if (!file_exists($path)) {
        http_response_code(500);
        exit("Critical file missing: $f");
    }
    require_once $path;
}

// ============================================
// SESSION
// ============================================
if (session_status() === PHP_SESSION_NONE) {
    $secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
    if (PHP_VERSION_ID >= 70300) {
        session_set_cookie_params([
            'lifetime' => 86400 * 30,
            'path'     => '/',
            'secure'   => $secure,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
    } else {
        session_set_cookie_params(86400 * 30, '/', '', $secure, true);
    }
    session_name('REVENDA_SESSION');
    session_start();
}

// ============================================
// LOAD MODULES (priority order)
// ============================================
$priorityModules = [
    'includes/security.php',
    'includes/rbac.php',
    'includes/frontdesk.php',
    'includes/laundry.php',
    'includes/i18n.php',
    'includes/seo.php',
    'includes/mailer.php',
    'includes/payments.php',
    'includes/payments_extended.php',
    'includes/smart_pricing.php',
    'includes/channel_manager.php',
    'includes/loyalty.php',
    'includes/ai.php',
    'includes/ai_concierge.php',
    'includes/trip_planner.php',
    'includes/destination_matcher.php',
    'includes/push.php',
    'includes/webrtc.php',
    'includes/blockchain.php',
    'includes/iot.php',
    'includes/robot_concierge.php',
    'includes/carbon.php',
    'includes/insurance.php',
    'includes/tenant.php',
    'includes/themes.php',
    'includes/gamification.php',
    'includes/support.php',
    'includes/PdfGenerator.php',
    'includes/ReportEngine.php',
    'includes/ForecastEngine.php',
    'includes/voice-concierge.php',
    'includes/admin_channels.php',
    'includes/admin_settlements.php',
    'includes/brand-images.php',
    'includes/property-images.php',
    'includes/image-helpers.php',
    'includes/analytics_helpers.php',
    'includes/tax_engine.php',
    'includes/tour_operators.php',
    'includes/mice_helpers.php',
    'includes/planner_helpers.php',
    'includes/event_helpers.php',
    'includes/event_waitlist.php',
    'includes/event_mailer.php',
    'includes/menu_templates.php',
    'includes/boot_helpers.php',
    'includes/business_type_helpers.php',
    'includes/dashboard_router.php',
    'includes/ride_receipt_helper.php',
];

$loadedModules = [];
foreach ($priorityModules as $module) {
    $path = $basePath . '/' . $module;
    if (!file_exists($path)) {
        error_log("Module missing (skipped): $module");
        continue;
    }
    if (in_array($module, $loadedModules, true)) {
        continue;
    }
    $loadedModules[] = $module;

    try {
        require_once $path;
    } catch (Throwable $e) {
        error_log("Module load failed: $module - " . $e->getMessage()
                  . ' @ ' . $e->getFile() . ':' . $e->getLine());
        if (ENVIRONMENT === 'development') {
            throw $e;
        }
    }
}

// ============================================
// SECURITY HEADERS
// ============================================
if (!headers_sent()) {
    header('Content-Type: text/html; charset=utf-8');
    header('X-Frame-Options: SAMEORIGIN');
    header('X-Content-Type-Options: nosniff');
    header('X-XSS-Protection: 1; mode=block');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header_remove('X-Powered-By');

    if (!empty($_SERVER['HTTPS'])) {
        header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
    }
}

// ============================================
// PARSE REQUEST
// ============================================
$page = isset($_GET['page'])
    ? preg_replace('/[^a-z0-9\-]/', '', strtolower($_GET['page']))
    : 'home';

$requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
    && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
$isApi  = strpos($page, 'api-') === 0;
$isCron = strpos($page, 'cron-') === 0;

// ============================================
// COMPLETE ROUTES ARRAY
// ============================================
$routes = [
    // ========== PUBLIC PAGES ==========
    'home' => ['file' => 'pages/home.php', 'title' => 'Find Your Perfect Stay'],
    'home-fold' => ['file' => 'pages/home-fold.php', 'title' => 'Find Your Perfect Stay'],
    'pricing' => ['file' => 'pages/pricing.php', 'title' => 'Pricing — Revenda'],
    'properties' => ['file' => 'pages/properties.php', 'title' => 'Browse Properties'],
    'property' => ['file' => 'pages/property.php', 'title' => 'Property Details'],
    'map' => ['file' => 'pages/map.php', 'title' => 'Explore on Map'],
    'search' => ['file' => 'pages/search.php', 'title' => 'Search'],
    'compare' => ['file' => 'pages/compare.php', 'title' => 'Compare Properties'],
    'about' => ['file' => 'pages/about.php', 'title' => 'About Us'],
    'contact' => ['file' => 'pages/contact.php', 'title' => 'Contact Us'],
    'terms' => ['file' => 'pages/terms.php', 'title' => 'Terms & Conditions'],
    'privacy' => ['file' => 'pages/privacy.php', 'title' => 'Privacy Policy'],
    'faq' => ['file' => 'pages/faq.php', 'title' => 'FAQ'],
    'how-it-works' => ['file' => 'pages/how-it-works.php', 'title' => 'How It Works'],
    'blog' => ['file' => 'pages/blog.php', 'title' => 'Travel Blog'],
    'currency-calculator' => ['file' => 'pages/currency-calculator.php', 'title' => 'Currency Calculator'],
    'sitemap' => ['file' => 'pages/sitemap.php', 'raw' => true],
    'profile-public' => ['file' => 'pages/profile-public.php', 'title' => 'Traveler Profile'],
    'ar-preview' => ['file' => 'pages/ar-preview.php', 'title' => 'AR Preview'],
    'ar-room-preview' => ['file' => 'pages/ar-room-preview.php', 'title' => 'AR Room Preview'],
    'kb-article' => ['file' => 'pages/kb-article.php', 'title' => 'Help Article'],
    'travel-stories' => ['file' => 'pages/travel-stories.php', 'title' => 'Travel Stories'],
    'carbon-marketplace' => ['file' => 'pages/carbon-marketplace.php', 'title' => 'Carbon Offset Marketplace'],
    'careers' => ['file' => 'pages/careers.php', 'title' => 'Careers'],
    '404' => ['file' => 'pages/404.php', 'title' => 'Page Not Found'],
    '500' => ['file' => 'pages/500.php', 'title' => 'Server Error'],
    'booking' => ['file' => 'pages/booking.php', 'auth' => true, 'title' => 'Booking'],
    'guest-menu-embed' => ['file' => 'pages/guest-menu-embed.php', 'raw' => true],
    'seed-menus' => ['file' => 'pages/seed-menus.php', 'raw' => true],
    'guest-menu'        => ['file' => 'pages/guest-menu.php',        'raw' => true],
    'guest-menu-print'  => ['file' => 'pages/guest-menu-print.php',  'raw' => true],
    'guest-order-status'  => ['file' => 'pages/guest-order-status.php',  'raw' => true],
    'guest-report' => ['file' => 'pages/guest-report.php', 'raw' => true],
    'laundry-track' => ['file' => 'pages/laundry-track.php', 'raw' => true],
    'live-chat' => ['file' => 'pages/live-chat.php', 'auth' => true, 'raw' => true],
    'partners' => ['file' => 'pages/partners.php', 'title' => 'Our Partners'],
    'press' => ['file' => 'pages/press.php', 'title' => 'Press Center'],
    'restaurant-detail' => ['file' => 'pages/restaurant-detail.php', 'title' => 'Restaurant Detail'],

    // ========== TOUR OPERATORS — PUBLIC ==========
    'tour-operators' => ['file' => 'pages/tour-operators.php', 'title' => 'Tour Operators'],
    'tour-operator'  => ['file' => 'pages/tour-operator.php',  'title' => 'Tour Operator'],
    'tour-packages'  => ['file' => 'pages/tour-packages.php',  'title' => 'Tour Packages'],
    'tour-package'   => ['file' => 'pages/tour-package.php',   'title' => 'Tour Package'],
    'tour-booking'   => ['file' => 'pages/tour-booking.php',   'auth' => true, 'title' => 'Book Tour'],
    'tour-review'    => ['file' => 'pages/tour-review.php',    'auth' => true, 'title' => 'Write a Review'],
    'tour-booking-confirm'   => ['file' => 'pages/tour-booking-confirm.php',   'title' => 'Booking Confirmed'],
    'cto-apply'              => ['file' => 'pages/cto-apply.php',              'title' => 'Become a Tour Operator'],

    // ========== PROPERTY CLAIMS ==========
    'claim-property' => ['file' => 'pages/claim-property.php', 'raw' => false, 'title' => 'Claim Your Property'],
    'claim-status'   => ['file' => 'pages/claim-status.php',   'auth' => true, 'raw' => false, 'title' => 'My Claims'],
    'admin-claims'   => ['file' => 'pages/admin/claims.php',   'auth' => true, 'admin' => true, 'raw' => false, 'title' => 'Property Claims'],

    // ========== ACTIVITIES & EXPERIENCES ==========
    'activities' => ['file' => 'pages/activities.php', 'title' => 'Things to Do & Experiences'],
    'activity'   => ['file' => 'pages/activity.php',   'title' => 'Activity Detail'],

    // ========== MICE — PUBLIC ==========
    'mice'  => ['file' => 'pages/mice.php',  'title' => 'MICE Venues — Meetings, Conferences & Events'],
    'venue' => ['file' => 'pages/venue.php', 'title' => 'Venue Details'],
    'list-your-venue' => ['file' => 'pages/list-your-venue.php', 'title' => 'List Your MICE Venue'],
    'become-a-planner' => ['file' => 'pages/become-a-planner.php', 'title' => 'Become a Planner'],

    // ========== EVENTS — PUBLIC ==========
    'events'         => ['file' => 'pages/events.php',         'title' => 'Events'],
    'event'          => ['file' => 'pages/event.php',          'title' => 'Event Details'],
    'event-confirm'  => ['file' => 'pages/event-confirm.php',  'title' => 'Registration Confirmed'],
    'event-checkin'  => ['file' => 'pages/event-checkin.php',  'auth' => true, 'title' => 'Event Check-In'],
    'event-pay'      => ['file' => 'pages/event-pay.php',      'auth' => true, 'title' => 'Pay for Event'],
    'event-register'              => ['file' => 'pages/event-register.php',              'raw' => true],
    'event-registration-cancel'   => ['file' => 'pages/event-registration-cancel.php',   'raw' => true],
    'event-announce-send'         => ['file' => 'pages/event-announce-send.php',         'raw' => true],

    // ========== QR CODE MENU ==========
    'menu' => ['file' => 'pages/menu-public.php', 'title' => 'Digital Menu'],
    'menu-qr' => ['file' => 'pages/menu-qr.php', 'title' => 'Menu QR Code'],
    'menu-view' => ['file' => 'pages/menu-public.php', 'title' => 'Digital Menu'],

    // ========== SEED TOOLS ==========
    'tools-seed-osm-country' => [
        'file'   => 'tools/seed-osm-country.php',
        'auth'   => true, 'admin'  => true, 'raw' => true,
        'title'  => 'Seed OSM Country'
    ],
    'tools-seed-osm-activities' => [
        'file'   => 'tools/seed-osm-activities.php',
        'auth'   => true, 'admin'  => true, 'raw' => true,
        'title'  => 'Seed OSM Activities'
    ],
    'tools-warm-hotel-cache' => [
        'file'   => 'tools/warm-hotel-cache.php',
        'auth'   => true, 'admin'  => true, 'raw' => true,
        'title'  => 'Warm Hotel Image Cache'
    ],
    'tools-migrate-v33-home' => [
        'file'   => 'tools/migrate-v33-home.php',
        'auth'   => true, 'admin'  => true, 'raw' => true,
        'title'  => 'Migrate v33 Home Schema'
    ],
    'tools-seed-airports' => [
    'file'   => 'pages/seed-airports.php',
    'auth'   => true, 'admin'  => true, 'raw' => true,
    'title'  => 'Seed Airports',
],
    'tools-module-status' => ['file' => 'tools/module-status.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Module Status'],
    'tools-insert-module-guards' => ['file' => 'tools/insert-module-guards.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Insert Module Guards'],
    'tools-insert-module-guards-v2' => ['file' => 'tools/insert-module-guards-v2.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Insert Module Guards v2'],
    'tools-insert-module-guards-v3' => ['file' => 'tools/insert-module-guards-v3.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Insert Module Guards v3'],
    'tools-insert-module-guards-v4' => ['file' => 'tools/insert-module-guards-v4.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Insert Module Guards v4'],
    'tools-diagnose-tour-bookings' => ['file' => 'tools/diagnose-tour-bookings.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Diagnose Tour Bookings'],
    'tools-insert-module-guards-v5' => ['file' => 'tools/insert-module-guards-v5.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Insert Module Guards v5'],
    'tools-check-phase-c' => ['file' => 'tools/check-phase-c.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Check Phase C'],
    'tools-set-seed-passwords' => ['file' => 'tools/set-seed-passwords.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Set Seed Passwords'],
    'tools-check-supplier-page-state' => ['file' => 'tools/check-supplier-page-state.php', 'auth' => true, 'admin' => true, 'raw' => true, 'title' => 'Check Supplier Page State'],

    // ========== AUTH ==========
    'login' => ['file' => 'pages/auth/login.php', 'guest_only' => true, 'title' => 'Sign In'],
    'register' => ['file' => 'pages/auth/register.php', 'guest_only' => true, 'title' => 'Create Account'],
    'logout' => ['file' => 'pages/auth/logout.php', 'raw' => true],
    'forgot-password' => ['file' => 'pages/auth/forgot-password.php', 'guest_only' => true, 'title' => 'Forgot Password'],
    'reset-password' => ['file' => 'pages/auth/reset-password.php', 'title' => 'Reset Password'],
    'verify-email' => ['file' => 'pages/auth/verify-email.php', 'auth' => true, 'title' => 'Verify Email'],

    // ========== USER ==========
    'dashboard' => ['file' => 'pages/user/dashboard.php', 'auth' => true, 'title' => 'Dashboard'],
    'profile' => ['file' => 'pages/user/profile.php', 'auth' => true, 'title' => 'My Profile'],
    'bookings' => ['file' => 'pages/user/bookings.php', 'auth' => true, 'title' => 'My Bookings'],
    'booking-detail' => ['file' => 'pages/user/booking-detail.php', 'auth' => true, 'title' => 'Booking Details'],
    'wishlist' => ['file' => 'pages/user/wishlist.php', 'auth' => true, 'title' => 'My Wishlist'],
    'messages' => ['file' => 'pages/user/messages.php', 'auth' => true, 'title' => 'Messages'],
    'conversation' => ['file' => 'pages/user/conversation.php', 'auth' => true, 'title' => 'Conversation'],
    'notifications' => ['file' => 'pages/user/notifications.php', 'auth' => true, 'title' => 'Notifications'],
    'rewards' => ['file' => 'pages/user/rewards.php', 'auth' => true, 'title' => 'Rewards'],
    'user-achievements' => ['file' => 'pages/user/achievements.php', 'auth' => true, 'title' => 'Achievements'],
    'loyalty-card' => ['file' => 'pages/user/loyalty-card.php',   'auth' => true,  'title' => 'My Loyalty Card'],
    'loyalty-card-public' => ['file' => 'pages/loyalty-card-public.php', 'auth' => false,  'title' => 'Revenda Loyalty Card'],
    'favorites' => ['file' => 'pages/user/favorites.php', 'auth' => true, 'title' => 'Favorites'],
    'payment-methods' => ['file' => 'pages/user/payment-methods.php', 'auth' => true, 'title' => 'Payment Methods'],
    'security' => ['file' => 'pages/user/security.php', 'auth' => true, 'title' => 'Security'],
    'preferences' => ['file' => 'pages/user/preferences.php', 'auth' => true, 'title' => 'Preferences'],
    'write-review' => ['file' => 'pages/write-review.php', 'auth' => true, 'title' => 'Write a Review'],
    'checkout' => ['file' => 'pages/checkout.php', 'auth' => true, 'title' => 'Checkout'],
    'for-you' => ['file' => 'pages/for-you.php', 'auth' => true, 'title' => 'For You'],
    'magic-login' => ['file' => 'pages/magic-login.php', 'raw' => true],

    // ========== USER — TOUR BOOKINGS ==========
    'user-tour-bookings'       => ['file' => 'pages/user/tour-bookings.php',       'auth' => true, 'module' => 'tour_bookings', 'title' => 'My Tour Bookings'],
    'user-tour-booking-detail' => ['file' => 'pages/user/tour-booking-detail.php', 'auth' => true, 'module' => 'tour_bookings', 'title' => 'Tour Booking Details'],

    // ========== USER — EVENT DASHBOARD ==========
    'user-event-dashboard'   => ['file' => 'pages/user/event-dashboard.php',   'auth' => true, 'module' => 'events', 'title' => 'Event Dashboard'],
    'user-event-edit'        => ['file' => 'pages/user/event-edit.php',        'auth' => true, 'module' => 'events', 'title' => 'Edit Event'],
    'user-event-fields-edit' => ['file' => 'pages/user/event-fields-edit.php', 'auth' => true, 'module' => 'events', 'title' => 'Event Form Fields'],
    'user-event-announce'    => ['file' => 'pages/user/event-announce.php',    'auth' => true, 'module' => 'events', 'title' => 'Send Announcement'],
    'user-event-tickets'     => ['file' => 'pages/user/event-tickets.php',     'auth' => true, 'module' => 'event_tickets', 'title' => 'Event Ticket Tiers'],
    
    // Aliases — pages internally reference ?page=budgets, ?page=approvals-inbox, etc.
    'budgets'                 => ['file' => 'pages/user/budgets.php',                 'auth' => true, 'module' => 'planner_budgets',   'title' => 'Budgets'],
    'approvals-inbox'         => ['file' => 'pages/user/approvals-inbox.php',         'auth' => true, 'module' => 'planner_approvals', 'title' => 'Approvals'],
    'approval-workflows'      => ['file' => 'pages/user/approval-workflows.php',      'auth' => true, 'module' => 'planner_approvals', 'title' => 'Approval Workflows'],
    'approval-detail'         => ['file' => 'pages/user/approval-detail.php',         'auth' => true, 'module' => 'planner_approvals', 'title' => 'Approval Detail'],
    'company-audit'           => ['file' => 'pages/user/company-audit.php',           'auth' => true, 'module' => 'planner_budgets',   'title' => 'Company Audit'],
    'vendor-scorecards'       => ['file' => 'pages/user/vendor-scorecards.php',       'auth' => true, 'module' => 'planner_compare',   'title' => 'Vendor Scorecards'],
    'vendor-scorecard-detail' => ['file' => 'pages/user/vendor-scorecard-detail.php', 'auth' => true, 'module' => 'planner_compare',   'title' => 'Vendor Scorecard'],
    'vendor-policies'         => ['file' => 'pages/user/vendor-policies.php',         'auth' => true, 'module' => 'planner_compare',   'title' => 'Vendor Policies'],
    'company-invoices'        => ['file' => 'pages/user/company-invoices.php',        'auth' => true, 'module' => 'planner_budgets',   'title' => 'Company Invoices'],
    'company-invoice-pdf'     => ['file' => 'pages/user/company-invoice-pdf.php',     'auth' => true, 'module' => 'planner_budgets', 'raw' => true, 'title' => 'Invoice PDF'],
    'company'                 => ['file' => 'pages/user/company.php',                 'auth' => true, 'title' => 'Company'],

    // ========== USER — EVENT REGISTRATIONS ==========
    'my-event-registrations' => ['file' => 'pages/user/my-event-registrations.php', 'auth' => true, 'module' => 'event_registrations', 'title' => 'My Event Tickets'],

    // ========== MICE — PLANNER ==========
    'user-rfps' => ['file' => 'pages/user/rfps.php', 'auth' => true, 'module' => 'planner_rfps', 'title' => 'My RFPs'],
    'user-rfp'  => ['file' => 'pages/user/rfp.php',  'auth' => true, 'module' => 'planner_rfps', 'title' => 'RFP Details'],
    'user-mice-booking' => ['file' => 'pages/user/mice-booking.php', 'auth' => true, 'module' => 'mice_venues', 'title' => 'My MICE Booking'],

    // ========== MICE — VENDOR OPS ==========
    'vendor-mice-calendar'  => ['file' => 'pages/vendor/mice-calendar.php',  'auth' => true, 'vendor' => true, 'module' => 'mice_venues', 'title' => 'MICE Venue Calendar'],
    'vendor-mice-analytics' => ['file' => 'pages/vendor/mice-analytics.php', 'auth' => true, 'vendor' => true, 'module' => 'mice_analytics', 'title' => 'MICE Analytics'],
    'vendor-mice-booking'         => ['file' => 'pages/vendor/mice-booking.php',         'auth' => true, 'vendor' => true, 'module' => 'mice_venues', 'title' => 'MICE Booking'],
    'vendor-mice-proposal-edit'   => ['file' => 'pages/vendor/mice-proposal-edit.php',   'auth' => true, 'vendor' => true, 'module' => 'rfp_pipeline', 'title' => 'Compose Proposal'],
    'vendor-documents' => ['file' => 'pages/vendor/documents.php', 'auth' => true, 'vendor' => true, 'module' => 'document_library', 'title' => 'Documents'],
    'vendor-venue-contracts' => ['file' => 'pages/vendor/venue-contracts.php', 'auth' => true, 'vendor' => true, 'module' => 'venue_contracts', 'title' => 'Venue Contracts'],
    'vendor-mice-dashboard' => ['file' => 'pages/vendor/mice-dashboard.php', 'auth' => true, 'vendor' => true, 'title' => 'MICE Dashboard'],

    // ========== MICE — ADMIN COMMISSIONS ==========
    'admin-mice-commissions'       => ['file' => 'pages/admin/mice-commissions.php',       'auth' => true, 'admin' => true, 'title' => 'MICE Commissions'],
    'admin-mice-commission-detail' => ['file' => 'pages/admin/mice-commission-detail.php', 'auth' => true, 'admin' => true, 'title' => 'Commission Detail'],
    'admin-mice-bookings'    => ['file' => 'pages/admin/mice-bookings.php',    'auth' => true, 'admin' => true, 'title' => 'MICE Bookings'],
    'admin-events'           => ['file' => 'pages/admin/events.php',           'auth' => true, 'admin' => true, 'title' => 'All Events'],
    'admin-event-settings'   => ['file' => 'pages/admin/event-settings.php',   'auth' => true, 'admin' => true, 'title' => 'Event Settings'],

    // ========== GUEST EXPERIENCE ==========
    'guest-app' => ['file' => 'pages/guest-app.php', 'auth' => true, 'title' => 'My App'],
    'smart-key' => ['file' => 'pages/smart-key.php', 'auth' => true, 'title' => 'Digital Key'],
    'voice-concierge' => ['file' => 'pages/voice-concierge.php', 'auth' => true, 'title' => 'Voice Concierge'],
    'nft-rewards' => ['file' => 'pages/nft-rewards.php', 'auth' => true, 'title' => 'NFT Rewards'],
    'crypto-referrals' => ['file' => 'pages/crypto-referrals.php', 'auth' => true, 'module' => 'referral', 'title' => 'Crypto Referrals'],
    'group-chat' => ['file' => 'pages/group-chat.php', 'auth' => true, 'title' => 'Group Chat'],
    'support' => ['file' => 'pages/support.php', 'auth' => true, 'module' => 'priority_support', 'title' => 'Support'],
    'ticket-detail' => ['file' => 'pages/ticket-detail.php', 'auth' => true, 'module' => 'priority_support', 'title' => 'Ticket'],
    'video-call' => ['file' => 'pages/video-call.php', 'auth' => true, 'title' => 'Video Call'],
    'blockchain-profile' => ['file' => 'pages/blockchain-profile.php', 'auth' => true, 'title' => 'Blockchain Profile'],
    'smart-room' => ['file' => 'pages/smart-room.php', 'auth' => true, 'title' => 'Smart Room'],
    'robot-concierge' => ['file' => 'pages/robot-concierge.php', 'auth' => true, 'title' => 'Robot Concierge'],
    'carbon-offset' => ['file' => 'pages/carbon-offset.php', 'auth' => true, 'title' => 'Carbon Offset'],
    'insurance' => ['file' => 'pages/insurance.php', 'auth' => true, 'title' => 'Insurance'],
    'trip-planner' => ['file' => 'pages/trip-planner.php', 'auth' => true, 'title' => 'Trip Planner'],
    'trip-detail' => ['file' => 'pages/trip-detail.php', 'auth' => true, 'title' => 'Trip Details'],

    // ========== STAFF ==========
    'agent-dashboard' => ['file' => 'pages/agent/dashboard.php', 'auth' => true, 'staff' => true, 'title' => 'Agent Dashboard'],
    'agent-tickets' => ['file' => 'pages/agent/tickets.php', 'auth' => true, 'staff' => true, 'title' => 'Tickets'],

    // ========== ADMIN IOT ==========
    'admin-iot-devices' => ['file' => 'pages/admin/iot-devices.php', 'auth' => true, 'admin' => true, 'title' => 'IoT Devices'],

    // ========== VENDOR IOT ==========
    'vendor-smart-devices' => ['file' => 'pages/vendor/smart-devices.php', 'auth' => true, 'vendor' => true, 'title' => 'Smart Devices'],

    // ========== VENDOR — CORE ==========
    'vendor-pms' => ['file' => 'pages/vendor/pms.php', 'auth' => true, 'vendor' => true, 'module' => 'pms', 'title' => 'PMS Hub'],
    'vendor-dashboard' => ['file' => 'pages/vendor/dashboard.php', 'auth' => true, 'vendor' => true, 'title' => 'Vendor Dashboard'],
    'vendor-client-crm' => ['file' => 'pages/vendor/client-crm.php', 'auth' => true, 'vendor' => true, 'module' => 'client_crm', 'title' => 'Client CRM'],
    'company-dashboard' => ['file' => 'pages/company/dashboard.php', 'auth' => true, 'title' => 'Company Dashboard'],
    'vendor-support'        => ['file' => 'pages/vendor/support.php',        'auth' => true, 'vendor' => true, 'title' => 'Customer Inbox'],
    'vendor-support-ticket' => ['file' => 'pages/vendor/support-ticket.php', 'auth' => true, 'vendor' => true, 'title' => 'Customer Message'],
    'contact-vendor'          => ['file' => 'pages/contact-vendor.php',           'auth' => true, 'title' => 'Message Vendor'],

    // ========== VENDOR — PROPERTIES ==========
    'vendor-properties' => ['file' => 'pages/vendor/properties.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'My Properties'],
    'vendor-add-property' => ['file' => 'pages/vendor/add-property.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'Add Property'],
    'vendor-edit-property' => ['file' => 'pages/vendor/edit-property.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'Edit Property'],
    'vendor-rooms' => ['file' => 'pages/vendor/rooms.php', 'auth' => true, 'vendor' => true, 'module' => 'rooms', 'title' => 'Room Types'],
    'vendor-add-room' => ['file' => 'pages/vendor/add-room.php', 'auth' => true, 'vendor' => true, 'module' => 'rooms', 'title' => 'Add Room'],
    'vendor-edit-room' => ['file' => 'pages/vendor/edit-room.php', 'auth' => true, 'vendor' => true, 'module' => 'rooms', 'title' => 'Edit Room'],
    'vendor-room-profile' => ['file' => 'pages/vendor/room-profile.php', 'auth' => true, 'vendor' => true, 'module' => 'rooms', 'title' => 'Room Profile'],
    'vendor-sync-rooms' => ['file' => 'pages/vendor/sync-rooms.php', 'auth' => true, 'vendor' => true, 'module' => 'rooms', 'title' => 'Sync Rooms'],
    'vendor-calendar' => ['file' => 'pages/vendor/calendar.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'Calendar'],
    'vendor-rate-management' => ['file' => 'pages/vendor/rate-management.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'Smart Pricing'],
    'vendor-inventory' => ['file' => 'pages/vendor/inventory.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'Inventory'],
    'list-your-restaurant' => ['file' => 'pages/vendor/list-your-restaurant.php', 'auth' => false],
    'restaurants' => ['file' => 'pages/restaurants.php', 'auth' => false],
    'restaurant' => ['file' => 'pages/restaurant.php', 'auth' => false],
    'vendor-reservations' => ['file' => 'pages/vendor/vendor-reservations.php', 'auth' => true, 'vendor' => true],
    'find-table' => ['file' => 'pages/find-table.php', 'auth' => false],

    // ========== VENDOR — OPERATIONS ==========
    'vendor-frontdesk' => ['file' => 'pages/vendor/frontdesk.php', 'auth' => true, 'vendor' => true, 'module' => 'frontdesk', 'title' => 'Front Desk'],
    'vendor-bookings' => ['file' => 'pages/vendor/bookings.php', 'auth' => true, 'vendor' => true, 'can' => 'booking.view', 'module' => 'properties', 'title' => 'Bookings'],
    'vendor-finance' => ['file' => 'pages/vendor/finance.php', 'auth' => true, 'vendor' => true, 'can' => 'finance.view', 'module' => 'financial_dashboard', 'title' => 'Finance'],
    'vendor-housekeeping' => ['file' => 'pages/vendor/housekeeping.php', 'auth' => true, 'staff' => true, 'can' => 'housekeeping.view', 'module' => 'housekeeping', 'title' => 'Housekeeping'],
    'vendor-staff' => ['file' => 'pages/vendor/staff.php', 'auth' => true, 'vendor' => true, 'can' => 'staff.view', 'module' => 'staff_scheduling', 'title' => 'Staff'],
    'vendor-booking-detail' => ['file' => 'pages/vendor/booking-detail.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'Booking Details'],
    'vendor-checkin' => ['file' => 'pages/vendor/checkin.php', 'auth' => true, 'staff' => true, 'module' => 'frontdesk', 'title' => 'Check-In'],
    'vendor-checkout' => ['file' => 'pages/vendor/checkout.php', 'auth' => true, 'staff' => true, 'module' => 'frontdesk', 'title' => 'Check-Out'],
    'vendor-guest-management' => ['file' => 'pages/vendor/guest-management.php', 'auth' => true, 'vendor' => true, 'module' => 'frontdesk', 'title' => 'Guests'],
    'vendor-night-audit' => ['file' => 'pages/vendor/night-audit.php', 'auth' => true, 'vendor' => true, 'module' => 'night_audit', 'title' => 'Night Audit'],
    'vendor-waitlist' => ['file' => 'pages/vendor/waitlist.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'Waitlist'],
    'vendor-group-bookings' => ['file' => 'pages/vendor/group-bookings.php', 'auth' => true, 'vendor' => true, 'module' => 'properties', 'title' => 'Group Bookings'],
    'vendor-suppliers' => ['file' => 'pages/vendor/suppliers.php', 'auth' => true, 'vendor' => true, 'module' => 'supplier_management', 'title' => 'Suppliers'],

    // ========== VENDOR — TOUR OPERATORS ==========
    'vendor-tour-dashboard'    => ['file' => 'pages/vendor/tour-dashboard.php',    'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'Tour Operator Dashboard'],
    'vendor-tour-guest-experience' => ['file' => 'pages/vendor/tour-guest-experience.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_guest_experience', 'title' => 'Guest Experience'],
    'vendor-tour-quotes'      => ['file' => 'pages/vendor/tour-quotes.php',      'auth' => true, 'vendor' => true, 'module' => 'office_suite', 'title' => 'Tour Quotes'],
    'vendor-tour-quote-edit'  => ['file' => 'pages/vendor/tour-quote-edit.php',  'auth' => true, 'vendor' => true, 'module' => 'office_suite', 'title' => 'Edit Quote'],
    'vendor-tour-itineraries'    => ['file' => 'pages/vendor/tour-itineraries.php',    'auth' => true, 'vendor' => true, 'module' => 'office_suite', 'title' => 'Tour Itineraries'],
    'vendor-tour-itinerary-edit' => ['file' => 'pages/vendor/tour-itinerary-edit.php', 'auth' => true, 'vendor' => true, 'module' => 'office_suite', 'title' => 'Edit Itinerary'],
    'vendor-tour-clients'        => ['file' => 'pages/vendor/tour-clients.php',        'auth' => true, 'vendor' => true, 'module' => 'office_suite', 'title' => 'Tour Clients'],
    'vendor-tour-finance' => ['file' => 'pages/vendor/tour-finance.php', 'auth' => true, 'vendor' => true, 'module' => 'quotes', 'title' => 'Tour Finance'],
    'vendor-tour-guest-experience-manifest' => ['file' => 'pages/vendor/tour-guest-experience-manifest.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_guest_experience', 'title' => 'Manifest'],
    'vendor-tour-guest-experience-feedback' => ['file' => 'pages/vendor/tour-guest-experience-feedback.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_guest_experience', 'title' => 'Guest Feedback'],
    'vendor-tour-transfers' => ['file' => 'pages/vendor/tour-transfers.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_transfers', 'title' => 'Tour Transfers'],
    'vendor-tour-packages'     => ['file' => 'pages/vendor/tour-packages.php',     'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'Tour Packages'],
    'vendor-tour-package-edit' => ['file' => 'pages/vendor/tour-package-edit.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'Edit Tour Package'],
    'vendor-tour-package-new'  => ['file' => 'pages/vendor/tour-package-edit.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'New Tour Package'],
    'vendor-tour-departures'   => ['file' => 'pages/vendor/tour-departures.php',   'auth' => true, 'vendor' => true, 'module' => 'tour_departures', 'title' => 'Tour Departures'],
    'vendor-tour-guides'       => ['file' => 'pages/vendor/tour-guides.php',       'auth' => true, 'vendor' => true, 'module' => 'tour_guides', 'title' => 'Tour Guides'],
    'vendor-tour-vehicles'     => ['file' => 'pages/vendor/tour-vehicles.php',     'auth' => true, 'vendor' => true, 'module' => 'tour_vehicles', 'title' => 'Tour Vehicles'],
    'vendor-tour-bookings'     => ['file' => 'pages/vendor/tour-bookings.php',     'auth' => true, 'vendor' => true, 'module' => 'tour_bookings', 'title' => 'Tour Bookings'],
    'vendor-tour-settings'     => ['file' => 'pages/vendor/tour-settings.php',     'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'Operator Settings'],
    'vendor-tour-onboarding'   => ['file' => 'pages/vendor/tour-onboarding.php',   'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'Become a Tour Operator'],
    'vendor-tour-analytics'    => ['file' => 'pages/vendor/tour-analytics.php',    'auth' => true, 'vendor' => true, 'module' => 'analytics_advanced', 'title' => 'Tour Analytics'],
    'vendor-api-access'       => ['file' => 'pages/vendor/api-access.php',       'auth' => true, 'vendor' => true, 'module' => 'api_access',       'title' => 'API Access'],
    'vendor-white-label'      => ['file' => 'pages/vendor/white-label.php',      'auth' => true, 'vendor' => true, 'module' => 'white_label',      'title' => 'White Label'],
    'vendor-multi-entity'     => ['file' => 'pages/vendor/multi-entity.php',     'auth' => true, 'vendor' => true, 'module' => 'multi_entity',     'title' => 'Multi-Entity'],
    'vendor-analytics-custom' => ['file' => 'pages/vendor/analytics-custom.php', 'auth' => true, 'vendor' => true, 'module' => 'analytics_custom', 'title' => 'Custom Analytics'],
    'vendor-account-manager'  => ['file' => 'pages/vendor/account-manager.php',  'auth' => true, 'vendor' => true, 'module' => 'account_manager',  'title' => 'Account Manager'],
    'vendor-event-procurement'=> ['file' => 'pages/vendor/event-procurement.php','auth' => true, 'module' => 'event_procurement','title' => 'Event Procurement'],
    'vendor-tour-operator-profile' => ['file' => 'pages/vendor/tour-operator-profile.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'Operator Profile'],

    // ========== VENDOR — TOUR OPERATORS ==========
    'vendor-vehicle-maintenance'      => ['file' => 'pages/vendor/vehicle-maintenance.php',      'auth' => true, 'vendor' => true, 'module' => 'tour_vehicles', 'title' => 'Vehicle Maintenance'],
    'vendor-vehicle-maintenance-new'  => ['file' => 'pages/vendor/vehicle-maintenance-new.php',  'auth' => true, 'vendor' => true, 'module' => 'tour_vehicles', 'title' => 'Log Maintenance'],
    'vendor-compliance-new'           => ['file' => 'pages/vendor/compliance-new.php',           'auth' => true, 'vendor' => true, 'module' => 'tour_vehicles', 'title' => 'Upload Compliance'],
    'vendor-vehicle-expenses'         => ['file' => 'pages/vendor/vehicle-expenses.php',         'auth' => true, 'vendor' => true, 'module' => 'tour_vehicles', 'title' => 'Vehicle Expenses'],
    'vendor-vehicle-profile'          => ['file' => 'pages/vendor/vehicle-profile.php',          'auth' => true, 'vendor' => true, 'module' => 'tour_vehicles', 'title' => 'Vehicle Profile'],

    // ========== TRANSFERS — TOUR OPERATORS ==========
    'driver-transfer' => ['file' => 'pages/driver-transfer.php', 'raw' => true],
    'transfer-track'  => ['file' => 'pages/transfer-track.php', 'raw' => true],
    'api-transfer-location' => ['file' => 'pages/api/transfer-location.php', 'raw' => true],
    'transfer-qr' => ['file' => 'pages/transfer-qr.php', 'raw' => true],

    // ========== VENDOR — MICE ==========
    'vendor-mice-inbox'        => ['file' => 'pages/vendor/mice-inbox.php',        'auth' => true, 'vendor' => true, 'module' => 'rfp_pipeline', 'title' => 'MICE RFP Inbox'],
    'vendor-mice-rfp'          => ['file' => 'pages/vendor/mice-rfp.php',          'auth' => true, 'vendor' => true, 'module' => 'rfp_pipeline', 'title' => 'MICE RFP Details'],
    'vendor-mice-venues'       => ['file' => 'pages/vendor/mice-venues.php',       'auth' => true, 'vendor' => true, 'module' => 'mice_venues', 'title' => 'My Meeting Venues'],
    'vendor-mice-venue-edit'   => ['file' => 'pages/vendor/mice-venue-edit.php',   'auth' => true, 'vendor' => true, 'module' => 'mice_venues', 'title' => 'Edit Meeting Venue'],
    'vendor-mice-package-edit' => ['file' => 'pages/vendor/mice-package-edit.php', 'auth' => true, 'vendor' => true, 'module' => 'conference_packages', 'title' => 'Edit Conference Package'],

    // ========== VENDOR — HOUSEKEEPING / MAINTENANCE ==========
    'vendor-maintenance' => ['file' => 'pages/vendor/maintenance.php', 'auth' => true, 'staff' => true, 'module' => 'maintenance', 'title' => 'Maintenance'],

    // ========== VENDOR — LAUNDRY ==========
    'vendor-laundry' => ['file' => 'pages/vendor/laundry.php', 'auth' => true, 'vendor' => true, 'module' => 'laundry', 'title' => 'Laundry'],
    'vendor-laundry-order' => ['file' => 'pages/vendor/laundry-order.php', 'auth' => true, 'vendor' => true, 'module' => 'laundry', 'title' => 'Laundry Order'],
    'vendor-laundry-services' => ['file' => 'pages/vendor/laundry-services.php', 'auth' => true, 'vendor' => true, 'module' => 'laundry', 'title' => 'Laundry Services'],

    // ========== VENDOR — F&B ==========
    'vendor-restaurant-pos' => ['file' => 'pages/vendor/restaurant-pos.php', 'auth' => true, 'vendor' => true, 'module' => 'restaurant_pos', 'title' => 'Restaurant POS'],
    'vendor-restaurant-reports' => ['file' => 'pages/vendor/restaurant-reports.php', 'auth' => true, 'vendor' => true, 'module' => 'restaurant_pos', 'title' => 'Restaurant Reports'],
    'vendor-restaurants' => ['file' => 'pages/vendor/restaurants.php', 'auth' => true, 'vendor' => true, 'module' => 'restaurant_pos', 'title' => 'Restaurants'],
    'vendor-menu' => ['file' => 'pages/vendor/menu.php', 'auth' => true, 'vendor' => true, 'module' => 'restaurant_pos', 'title' => 'Menu'],
    'vendor-menu-onboarding' => ['file' => 'pages/vendor/menu-onboarding.php', 'auth' => true, 'vendor' => true, 'module' => 'restaurant_pos', 'title' => 'Menu Setup'],
    'vendor-orders' => ['file' => 'pages/vendor/orders.php', 'auth' => true, 'vendor' => true, 'module' => 'restaurant_pos', 'title' => 'Guest Orders'],
    'vendor-menu-qr' => ['file' => 'pages/vendor/menu-qr-generator.php', 'auth' => true, 'vendor' => true, 'module' => 'restaurant_pos', 'title' => 'Menu QR Codes'],
    'vendor-dining' => ['file' => 'pages/vendor/dining.php', 'auth' => true, 'vendor' => true, 'module' => 'restaurant_pos', 'title' => 'Dining Reservations'],
    'vendor-room-service' => ['file' => 'pages/vendor/room-service.php', 'auth' => true, 'vendor' => true, 'module' => 'room_service', 'title' => 'Room Service'],
    'vendor-door-scan' => ['file' => 'pages/vendor/door-scan.php', 'auth' => true],

    // ========== VENDOR — EVENTS ==========
    'vendor-events'              => ['file' => 'pages/vendor/events.php',              'auth' => true, 'vendor' => true, 'module' => 'events', 'title' => 'My Events'],
    'vendor-event-edit'          => ['file' => 'pages/vendor/event-edit.php',          'auth' => true, 'vendor' => true, 'module' => 'events', 'title' => 'Edit Event'],
    'vendor-event-registrations' => ['file' => 'pages/vendor/event-registrations.php', 'auth' => true, 'vendor' => true, 'module' => 'event_registrations', 'title' => 'Event Registrations'],
    'vendor-event-announce'      => ['file' => 'pages/vendor/event-announce.php',      'auth' => true, 'vendor' => true, 'module' => 'events', 'title' => 'Send Event Announcement'],
    'vendor-event-checkin' => ['file' => 'pages/vendor/event-checkin.php', 'auth' => true, 'vendor' => true, 'module' => 'event_checkin', 'title' => 'Event Check-In'],

    // ========== VENDOR — CONCIERGE ==========
    'vendor-concierge' => ['file' => 'pages/vendor/concierge.php', 'auth' => true, 'vendor' => true, 'title' => 'Concierge'],
    'vendor-tours' => ['file' => 'pages/vendor/tours.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'Tours'],
    'vendor-activities' => ['file' => 'pages/vendor/activities.php', 'auth' => true, 'vendor' => true, 'module' => 'tour_packages', 'title' => 'Activities'],

    // ========== VENDOR — STAFF ==========
    'vendor-staff-schedule' => ['file' => 'pages/vendor/staff-schedule.php', 'auth' => true, 'vendor' => true, 'module' => 'staff_scheduling', 'title' => 'Staff Schedule'],

    // ========== VENDOR — FINANCE ==========
    'vendor-analytics' => ['file' => 'pages/vendor/analytics.php', 'auth' => true, 'vendor' => true, 'module' => 'analytics_basic', 'title' => 'Analytics'],
    'vendor-revenue-detail' => ['file' => 'pages/vendor/revenue-detail.php', 'auth' => true, 'vendor' => true, 'module' => 'financial_dashboard', 'title' => 'Revenue Details'],
    'vendor-forecasting' => ['file' => 'pages/vendor/forecasting.php', 'auth' => true, 'vendor' => true, 'module' => 'analytics_advanced', 'title' => 'AI Forecasting'],
    'vendor-payouts' => ['file' => 'pages/vendor/payouts.php', 'auth' => true, 'vendor' => true, 'module' => 'financial_dashboard', 'title' => 'Payouts'],
    'vendor-invoice' => ['file' => 'pages/vendor/invoice.php', 'auth' => true, 'vendor' => true, 'module' => 'financial_dashboard', 'title' => 'Invoice'],
    'vendor-reports' => ['file' => 'pages/vendor/reports.php', 'auth' => true, 'vendor' => true, 'module' => 'financial_dashboard', 'title' => 'Reports'],
    'vendor-tax-settings' => ['file' => 'pages/vendor/tax-settings.php', 'auth' => true, 'vendor' => true, 'module' => 'financial_dashboard', 'title' => 'Tax Settings'],
    'vendor-folio' => ['file' => 'pages/vendor/folio.php', 'auth' => true, 'vendor' => true, 'module' => 'folio', 'title' => 'Folios'],

    // ========== VENDOR — MARKETING ==========
    'vendor-promotions' => ['file' => 'pages/vendor/promotions.php', 'auth' => true, 'vendor' => true, 'module' => 'promotions', 'title' => 'Promotions'],
    'vendor-reviews-management' => ['file' => 'pages/vendor/reviews-management.php', 'auth' => true, 'vendor' => true, 'title' => 'Reviews'],
    'vendor-email-templates' => ['file' => 'pages/vendor/email-templates.php', 'auth' => true, 'vendor' => true, 'title' => 'Email Templates'],
    'vendor-automation' => ['file' => 'pages/vendor/automation.php', 'auth' => true, 'vendor' => true, 'title' => 'Automation'],

    // ========== VENDOR — SETTINGS ==========
    'vendor-integrations' => ['file' => 'pages/vendor/integrations.php', 'auth' => true, 'vendor' => true, 'title' => 'Integrations'],
    'vendor-subscription' => ['file' => 'pages/vendor/subscription.php', 'auth' => true, 'vendor' => true, 'title' => 'Subscription'],
    'vendor-settings' => ['file' => 'pages/vendor/settings.php', 'auth' => true, 'vendor' => true, 'title' => 'Settings'],
    'vendor-theme' => ['file' => 'pages/vendor/theme.php', 'auth' => true, 'vendor' => true, 'title' => 'Theme'],
    'vendor-backup' => ['file' => 'pages/vendor/backup.php', 'auth' => true, 'vendor' => true, 'title' => 'Backup'],
    'vendor-channels' => ['file' => 'pages/vendor/channels.php', 'auth' => true, 'vendor' => true, 'module' => 'channel_manager', 'title' => 'Channel Connections'],
    
    // ============================================================
    // REVENDA RIDE MODULE (v1.0.0) — Independent module
    // Gated on 'rides' plan flag (NOT restaurant_pos). See migration:
    // ALTER platform_modules + vendor_enabled_modules for 'rides'.
    // ============================================================

    // -------- PUBLIC (no auth) --------
    'rides'                      => ['file' => 'pages/rides.php',                            'auth' => false, 'title' => 'Rides & Transfers'],
    'ride-book'                  => ['file' => 'pages/ride-book.php',                        'auth' => false, 'title' => 'Book a Ride'],
    'ride-confirm'               => ['file' => 'pages/ride-confirm.php',                     'auth' => false, 'title' => 'Ride Confirmed'],
    'ride-track'                 => ['file' => 'pages/ride-track.php',                       'auth' => false, 'title' => 'Track Ride'],
    'ride-receipt'               => ['file' => 'pages/ride-receipt.php',                     'auth' => false, 'raw' => true, 'title' => 'Ride Receipt'],

    // -------- AUTHENTICATED (any user) --------
    'ride-register'              => ['file' => 'pages/ride-register.php',                    'auth' => true,  'title' => 'Register your fleet'],
    'driver-register'            => ['file' => 'pages/driver-register.php',                  'auth' => true,  'title' => 'Drive with Revenda'],
    'ride-history'               => ['file' => 'pages/ride-history.php',                     'auth' => true,  'title' => 'My Rides'],
    'ride-rate'                  => ['file' => 'pages/ride-rate.php',                        'auth' => true,  'title' => 'Rate Ride'],
    'ride-disputes'              => ['file' => 'pages/user/ride-disputes.php',               'auth' => true,  'title' => 'My Ride Disputes'],
    'api-ride-rate'              => ['file' => 'pages/api/ride-rate.php',                    'raw' => true],
    'api-ride-dispute'           => ['file' => 'pages/api/ride-dispute.php',                 'raw' => true],

    // -------- VENDOR (auth + vendor + 'rides' module) --------
    'vendor-rides'               => ['file' => 'pages/vendor/rides.php',                     'auth' => true,  'vendor' => true, 'module' => 'rides', 'title' => 'Rides'],
    'vendor-rides-bookings'      => ['file' => 'pages/vendor/rides-bookings.php',            'auth' => true,  'vendor' => true, 'module' => 'rides', 'title' => 'Ride Bookings'],
    'vendor-rides-fleet'         => ['file' => 'pages/vendor/rides-fleet.php',               'auth' => true,  'vendor' => true, 'module' => 'rides', 'title' => 'Fleet'],
    'vendor-rides-fleet-edit'    => ['file' => 'pages/vendor/rides-fleet-edit.php',          'auth' => true,  'vendor' => true, 'module' => 'rides', 'title' => 'Add/Edit Asset'],
    'vendor-rides-drivers'       => ['file' => 'pages/vendor/rides-drivers.php',             'auth' => true,  'vendor' => true, 'module' => 'rides', 'title' => 'Drivers'],
    'vendor-rides-reports'       => ['file' => 'pages/vendor/rides-reports.php',             'auth' => true,  'vendor' => true, 'module' => 'rides', 'title' => 'Ride Reports'],
    'vendor-rides-settings'      => ['file' => 'pages/vendor/rides-settings.php',            'auth' => true,  'vendor' => true, 'module' => 'rides', 'title' => 'Ride Settings'],

    // -------- DRIVER APP (auth + 'rides' module) --------
    'driver-dashboard'           => ['file' => 'pages/driver/dashboard.php',                 'auth' => true,  'module' => 'rides', 'title' => 'Driver Dashboard'],
    'driver-ride'                => ['file' => 'pages/driver/ride.php',                      'auth' => true,  'module' => 'rides', 'title' => 'Active Ride'],
    'driver-shift'               => ['file' => 'pages/driver/shift.php',                     'auth' => true,  'module' => 'rides', 'title' => 'Shift'],
    'driver-earnings'            => ['file' => 'pages/driver/earnings.php',                  'auth' => true,  'module' => 'rides', 'title' => 'My Earnings'],
    'driver-profile'             => ['file' => 'pages/driver/profile.php',                   'auth' => true,  'module' => 'rides', 'title' => 'Driver Profile'],
    'driver-kyc'                 => ['file' => 'pages/driver/kyc.php',                       'auth' => true,  'module' => 'rides', 'title' => 'KYC Documents'],
    'driver-kyc-upload'          => ['file' => 'pages/driver/kyc-upload.php',                'auth' => true,  'raw' => true],

    // -------- ADMIN (auth + admin) --------
    'admin-rides'                => ['file' => 'pages/admin/rides.php',                      'auth' => true,  'admin' => true, 'title' => 'Rides Console'],
    'admin-ride-applications'    => ['file' => 'pages/admin/ride-applications.php',          'auth' => true,  'admin' => true, 'title' => 'Ride Applications'],
    'admin-kyc-review'           => ['file' => 'pages/admin/kyc-review.php',                 'auth' => true,  'admin' => true, 'title' => 'KYC Review'],
    'admin-rides-providers'      => ['file' => 'pages/admin/rides-providers.php',            'auth' => true,  'admin' => true, 'title' => 'Ride Providers'],
    'admin-rides-analytics'      => ['file' => 'pages/admin/rides-analytics.php',            'auth' => true,  'admin' => true, 'title' => 'Ride Analytics'],
    'admin-rides-disputes'       => ['file' => 'pages/admin/rides-disputes.php',             'auth' => true,  'admin' => true, 'title' => 'Ride Disputes'],

    // -------- PUBLIC APIs (raw JSON) --------
    'api-geocode'                => ['file' => 'pages/api/geocode.php',                      'raw' => true],
    'api-route'                  => ['file' => 'pages/api/route.php',                        'raw' => true],
    'api-ride-estimate'          => ['file' => 'pages/api/ride-estimate.php',                'raw' => true],
    'api-ride-nearby'            => ['file' => 'pages/api/ride-nearby.php',                  'raw' => true],
    'api-ride-book'              => ['file' => 'pages/api/ride-book.php',                    'raw' => true],
    'api-ride-status'            => ['file' => 'pages/api/ride-status.php',                  'raw' => true],
    'api-ride-ping'              => ['file' => 'pages/api/ride-ping.php',                    'auth' => true, 'raw' => true],
    'api-ride-locations'         => ['file' => 'pages/api/ride-locations.php',               'raw' => true],
    'api-ride-dispatch'          => ['file' => 'pages/api/ride-dispatch.php',                'raw' => true],
    'api-ride-accept'            => ['file' => 'pages/api/ride-accept.php',                  'raw' => true],
    'api-ride-decline'           => ['file' => 'pages/api/ride-decline.php',                 'raw' => true],
    'api-ride-classes'           => ['file' => 'pages/api/ride-classes.php',                 'raw' => true],

    // ========== ADMIN ==========
    'admin-dashboard' => ['file' => 'pages/admin/dashboard.php', 'auth' => true, 'admin' => true, 'title' => 'Admin Dashboard'],
    'admin-users' => ['file' => 'pages/admin/users.php', 'auth' => true, 'admin' => true, 'title' => 'Users'],
    'admin-pms' => ['file' => 'pages/admin/pms.php', 'auth' => true, 'admin' => true, 'title' => 'PMS Command Center'],
    'admin-vendors' => ['file' => 'pages/admin/vendors.php', 'auth' => true, 'admin' => true, 'title' => 'Vendors'],
    'admin-properties' => ['file' => 'pages/admin/properties.php', 'auth' => true, 'admin' => true, 'title' => 'Properties'],
    'admin-bookings' => ['file' => 'pages/admin/bookings.php', 'auth' => true, 'admin' => true, 'title' => 'Bookings'],
    'admin-analytics' => ['file' => 'pages/admin/analytics.php', 'auth' => true, 'admin' => true, 'title' => 'Analytics'],
    'admin-settings' => ['file' => 'pages/admin/settings.php', 'auth' => true, 'admin' => true, 'title' => 'Platform Settings'],
    'admin-tenants' => ['file' => 'pages/admin/tenants.php', 'auth' => true, 'admin' => true, 'title' => 'Tenants'],
    'admin-create-tenant' => ['file' => 'pages/admin/create-tenant.php', 'auth' => true, 'admin' => true, 'title' => 'Create Tenant'],
    'admin-system-info' => ['file' => 'pages/admin/system-info.php', 'auth' => true, 'admin' => true, 'title' => 'System Info'],
    'admin-subscriptions' => ['file' => 'pages/admin/subscriptions.php', 'auth' => true, 'admin' => true, 'title' => 'Subscriptions'],
    'admin-payouts' => ['file' => 'pages/admin/payouts.php', 'auth' => true, 'admin' => true, 'title' => 'Payouts'],
    'admin-payments' => ['file' => 'pages/admin/payments.php', 'auth' => true, 'admin' => true, 'title' => 'Payments'],
    'admin-roles' => ['file' => 'pages/admin/roles.php', 'auth' => true, 'admin' => true, 'title' => 'Roles'],
    'admin-audit-logs' => ['file' => 'pages/admin/audit-logs.php', 'auth' => true, 'admin' => true, 'title' => 'Audit Logs'],
    'admin-backup' => ['file' => 'pages/admin/backup.php', 'auth' => true, 'admin' => true, 'title' => 'Backup'],
    'admin-email-templates' => ['file' => 'pages/admin/email-templates.php', 'auth' => true, 'admin' => true, 'title' => 'Email Templates'],
    'admin-translations' => ['file' => 'pages/admin/translations.php', 'auth' => true, 'admin' => true, 'title' => 'Translations'],
    'admin-currencies' => ['file' => 'pages/admin/currencies.php', 'auth' => true, 'admin' => true, 'title' => 'Currencies'],
    'admin-taxes' => ['file' => 'pages/admin/taxes.php', 'auth' => true, 'admin' => true, 'title' => 'Taxes'],
    'admin-cron-jobs' => ['file' => 'pages/admin/cron-jobs.php', 'auth' => true, 'admin' => true, 'title' => 'Cron Jobs'],
    'admin-queue-monitor' => ['file' => 'pages/admin/queue-monitor.php', 'auth' => true, 'admin' => true, 'title' => 'Queue Monitor'],
    'admin-cache-manager' => ['file' => 'pages/admin/cache-manager.php', 'auth' => true, 'admin' => true, 'title' => 'Cache Manager'],
    'admin-booking-detail' => ['file' => 'pages/admin/booking-detail.php', 'auth' => true, 'admin' => true, 'title' => 'Booking Details'],
    'admin-bookings-timeline' => ['file' => 'pages/admin/booking-timeline.php', 'auth' => true, 'admin' => true, 'raw' => true],
    'admin-vendor-settlements' => ['file' => 'pages/admin/vendor-settlements.php', 'auth' => true, 'admin' => true, 'title' => 'Vendor Settlements'],
    'admin-channel-sync' => ['file' => 'pages/admin/channel-sync.php', 'auth' => true, 'admin' => true, 'title' => 'Channel Sync'],
    'admin-analytics-global' => ['file' => 'pages/admin/analytics-global.php', 'auth' => true, 'admin' => true, 'title' => 'Global Analytics'],
    'admin-transfer-ops' => ['file' => 'pages/admin/transfer-ops.php', 'auth' => true, 'admin' => true, 'title' => 'Transfer Ops'],
    'admin-support-tickets' => ['file' => 'pages/admin/support-tickets.php', 'auth' => true, 'admin' => true, 'title' => 'Support Tickets'],
    'admin-restaurant-detail' => ['file' => 'pages/admin/restaurant-detail.php', 'auth' => true, 'admin' => true, 'title' => 'Restaurants Detail'],
    'admin-restaurants' => ['file' => 'pages/admin/restaurants.php', 'auth' => true, 'admin' => true, 'title' => 'Restaurants'],
    'admin-restaurant-sales' => ['file' => 'pages/admin/restaurant-sales.php', 'auth' => true, 'admin' => true, 'title' => 'Restaurant Sales'],
    'admin-restaurant-payouts' => ['file' => 'pages/admin/restaurant-payouts.php', 'auth' => true, 'admin' => true, 'title' => 'Restaurants Payouts'],
    'admin-restaurant-form' => ['file' => 'pages/admin/restaurant-form.php', 'auth' => true, 'admin' => true, 'title' => 'Register Restaurants '],
    'admin-restaurant-delete' => ['file' => 'pages/admin/restaurant-delete.php', 'auth' => true, 'admin' => true, 'title' => 'Delete Restaurants'],
    'admin-restaurant-vendors' => ['file' => 'pages/admin/restaurant-vendors.php', 'auth' => true, 'admin' => true, 'title' => 'Restaurants Vendors'],

    // ========== ADMIN — MICE ==========
    'admin-mice'           => ['file' => 'pages/admin/mice.php',           'auth' => true, 'admin' => true, 'title' => 'MICE Console'],
    'admin-mice-analytics' => ['file' => 'pages/admin/mice-analytics.php', 'auth' => true, 'admin' => true, 'title' => 'MICE Analytics'],
    'admin-mice-rfp-print' => ['file' => 'pages/admin/mice-rfp-print.php', 'auth' => true, 'admin' => true, 'raw' => true],

    // ========== ADMIN — TOUR OPERATORS ==========
    'admin-tour-operators' => ['file' => 'pages/admin/tour-operators.php', 'auth' => true, 'admin' => true, 'title' => 'Tour Operators'],
    'admin-tour-packages'  => ['file' => 'pages/admin/tour-packages.php',  'auth' => true, 'admin' => true, 'title' => 'Tour Packages'],
    'admin-tour-bookings'  => ['file' => 'pages/admin/tour-bookings.php',  'auth' => true, 'admin' => true, 'title' => 'Tour Bookings'],
    'admin-tour-reviews'   => ['file' => 'pages/admin/tour-reviews.php',   'auth' => true, 'admin' => true, 'title' => 'Tour Reviews'],

    // ========== ADMIN — CTO ==========
    'admin-cto-applications' => ['file' => 'pages/admin/cto-applications.php', 'auth' => true, 'admin' => true, 'title' => 'CTO Applications'],
    'admin-cto-curation'     => ['file' => 'pages/admin/cto-curation.php',     'auth' => true, 'admin' => true, 'title' => 'CTO Curation'],

    // ========== TOUR OPERATORS — PAYMENT + VOUCHER + ANALYTICS ==========
    'tour-booking-pay'      => ['file' => 'pages/tour-booking-pay.php',      'title' => 'Pay for Tour'],
    'tour-booking-voucher'  => ['file' => 'pages/tour-booking-voucher.php',  'title' => 'Tour Voucher'],

    // API — extended tour search
    'api-search-tours' => ['file' => 'pages/api/search-tours.php', 'raw' => true],

    // ========== API ENDPOINTS (raw) ==========
    'api-properties' => ['file' => 'pages/api/properties.php', 'raw' => true],
    'api-search' => ['file' => 'pages/api/search.php', 'raw' => true],
    'api-cities' => ['file' => 'pages/api/cities.php', 'raw' => true],
    'api-destinations-search' => ['file' => 'pages/api/destinations-search.php', 'raw' => true],
    'api-wishlist' => ['file' => 'pages/api/wishlist.php', 'auth' => true, 'raw' => true],
    'api-bookings' => ['file' => 'pages/api/bookings.php', 'auth' => true, 'raw' => true],
    'api-rampex-webhook' => ['file' => 'pages/api/rampex-webhook.php', 'raw' => true],
    'api-availability' => ['file' => 'pages/api/availability.php', 'raw' => true],
    'api-pricing' => ['file' => 'pages/api/pricing.php', 'raw' => true],
    'api-notifications' => ['file' => 'pages/api/notifications.php', 'auth' => true, 'raw' => true],
    'api-auth' => ['file' => 'pages/api/auth.php', 'raw' => true],
    'api-webhooks' => ['file' => 'pages/api/webhooks.php', 'raw' => true],
    'api-payment-webhook' => ['file' => 'pages/api/payment-webhook.php', 'raw' => true],
    'api-reports' => ['file' => 'pages/api/reports.php', 'auth' => true, 'raw' => true],
    'api-analytics' => ['file' => 'pages/api/analytics.php', 'auth' => true, 'raw' => true],
    'api-export' => ['file' => 'pages/api/export.php', 'auth' => true, 'raw' => true],
    'api-import' => ['file' => 'pages/api/import.php', 'auth' => true, 'raw' => true],
    'api-settings' => ['file' => 'pages/api/settings.php', 'auth' => true, 'raw' => true],
    'api-compare' => ['file' => 'pages/api/compare.php', 'raw' => true],
    'api-currency' => ['file' => 'pages/api/currency.php', 'raw' => true],
    'api-mobile' => ['file' => 'pages/api/mobile.php', 'raw' => true],
    'api-chat' => ['file' => 'pages/api/chat.php', 'auth' => true, 'raw' => true],
    'api-payment' => ['file' => 'pages/api/payment.php', 'auth' => true, 'raw' => true],
    'api-social' => ['file' => 'pages/api/social.php', 'auth' => true, 'raw' => true],
    'api-loyalty' => ['file' => 'pages/api/loyalty.php', 'auth' => true, 'raw' => true],
    'api-concierge' => ['file' => 'pages/api/concierge.php', 'auth' => true, 'raw' => true],
    'api-virtual-tours' => ['file' => 'pages/api/virtual-tours.php', 'raw' => true],
    'api-webrtc' => ['file' => 'pages/api/webrtc.php', 'auth' => true, 'raw' => true],
    'api-ar' => ['file' => 'pages/api/ar.php', 'raw' => true],
    'api-blockchain' => ['file' => 'pages/api/blockchain.php', 'raw' => true],
    'api-iot' => ['file' => 'pages/api/iot.php', 'auth' => true, 'raw' => true],
    'api-robot' => ['file' => 'pages/api/robot.php', 'raw' => true],
    'api-carbon' => ['file' => 'pages/api/carbon.php', 'raw' => true],
    'api-insurance' => ['file' => 'pages/api/insurance.php', 'raw' => true],
    'api-pms-live' => ['file' => 'pages/api/pms-live.php', 'auth' => true, 'raw' => true],
    'api-pos' => ['file' => 'pages/api/pos.php', 'auth' => true, 'raw' => true],
    'api-frontdesk' => ['file' => 'pages/api/frontdesk.php', 'auth' => true, 'raw' => true],
    'api-night-audit' => ['file' => 'pages/api/night-audit.php', 'auth' => true, 'raw' => true],
    'api-concierge-requests' => ['file' => 'pages/api/concierge-requests.php', 'auth' => true, 'raw' => true],
    'api-menu' => ['file' => 'pages/api/menu.php', 'raw' => true],
    'api-qr' => ['file' => 'pages/api/qr.php', 'raw' => true],
    'api-track-view' => ['file' => 'pages/api/track-view.php', 'auth' => true, 'raw' => true],
    'api-vendor-balance' => ['file' => 'pages/api/vendor-balance.php', 'raw' => true],
    'api-search-cities' => ['file' => 'pages/api/search-cities.php', 'raw' => true],
    'api-resolve-images' => ['file' => 'pages/api/resolve-images.php', 'auth' => true, 'raw' => true],
    'api-home-loadmore' => ['file' => 'pages/api/home-loadmore.php', 'auth' => true, 'raw' => true],
    'api-mice-availability' => ['file' => 'pages/api/mice-availability.php', 'raw' => true],
    'api-event-registrations' => ['file' => 'pages/api/event-registrations.php', 'raw' => true],
    'api-event-checkin' => ['file' => 'pages/api/event-checkin.php', 'raw' => true],
    'api-event-pay-init'    => ['file' => 'pages/api/event-pay-init.php',    'raw' => true],
    'api-event-pay-webhook' => ['file' => 'pages/api/event-pay-webhook.php', 'raw' => true],
    'api-upload-tour' => ['file' => 'pages/api/upload-tour.php', 'raw' => true],
    'api-create-vendor-ticket'=> ['file' => 'pages/api/create-vendor-ticket.php', 'raw' => true],
    'api-vendor-notify' => ['file' => 'pages/api/vendor-notify.php', 'auth' => false],
   
    // -- Vehicle Transfers & Flight Tracking --
    'api-flight-status'     => ['file' => 'pages/api/flight-status.php', 'raw' => true],
    'api-transfer-location' => ['file' => 'pages/api/transfer-location.php', 'raw' => true],

    // ========== MICE — RAW HANDLERS ==========
    'mice-rfp-submit' => ['file' => 'pages/mice-rfp-submit.php', 'raw' => true],
    'mice-rfp-reply'  => ['file' => 'pages/mice-rfp-reply.php',  'raw' => true],
    'mice-booking-accept' => ['file' => 'pages/mice-booking-accept.php', 'raw' => true],

    // ========== CRON JOBS (raw) ==========
    'cron-process-emails' => ['file' => 'pages/cron/process-emails.php', 'raw' => true],
    'cron-sync-channels' => ['file' => 'pages/cron/sync-channels.php', 'raw' => true],
    'cron-check-rates' => ['file' => 'pages/cron/check-rates.php', 'raw' => true],
    'cron-expire-points' => ['file' => 'pages/cron/expire-points.php', 'raw' => true],
    'cron-night-audit' => ['file' => 'pages/cron/night-audit.php', 'raw' => true],
    'cron-expire-event-payments' => ['file' => 'pages/cron/expire-event-payments.php', 'raw' => true],
];

// ============================================
// RESOLVE ROUTE
// ============================================
if (!isset($routes[$page])) {
    http_response_code(404);
    $page = '404';
    $route = $routes['404'];
} else {
    $route = $routes[$page];
}

$route = array_merge([
    'auth'       => false,
    'guest_only' => false,
    'vendor'     => false,
    'admin'      => false,
    'staff'      => false,
    'raw'        => false,
    'module'     => null,
    'title'      => 'Revenda',
], $route);

// ============================================
// ACCESS CONTROL
// ============================================

// 1. Authentication required
if ($route['auth'] && !isLoggedIn()) {
    if ($isAjax || $isApi) {
        http_response_code(401);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'requires_login' => true]);
        ob_end_flush();
        exit;
    }
    $redirect = urlencode($_SERVER['REQUEST_URI'] ?? '/');
    redirect('/?page=login&redirect=' . $redirect);
    exit;
}

// 2. Guest-only pages
if ($route['guest_only'] && isLoggedIn()) {
    redirect('/?page=dashboard');
    exit;
}

// 3. Vendor access
if ($route['vendor'] && !isVendor()) {
    if ($isAjax || $isApi) {
        http_response_code(403);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Vendor access required']);
        ob_end_flush();
        exit;
    }
    setMessage('Vendor access required', 'error');
    redirect('/?page=dashboard');
    exit;
}

// 4. Admin access
if ($route['admin'] && !isAdmin()) {
    if ($isAjax || $isApi) {
        http_response_code(403);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Admin access required']);
        ob_end_flush();
        exit;
    }
    setMessage('Admin access required', 'error');
    redirect('/?page=dashboard');
    exit;
}

// 5. Staff access
if ($route['staff'] && !isStaff() && !isVendor() && !isAdmin()) {
    if ($isAjax || $isApi) {
        http_response_code(403);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Staff access required']);
        ob_end_flush();
        exit;
    }
    setMessage('Staff access required', 'error');
    redirect('/?page=dashboard');
    exit;
}

// 6. Module access (from platform_modules / vendor_enabled_modules)
if (!empty($route['module']) && function_exists('vendorHasModule')) {
    $__moduleVendor = getVendor();
    if ($__moduleVendor) {
        $__moduleVendorId = (int)$__moduleVendor['id'];
        if (!vendorHasModule($__moduleVendorId, $route['module'])) {
            if ($isAjax || $isApi) {
                http_response_code(403);
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => false,
                    'message' => 'This feature requires a higher plan.',
                    'requires_upgrade' => true,
                    'module' => $route['module'],
                ]);
                ob_end_flush();
                exit;
            }
            setMessage('This feature is not enabled on your current plan. Upgrade to access.', 'error');
            redirect('/?page=vendor-subscription');
            exit;
        }
    }
}

// ============================================
// RENDER PAGE
// ============================================
$pageFile = $basePath . '/' . $route['file'];

if (!file_exists($pageFile)) {
    http_response_code(500);
    error_log("Route file missing: {$route['file']} for page '{$page}'");

    if (ENVIRONMENT === 'development') {
        exit("Route file missing: {$route['file']}");
    }

    if ($page !== '404' && file_exists($basePath . '/pages/404.php')) {
        http_response_code(404);
        include $basePath . '/pages/404.php';
        if (ob_get_level() > 0) ob_end_flush();
        exit;
    }

    exit('Page not available.');
}

$pageTitle = $route['title'];
$isRaw = !empty($route['raw']) || $isApi || $isCron;

try {
    if ($isRaw) {
        require $pageFile;
    } else {
        $headerFile = $basePath . '/includes/header.php';
        $footerFile = $basePath . '/includes/footer.php';

        if (file_exists($headerFile)) {
            require_once $headerFile;
        }

        require $pageFile;

        if (file_exists($footerFile)) {
            require_once $footerFile;
        }
    }
} catch (Throwable $e) {
    error_log("Page render failed: {$route['file']} - " . $e->getMessage()
              . ' @ ' . $e->getFile() . ':' . $e->getLine());

    if (ENVIRONMENT === 'development') {
        if (ob_get_level() > 0) ob_end_clean();
        echo '<pre style="background:#1a202c;color:#f56565;padding:20px;font-family:monospace;overflow:auto;">';
        echo "<strong>Fatal error while rendering {$page}</strong>\n\n";
        echo htmlspecialchars($e->getMessage()) . "\n\n";
        echo htmlspecialchars($e->getFile()) . ' on line ' . $e->getLine() . "\n\n";
        echo htmlspecialchars($e->getTraceAsString());
        echo '</pre>';
        exit;
    }

    http_response_code(500);
    if (ob_get_level() > 0) ob_end_clean();

    echo '<!doctype html><html><head><meta charset="utf-8"><title>Something went wrong</title>'
       . '<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f7fafc;color:#1a202c}'
       . '.box{text-align:center;padding:40px;max-width:500px}h1{font-size:3rem;margin:0 0 10px;color:#0066ff}p{color:#718096}</style></head>'
       . '<body><div class="box"><h1>500</h1><p>Something went wrong on our end. Please try again later.</p>'
       . '<p><a href="/" style="color:#0066ff;text-decoration:none;font-weight:600">Go Home</a></p></div></body></html>';
}

// Automatic age-only cleanup (runs at most once every 15 minutes)
(static function (): void {
    $lockFile = '/home/betvrtjcje/revenda.tanzaquest.com/cache/.auto_sweep.lock';
    if (is_file($lockFile) && (time() - (@filemtime($lockFile) ?: 0)) < 900) {
        return;
    }
    @file_put_contents($lockFile, (string)time());

    $now     = time();
    $targets = [
        ['dir' => '/home/betvrtjcje/.cagefs/tmp',                 'maxAge' => 28800, 'prefix' => 'sess_'],
        ['dir' => '/home/betvrtjcje/revenda_sessions',             'maxAge' => 28800, 'prefix' => 'sess_'],
        ['dir' => '/home/betvrtjcje/revenda.tanzaquest.com/cache', 'maxAge' => 14400, 'prefix' => null],
    ];
    $skip = ['.', '..', '.htaccess', 'index.html', 'index.php', '.auto_sweep.lock'];

    foreach ($targets as $t) {
        if (!is_dir($t['dir']) || !is_readable($t['dir'])) {
            continue;
        }
        $iter = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($t['dir'], FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach ($iter as $entry) {
            /** @var SplFileInfo $entry */
            $name = $entry->getFilename();
            if (in_array($name, $skip, true) || $entry->isLink()) {
                continue;
            }
            if ($entry->isDir()) {
                @rmdir($entry->getPathname());
                continue;
            }
            if ($t['prefix'] !== null && !str_starts_with($name, $t['prefix'])) {
                continue;
            }
            if (($now - $entry->getMTime()) >= $t['maxAge']) {
                @unlink($entry->getPathname());
            }
        }
    }
})();

// ============================================
// FLUSH OUTPUT
// ============================================
if (ob_get_level() > 0) {
    ob_end_flush();
}