<?php

use App\Http\Controllers\{
    // Dashboard
    DashboardController,
    HomeController,
    
    // Core Modules
    RoomController,
    RoomTypeController,
    ReservationController,
    GuestController,
    InOutController,
    
    // Services
    ServiceController,
    
    
    // POS & Menu
    PosController,
    MenuCategoryController,
    MenuItemController,
    
    // Maintenance
    MaintenanceController,
    TechnicianController,
    
    // Housekeeping
    HousekeepingController,
    
    // Inventory & Purchasing
    InventoryController,
    PurchaseOrderController,
    
    // HR & Staff
    StaffController,
    PayrollController,
    AttendanceController,
    LeaveController,
    LeaveReportController,
    
    // Documents
    DocumentController,
    
    // Surveys
    SurveyController,
    SurveyResponseController,
    SurveyInvitationController,
    
    // Reports
    ReportController,
    
    // Other
    CategoryController,
    ContactController,
    ExpenseController,
    InstallmentPlanController,
    SettingController,
    // ProfileController,
    BackupController,
    NotificationController,
    // AuditLogController,
    // HelpController,
    AnnouncementController,
    FeedbackController,
    TaskController,
    MaintenanceRequestController
};
use App\Http\Controllers\PublicBookingController;
use App\Http\Controllers\ContactRequestController;
use App\Http\Controllers\Accounting\AccountingController;
use App\Http\Controllers\Admin\SuperAdminController;
use App\Http\Controllers\Admin\ContactRequestAdminController;
use App\Http\Controllers\Payments\PesapalPaymentController;
use App\Models\{Survey, SurveyInvitation};
use Illuminate\Support\Facades\{Route, Auth};
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

// ==================== PUBLIC ROUTES ====================
Route::get('/', function () {
    return view('welcome');
})->name('welcome');

// Public marketing / booking pages (templates 1–6 per hotel — see hotels.public_booking_template)
Route::get('/book/{slug}', [PublicBookingController::class, 'show'])
    ->name('public.booking.show');
Route::post('/book/{slug}/reserve', [PublicBookingController::class, 'reserve'])
    ->middleware('throttle:15,1')
    ->name('public.booking.reserve');

// Marketing site contact form
Route::post('/contact-requests', [ContactRequestController::class, 'store'])
    ->middleware('throttle:6,1')
    ->name('contact-requests.store');

Route::get('/test', function() {
    return response()->json([
        'message' => 'Test route is working!',
        'timestamp' => now()->toDateTimeString()
    ]);
})->name('test');

// ==================== AUTHENTICATION ====================
Route::group(['namespace' => 'App\Http\Controllers\Auth'], function () {
    Route::get('login', 'LoginController@showLoginForm')->name('login');
    Route::post('login', 'LoginController@login');
    Route::post('logout', 'LoginController@logout')->name('logout');
    Route::get('password/reset', 'ForgotPasswordController@showLinkRequestForm')->name('password.request');
    Route::post('password/email', 'ForgotPasswordController@sendResetLinkEmail')->name('password.email');
    Route::get('password/reset/{token}', 'ResetPasswordController@showResetForm')->name('password.reset');
    Route::post('password/reset', 'ResetPasswordController@reset')->name('password.update');
});

// ==================== SUBSCRIPTION ROUTES ====================
Route::middleware(['auth'])->prefix('subscription')->name('subscription.')->group(function () {
    Route::get('/required', function() { return view('subscription.required'); })->name('required');
    Route::get('/inactive', function() { return view('subscription.inactive'); })->name('inactive');
    Route::get('/expired', function() { return view('subscription.expired'); })->name('expired');
    Route::get('/renew', function() { return view('subscription.renew'); })->name('renew');
    Route::get('/upgrade', function() { return view('subscription.upgrade'); })->name('upgrade');
    Route::get('/details', function() { return view('subscription.details'); })->name('details');
});

// ==================== HOME & DASHBOARD ====================
Route::get('/home', [DashboardController::class, 'index'])->middleware('auth')->name('home');
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('auth')->name('dashboard');

// ==================== API ROUTES ====================
Route::prefix('api')->name('api.')->group(function () {
    // Theme settings
    Route::get('/theme-settings', function() {
        try {
            $settingsService = app(\App\Services\SettingsService::class);
            return response()->json([
                'success' => true,
                'variables' => $settingsService->getThemeCssVariables(),
                'mode' => $settingsService->getThemeMode(),
                'hotelName' => $settingsService->getHotelName()
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    })->name('theme-settings');
    
    // Reports
    Route::get('/reports/performance-data', [ReportController::class, 'kpiData'])->name('reports.performance-data');
    
    // Inventory
    Route::get('/inventory/low-stock-count', [InventoryController::class, 'lowStockCount'])->name('inventory.low-stock-count');
    
    // Guest
    Route::post('/check-guest-email', [GuestController::class, 'checkEmail'])->name('check-guest-email');
    
    // Categories (API)
    Route::get('/categories', [CategoryController::class, 'apiIndex'])->name('categories.api.index');
    Route::get('/categories/status', [CategoryController::class, 'apiStatus'])->name('categories.api.status');
    Route::get('/categories/inventory', [CategoryController::class, 'apiInventory'])->name('categories.api.inventory');
    Route::post('/categories', [CategoryController::class, 'store'])->name('categories.api.store');
    Route::put('/categories/{id}', [CategoryController::class, 'apiUpdate'])->name('categories.api.update');
    Route::delete('/categories/{id}', [CategoryController::class, 'apiDestroy'])->name('categories.api.destroy');
    
    // Staff HR AJAX — must run authenticated (session + hotel context + module access)
    Route::middleware(['auth', 'check.module.access:hr'])->group(function () {
        Route::prefix('staff')->name('staff.')->group(function () {
            Route::get('/departments/list', [StaffController::class, 'getDepartmentsApi'])->name('departments.list');
            Route::get('/positions/list', [StaffController::class, 'getPositionsApi'])->name('positions.list');
            Route::post('/departments', [StaffController::class, 'storeDepartmentApi'])->name('departments.store');
            Route::post('/positions', [StaffController::class, 'storePositionApi'])->name('positions.store');
        });
    });


    
    // Surveys
    Route::get('/surveys/chart-data', [SurveyController::class, 'getChartData'])->name('surveys.chart-data');
    
    // POS
    Route::get('/today-stats', [PosController::class, 'getTodayStats'])->name('today-stats');
});

// ==================== SUPER ADMIN ROUTES ====================
Route::prefix('super-admin')->name('super.admin.')->group(function () {
    // Guest routes for login
    Route::middleware('guest')->group(function () {
        Route::get('/login', [SuperAdminController::class, 'showLoginForm'])->name('login');
        Route::post('/login', [SuperAdminController::class, 'login'])->name('login.post');
    });

    // Protected super admin routes
    Route::middleware(['auth', \App\Http\Middleware\SuperAdminMiddleware::class])->group(function () {
        Route::get('/dashboard', [SuperAdminController::class, 'dashboard'])->name('dashboard');
        Route::get('/', [SuperAdminController::class, 'dashboard'])->name('index');

        // Guest / public website template — assign each hotel to one of four themes (must stay above generic /hotels/{hotel} patterns)
        Route::get('/website-assignments', [SuperAdminController::class, 'websiteAssignments'])->name('website-assignments.index');
        Route::get('/website-assignments/{id}/edit', [SuperAdminController::class, 'websiteAssignmentEdit'])->name('website-assignments.edit');
        Route::put('/website-assignments/{id}', [SuperAdminController::class, 'updateWebsiteAssignment'])->name('website-assignments.update');
        
        // Hotels Management
        Route::prefix('hotels')->name('hotels.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'hotels'])->name('index');
            Route::get('/{id}/data', [SuperAdminController::class, 'getHotelData'])->name('data');
            Route::get('/{id}/users', [SuperAdminController::class, 'getHotelUsers'])->name('users');
            Route::post('/users', [SuperAdminController::class, 'storeHotelUser'])->name('users.store');
            Route::put('/{hotelId}/users/{userId}', [SuperAdminController::class, 'updateHotelUser'])->name('users.update');
            Route::delete('/{hotelId}/users/{userId}', [SuperAdminController::class, 'deleteHotelUser'])->name('users.delete');
            Route::post('/users/reset-password/{id}', [SuperAdminController::class, 'resetUserPassword'])->name('users.reset-password');
            Route::post('/{id}/subscription', [SuperAdminController::class, 'updateSubscription'])->name('subscription.update');
            Route::get('/{id}/subscription/history', [SuperAdminController::class, 'getSubscriptionHistory'])->name('subscription.history');
            Route::get('/create', [SuperAdminController::class, 'createHotel'])->name('create');
            Route::post('/store', [SuperAdminController::class, 'storeHotel'])->name('store');
            Route::get('/{hotel}', [SuperAdminController::class, 'showHotel'])->name('show');
            Route::get('/{hotel}/edit', [SuperAdminController::class, 'editHotel'])->name('edit');
            Route::put('/{hotel}', [SuperAdminController::class, 'updateHotel'])->name('update');
            Route::delete('/{hotel}', [SuperAdminController::class, 'deleteHotel'])->name('delete');
            Route::get('/export', [SuperAdminController::class, 'exportHotels'])->name('export');
        });
        
        // Subscriptions Management
        Route::prefix('subscriptions')->name('subscriptions.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'subscriptions'])->name('index');
            Route::get('/expiring', [SuperAdminController::class, 'expiringSubscriptions'])->name('expiring');
            Route::get('/export', [SuperAdminController::class, 'exportSubscriptions'])->name('export');
            Route::post('/send-reminders', [SuperAdminController::class, 'sendSubscriptionRemindersNow'])->name('send-reminders');
            Route::get('/{id}', [SuperAdminController::class, 'getSubscription'])->name('get');
            Route::get('/{id}/edit', [SuperAdminController::class, 'editSubscription'])->name('edit');
            Route::post('/', [SuperAdminController::class, 'storeSubscription'])->name('store');
            Route::put('/{id}', [SuperAdminController::class, 'updateSubscription'])->name('update');
            Route::delete('/{id}', [SuperAdminController::class, 'deleteSubscription'])->name('delete');
            Route::get('/{id}/renewal-info', [SuperAdminController::class, 'getRenewalInfo'])->name('renewal-info');
            Route::post('/{id}/renew', [SuperAdminController::class, 'renewSubscription'])->name('renew');
            Route::get('/{id}/upgrade-info', [SuperAdminController::class, 'getUpgradeInfo'])->name('upgrade-info');
            Route::post('/{id}/upgrade', [SuperAdminController::class, 'upgradeSubscription'])->name('upgrade');
            Route::post('/{id}/suspend', [SuperAdminController::class, 'suspendSubscription'])->name('suspend');
            Route::post('/{id}/activate', [SuperAdminController::class, 'activateSubscription'])->name('activate');
        });
        
        // Payments Management
        Route::prefix('payments')->name('payments.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'payments'])->name('index');
            Route::get('/export', [SuperAdminController::class, 'exportPayments'])->name('export');
            Route::get('/{id}', [SuperAdminController::class, 'getPayment'])->name('get');
            Route::post('/', [SuperAdminController::class, 'storePayment'])->name('store');
            Route::put('/{id}/status', [SuperAdminController::class, 'updatePaymentStatus'])->name('status.update');
            Route::post('/{id}/pesapal/checkout', [PesapalPaymentController::class, 'initiateCheckout'])->name('pesapal.checkout');
        });
        
        // Users Management
        Route::prefix('users')->name('users.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'users'])->name('index');
            Route::get('/create', [SuperAdminController::class, 'createUser'])->name('create');
            Route::post('/', [SuperAdminController::class, 'storeUser'])->name('store');
            Route::get('/{id}', [SuperAdminController::class, 'showUser'])->name('show');
            Route::get('/{id}/edit', [SuperAdminController::class, 'editUser'])->name('edit');
            Route::put('/{id}', [SuperAdminController::class, 'updateUser'])->name('update');
            Route::delete('/{id}', [SuperAdminController::class, 'deleteUser'])->name('delete');
            Route::post('/{id}/reset-password', [SuperAdminController::class, 'resetUserPassword'])->name('reset-password');
            Route::post('/import', [SuperAdminController::class, 'importUsers'])->name('import');
            Route::post('/bulk-delete', [SuperAdminController::class, 'bulkDeleteUsers'])->name('bulk-delete');
            Route::get('/export', [SuperAdminController::class, 'exportUsers'])->name('export');
        });
        
        // Reports
        Route::prefix('reports')->name('reports.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'reports'])->name('index');
            Route::post('/generate', [SuperAdminController::class, 'generateReport'])->name('generate');
            Route::get('/export', [SuperAdminController::class, 'exportReport'])->name('export');
            Route::get('/financial', [SuperAdminController::class, 'financialReports'])->name('financial');
            Route::get('/subscription', [SuperAdminController::class, 'subscriptionReports'])->name('subscription');
            Route::get('/activity', [SuperAdminController::class, 'activityReports'])->name('activity');
        });
        
        // Profile
        Route::prefix('profile')->name('profile.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'profile'])->name('index');
            Route::put('/', [SuperAdminController::class, 'updateProfile'])->name('update');
            Route::put('/password', [SuperAdminController::class, 'updatePassword'])->name('password');
        });
        
        // Settings
        Route::prefix('settings')->name('settings.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'settings'])->name('index');
            Route::post('/', [SuperAdminController::class, 'updateSettings'])->name('update');
            Route::post('/test-pesapal', [SuperAdminController::class, 'testPesapalConnection'])->name('test-pesapal');
            Route::get('/system', [SuperAdminController::class, 'systemSettings'])->name('system');
            Route::post('/system', [SuperAdminController::class, 'updateSystemSettings'])->name('system.update');
            Route::get('/backup', [SuperAdminController::class, 'backupSettings'])->name('backup');
            Route::post('/backup/create', [SuperAdminController::class, 'createBackup'])->name('backup.create');
            Route::get('/backup/download/{filename}', [SuperAdminController::class, 'downloadBackup'])->name('backup.download');
        });
        
        // Export
        Route::prefix('export')->name('export.')->group(function () {
            Route::get('/hotels', [SuperAdminController::class, 'exportHotels'])->name('hotels');
            Route::get('/users', [SuperAdminController::class, 'exportUsers'])->name('users');
            Route::get('/subscriptions', [SuperAdminController::class, 'exportSubscriptions'])->name('subscriptions');
            Route::get('/payments', [SuperAdminController::class, 'exportPayments'])->name('payments');
            Route::get('/reports', [SuperAdminController::class, 'exportReport'])->name('reports');
        });
        
        // Analytics
        Route::prefix('analytics')->name('analytics.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'analytics'])->name('index');
            Route::get('/revenue', [SuperAdminController::class, 'revenueAnalytics'])->name('revenue');
            Route::get('/growth', [SuperAdminController::class, 'growthAnalytics'])->name('growth');
        });
        
        // Maintenance
        Route::prefix('maintenance')->name('maintenance.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'maintenance'])->name('index');
            Route::post('/clear-cache', [SuperAdminController::class, 'clearCache'])->name('clear-cache');
            Route::post('/optimize', [SuperAdminController::class, 'optimize'])->name('optimize');
            Route::get('/logs', [SuperAdminController::class, 'viewLogs'])->name('logs');
            Route::get('/logs/download/{log}', [SuperAdminController::class, 'downloadLog'])->name('logs.download');
        });
        
        // API Keys
        Route::prefix('api-keys')->name('api-keys.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'apiKeys'])->name('index');
            Route::post('/generate', [SuperAdminController::class, 'generateApiKey'])->name('generate');
            Route::delete('/{key}', [SuperAdminController::class, 'revokeApiKey'])->name('revoke');
        });
        
        // Notifications
        Route::prefix('notifications')->name('notifications.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'notifications'])->name('index');
            Route::post('/send', [SuperAdminController::class, 'sendNotification'])->name('send');
            Route::post('/broadcast', [SuperAdminController::class, 'broadcastNotification'])->name('broadcast');
        });
        
        // Audit Logs
        Route::prefix('audit-logs')->name('audit-logs.')->group(function () {
            Route::get('/', [SuperAdminController::class, 'auditLogs'])->name('index');
            Route::get('/export', [SuperAdminController::class, 'exportAuditLogs'])->name('export');
        });

        // Contact Requests (inbox for marketing site form submissions)
        Route::prefix('contact-requests')->name('contact-requests.')->group(function () {
            Route::get('/', [ContactRequestAdminController::class, 'index'])->name('index');
            Route::get('/export', [ContactRequestAdminController::class, 'export'])->name('export');
            Route::get('/{id}', [ContactRequestAdminController::class, 'show'])
                ->whereNumber('id')
                ->name('show');
            Route::put('/{id}/status', [ContactRequestAdminController::class, 'updateStatus'])
                ->whereNumber('id')
                ->name('status.update');
            Route::delete('/{id}', [ContactRequestAdminController::class, 'destroy'])
                ->whereNumber('id')
                ->name('destroy');
        });

        // Logout
        Route::post('/logout', [SuperAdminController::class, 'logout'])->name('logout');
    });
});

// Public callback/IPN routes for payment gateway status sync
Route::match(['get', 'post'], '/payments/pesapal/callback', [PesapalPaymentController::class, 'callback'])->name('payments.pesapal.callback');
Route::match(['get', 'post'], '/payments/pesapal/ipn', [PesapalPaymentController::class, 'ipn'])->name('payments.pesapal.ipn');

// ==================== PROTECTED ROUTES (NON-PREFIXED) ====================
Route::middleware(['auth', 'package.access'])->group(function () {
    
    // ==================== ROOMS ====================
    Route::middleware(['check.module:rooms'])->group(function () {
        Route::resource('rooms', RoomController::class);
        Route::prefix('rooms')->name('rooms.')->group(function () {
            Route::get('/status/{status}', [RoomController::class, 'byStatus'])->name('byStatus');
            Route::get('/floor-plan', [RoomController::class, 'floorPlan'])->name('floor-plan');
            Route::post('/{room}/update-status', [RoomController::class, 'updateStatus'])->name('update-status');
            Route::get('/import-export', [RoomController::class, 'importExport'])->name('import-export');
            Route::get('/export', [RoomController::class, 'export'])->name('export');
            Route::post('/import', [RoomController::class, 'import'])->name('import');
            Route::get('/download-template', [RoomController::class, 'downloadTemplate'])->name('download-template');
            Route::post('/bulk-actions', [RoomController::class, 'bulkActions'])->name('bulk-actions');
            Route::get('/{room}/maintenance', [RoomController::class, 'roomMaintenance'])->name('maintenance');
        });
        
        // ==================== ROOM TYPES ====================
        Route::resource('room-types', RoomTypeController::class);
    });
    
    // ==================== RESERVATIONS ====================
    Route::middleware(['check.module:reservations'])->group(function () {
        Route::resource('reservations', ReservationController::class);
        Route::prefix('reservations')->name('reservations.')->group(function () {
            Route::post('/{reservation}/cancel', [ReservationController::class, 'cancel'])->name('cancel');
            Route::post('/{reservation}/confirm', [ReservationController::class, 'confirm'])->name('confirm');
            Route::post('/{reservation}/checkin', [ReservationController::class, 'checkin'])->name('checkin');
            Route::post('/{reservation}/checkout', [ReservationController::class, 'checkout'])->name('checkout');
            Route::get('/calendar', [ReservationController::class, 'calendar'])->name('calendar');
            Route::get('/upcoming', [ReservationController::class, 'upcoming'])->name('upcoming');
            Route::get('/import-export', [ReservationController::class, 'importExport'])->name('import-export');
            Route::get('/export', [ReservationController::class, 'export'])->name('export');
            Route::post('/import', [ReservationController::class, 'import'])->name('import');
            Route::get('/download-template', [ReservationController::class, 'downloadTemplate'])->name('download-template');
            Route::post('/bulk-action', [ReservationController::class, 'bulkAction'])->name('bulk-action');
            Route::get('/room-details/{id}', [ReservationController::class, 'getRoomDetails'])->name('room-details');
            Route::get('/{reservation}/generate-invoice', [ReservationController::class, 'generateInvoice'])->name('generate-invoice');
            Route::get('/{reservation}/invoice', [ReservationController::class, 'showInvoice'])->name('invoice');
            Route::get('/{reservation}/record-payment', [ReservationController::class, 'recordPayment'])->name('record-payment');
            Route::post('/{reservation}/store-payment', [ReservationController::class, 'storePayment'])->name('store-payment');
        });
        
        // ==================== INSTALLMENT PLANS ====================
        Route::prefix('installments')->name('installments.')->group(function () {
            Route::get('/create/{reservation}', [InstallmentPlanController::class, 'create'])->name('create');
            Route::post('/store/{reservation}', [InstallmentPlanController::class, 'store'])->name('store');
            Route::post('/{installment}/payment', [InstallmentPlanController::class, 'recordPayment'])->name('payment');
        });
    });
    
    // ==================== GUESTS ====================
    Route::middleware(['check.module:guests'])->group(function () {
        Route::resource('guests', GuestController::class);
        // Fix: Add global route for check-guest-email to match Blade usage
        Route::post('/check-guest-email', [GuestController::class, 'checkEmail'])->name('check-guest-email');
        Route::prefix('guests')->name('guests.')->group(function () {
            Route::post('/check-existing', [GuestController::class, 'checkExisting'])->name('check-existing');
            Route::post('/check-email', [GuestController::class, 'checkEmail'])->name('check-email');
            Route::get('/search', [GuestController::class, 'search'])->name('search');
            Route::get('/export', [GuestController::class, 'export'])->name('export');
            Route::post('/import', [GuestController::class, 'import'])->name('import');
            Route::get('/blacklist', [GuestController::class, 'blacklistIndex'])->name('blacklist.index');
            Route::post('/{guest}/blacklist', [GuestController::class, 'blacklist'])->name('blacklist');
            Route::post('/{guest}/remove-from-blacklist', [GuestController::class, 'removeFromBlacklist'])->name('removeFromBlacklist');
            Route::get('/{guest}/activities', [GuestController::class, 'activities'])->name('activities');
            Route::post('/{guest}/log-activity', [GuestController::class, 'logActivity'])->name('log-activity');
            Route::post('/{guest}/update-type', [GuestController::class, 'updateGuestType'])->name('update-type');
            Route::get('/{guest}/history', [GuestController::class, 'history'])->name('history');
        });
    });
    
    // ==================== FRONT DESK ====================
    Route::middleware(['auth', 'check.module.access:front_desk'])->prefix('inout')->name('inout.')->group(function () {
        Route::get('/', [InOutController::class, 'index'])->name('index');
        Route::get('/walkin', [InOutController::class, 'walkinPage'])->name('walkin.page');
        Route::get('/checkin', [InOutController::class, 'checkinPage'])->name('checkin.page');
        Route::post('/checkin', [InOutController::class, 'checkin'])->name('checkin.submit');
        Route::post('/checkin-walkin', [InOutController::class, 'checkinWalkin'])->name('checkin.walkin');
        Route::post('/checkin-walkin-enhanced', [InOutController::class, 'checkinWalkinEnhanced'])->name('checkin.walkin.enhanced');
        Route::post('/checkout', [InOutController::class, 'checkout'])->name('checkout.submit');
        Route::post('/process-payment', [InOutController::class, 'processPayment'])->name('process-payment');
        Route::post('/process-checkin', [InOutController::class, 'processCheckin'])->name('process-checkin');
        Route::post('/confirm-reservation', [InOutController::class, 'confirmReservation'])->name('confirm-reservation');
        Route::post('/process-checkout', [InOutController::class, 'processCheckout'])->name('process-checkout');
        Route::post('/process-walkin-checkin', [InOutController::class, 'processWalkinCheckin'])->name('process-walkin-checkin');
        Route::get('/available-rooms', [InOutController::class, 'getAvailableRooms'])->name('available-rooms');
        Route::get('/reservation/{id}/details', [InOutController::class, 'getReservationDetails'])->name('reservation.details');
        Route::get('/reservation/{id}/invoice-preview', [InOutController::class, 'getInvoicePreview'])->name('invoice.preview');
        Route::get('/current-guests', [InOutController::class, 'getCurrentGuests'])->name('current-guests');
        Route::get('/expected-checkins', [InOutController::class, 'getExpectedCheckins'])->name('expected-checkins');
        Route::get('/expected-checkouts', [InOutController::class, 'getExpectedCheckouts'])->name('expected-checkouts');
        Route::get('/history', [InOutController::class, 'getHistory'])->name('history');
        Route::get('/stats', [InOutController::class, 'getStats'])->name('stats');
        Route::get('/room-status-summary', [InOutController::class, 'getRoomStatusSummary'])->name('room-status-summary');
        Route::get('/receipt/{reservationId}', [InOutController::class, 'getReceipt'])->name('receipt');
        Route::get('/consolidated-invoice/{reservationId}', [InOutController::class, 'showConsolidatedInvoice'])->name('consolidated-invoice');
        Route::get('/walkin-receipt/{reservationId}', [InOutController::class, 'getWalkinReceipt'])->name('walkin-receipt');
        Route::get('/invoice/{reservationId}', [InOutController::class, 'getInvoice'])->name('invoice');
        Route::post('/import', [InOutController::class, 'import'])->name('import');
        Route::post('/export-data', [InOutController::class, 'exportData'])->name('export-data');
        Route::post('/cancel-reservation', [InOutController::class, 'cancelReservation'])->name('cancel');
    });
    
    // ==================== SIMPLIFIED SERVICES ROUTES (ONE SECTION ONLY) ====================
    Route::middleware(['auth', 'check.module.access:hotel_services'])->prefix('services')->name('services.')->group(function () {
        
        // BASIC CRUD for services
        Route::get('/', [ServiceController::class, 'index'])->name('index');
        Route::get('/create', [ServiceController::class, 'create'])->name('create');
        Route::post('/', [ServiceController::class, 'store'])->name('store');
        Route::get('/{id}', [ServiceController::class, 'show'])->whereNumber('id')->name('show');
        Route::get('/{id}/edit', [ServiceController::class, 'edit'])->whereNumber('id')->name('edit');
        Route::put('/{id}', [ServiceController::class, 'update'])->whereNumber('id')->name('update');
        Route::delete('/{id}', [ServiceController::class, 'destroy'])->whereNumber('id')->name('destroy');
        
        // REQUEST ROUTES - These are the ones your blade files need
        Route::get('/requests', [ServiceController::class, 'showRequests'])->name('requests.index');
        Route::get('/requests/{id}', [ServiceController::class, 'showRequest'])->name('requests.show');
        Route::put('/requests/{id}/status', [ServiceController::class, 'updateStatus'])->name('requests.update-status');
        Route::delete('/requests/{id}', [ServiceController::class, 'destroyRequest'])->name('requests.destroy');
        
        // ASSIGN ROUTE
        Route::post('/assign', [ServiceController::class, 'assign'])->name('assign');
        
        // SEARCH ROUTES - For AJAX typeahead
        Route::get('/search/services', [ServiceController::class, 'searchServices'])->name('search');
        Route::get('/search/guests', [ServiceController::class, 'searchGuests'])->name('search-guests');
        
        // SERVICE DETAILS API
        Route::get('/{id}/details', [ServiceController::class, 'getServiceDetails'])->name('details');
        
        // CATEGORY ROUTES
        Route::prefix('categories')->name('categories.')->group(function () {
            Route::get('/', [ServiceController::class, 'categoriesIndex'])->name('index');
            Route::post('/', [ServiceController::class, 'storeCategory'])->name('store');
            Route::get('/{id}/edit', [ServiceController::class, 'editCategory'])->name('edit');
            Route::put('/{id}', [ServiceController::class, 'updateCategory'])->name('update');
            Route::delete('/{id}', [ServiceController::class, 'deleteCategory'])->name('delete');
            Route::post('/{id}/toggle', [ServiceController::class, 'toggleCategoryStatus'])->name('toggle');
            Route::get('/{id}', [ServiceController::class, 'showCategory'])->name('show');
        });
    });
    
    // ==================== HOUSEKEEPING ====================
    Route::middleware(['auth', 'check.module.access:housekeeping'])->group(function () {
        Route::resource('housekeeping', HousekeepingController::class)->only(['index']);
        Route::prefix('housekeeping')->name('housekeeping.')->group(function () {
            Route::get('/', [HousekeepingController::class, 'index'])->name('index');
            Route::get('/floor-plan', [HousekeepingController::class, 'floorPlan'])->name('floor-plan');
            Route::get('/schedule', [HousekeepingController::class, 'schedule'])->name('schedule');
            Route::get('/report', [HousekeepingController::class, 'report'])->name('report');
            Route::get('/staff-management', [HousekeepingController::class, 'staff'])->name('staff');
            Route::put('/rooms/{id}', [HousekeepingController::class, 'updateRoom'])->name('rooms.update');
            Route::post('/rooms/quick-update', [HousekeepingController::class, 'quickUpdateRoom'])->name('rooms.quick-update');
            Route::get('/rooms/{id}', [HousekeepingController::class, 'getRoom'])->name('rooms.show');
            Route::post('/tasks', [HousekeepingController::class, 'storeTask'])->name('tasks.store');
            Route::put('/tasks/{id}', [HousekeepingController::class, 'updateTask'])->name('tasks.update');
            Route::get('/tasks/{id}', [HousekeepingController::class, 'getTask'])->name('tasks.show');
            Route::delete('/tasks/{id}', [HousekeepingController::class, 'destroyTask'])->name('tasks.destroy');
            Route::post('/staff-management', [HousekeepingController::class, 'storeStaff'])->name('staff.store');
            Route::put('/staff-management/{id}', [HousekeepingController::class, 'updateStaff'])->name('staff.update');
            Route::delete('/staff-management/{id}', [HousekeepingController::class, 'destroyStaff'])->name('staff.destroy');
            Route::post('/notes', [HousekeepingController::class, 'storeNote'])->name('notes.store');
            Route::delete('/notes/{id}', [HousekeepingController::class, 'destroyNote'])->name('notes.destroy');
            Route::post('/bulk-update', [HousekeepingController::class, 'bulkUpdate'])->name('bulk-update');
            Route::get('/export', [HousekeepingController::class, 'export'])->name('export');
        });
    });
    
    // ==================== INVENTORY ====================
    Route::middleware(['auth', 'check.module.access:inventory'])->group(function () {
        Route::resource('inventory', InventoryController::class)->whereNumber('inventory');
        Route::prefix('inventory')->name('inventory.')->group(function () {
            Route::get('/low-stock', [InventoryController::class, 'lowStock'])->name('low-stock');
            Route::get('/transactions', [InventoryController::class, 'transactions'])->name('transactions');
            Route::get('/transactions/item/{item}', [InventoryController::class, 'itemTransactions'])->name('transactions.item');
            Route::post('/quick-adjust', [InventoryController::class, 'quickAdjust'])->name('quick-adjust');
            Route::post('/issue-stock', [InventoryController::class, 'issueStock'])->name('issue-stock');
            Route::get('/issues', [InventoryController::class, 'issues'])->name('issues');
            Route::post('/issues/{issue}/approve', [InventoryController::class, 'approveIssue'])->name('issues.approve');
            Route::post('/issues/{issue}/issue', [InventoryController::class, 'postIssue'])->name('issues.issue');
            Route::post('/issues/{issue}/reject', [InventoryController::class, 'rejectIssue'])->name('issues.reject');
            Route::get('/analytics', [InventoryController::class, 'analytics'])->name('analytics');
            Route::get('/report', [InventoryController::class, 'report'])->name('report');
            Route::get('/import-export', [InventoryController::class, 'importExport'])->name('import-export');
            Route::post('/import', [InventoryController::class, 'import'])->name('import');
            Route::post('/export', [InventoryController::class, 'export'])->name('export');
            Route::post('/export/pdf', [InventoryController::class, 'exportPdf'])->name('export.pdf');
            Route::post('/export/excel', [InventoryController::class, 'exportExcel'])->name('export.excel');
            Route::post('/export/csv', [InventoryController::class, 'exportCsv'])->name('export.csv');
            Route::get('/download-template', [InventoryController::class, 'downloadTemplate'])->name('download-template');
            Route::get('/categories', [InventoryController::class, 'categories'])->name('categories');
            Route::post('/categories', [InventoryController::class, 'storeCategory'])->name('categories.store');
            Route::get('/order/{item}', [InventoryController::class, 'showOrderForm'])->name('order.form');
            Route::post('/process-order', [InventoryController::class, 'processOrder'])->name('process-order');
            Route::post('/{inventoryItem}/adjust', [InventoryController::class, 'adjust'])->name('adjust');
            Route::post('/{inventoryItem}/order', [InventoryController::class, 'order'])->name('order');
            Route::post('/{inventoryItem}/toggle-status', [InventoryController::class, 'toggleStatus'])->name('toggle-status');
            Route::get('/{inventoryItem}/details', [InventoryController::class, 'getItemDetails'])->name('details');
            Route::post('/bulk-delete', [InventoryController::class, 'bulkDelete'])->name('bulk-delete');
            Route::post('/bulk-update', [InventoryController::class, 'bulkUpdate'])->name('bulk-update');
            Route::post('/bulk-export', [InventoryController::class, 'bulkExport'])->name('bulk-export');
            Route::get('/reports/summary', [InventoryController::class, 'summaryReport'])->name('reports.summary');
            Route::get('/reports/value', [InventoryController::class, 'valueReport'])->name('reports.value');
            Route::get('/reports/movement', [InventoryController::class, 'movementReport'])->name('reports.movement');
            Route::get('/low-stock-count', [InventoryController::class, 'lowStockCount'])->name('low-stock-count');
        });

        // ==================== CATEGORIES ====================
        Route::prefix('categories')->name('categories.')->group(function () {
            Route::get('/', [CategoryController::class, 'index'])->name('index');
        });
        
        // ==================== PURCHASE ORDERS ====================
        Route::resource('purchase-orders', PurchaseOrderController::class);
        Route::prefix('purchase-orders')->name('purchase-orders.')->group(function () {
            Route::post('/{purchaseOrder}/status', [PurchaseOrderController::class, 'updateStatus'])->name('update-status');
            Route::post('/{purchaseOrder}/receive-delivery', [PurchaseOrderController::class, 'receiveDelivery'])->name('receive-delivery');
            Route::post('/{purchaseOrder}/return-rejected', [PurchaseOrderController::class, 'returnRejected'])->name('return-rejected');
            Route::post('/{purchaseOrder}/approve', [PurchaseOrderController::class, 'approve'])->name('approve');
            Route::post('/{purchaseOrder}/reject', [PurchaseOrderController::class, 'reject'])->name('reject');
            Route::post('/{purchaseOrder}/complete', [PurchaseOrderController::class, 'complete'])->name('complete');
            Route::post('/{purchaseOrder}/cancel', [PurchaseOrderController::class, 'cancel'])->name('cancel');
            Route::get('/{purchaseOrder}/print', [PurchaseOrderController::class, 'print'])->name('print');
            Route::get('/{purchaseOrder}/pdf', [PurchaseOrderController::class, 'pdf'])->name('pdf');
            Route::get('/{purchaseOrder}/email', [PurchaseOrderController::class, 'sendEmail'])->name('email');
            Route::get('/draft', [PurchaseOrderController::class, 'draft'])->name('draft');
            Route::get('/pending', [PurchaseOrderController::class, 'pending'])->name('pending');
            Route::get('/approved', [PurchaseOrderController::class, 'approved'])->name('approved');
            Route::get('/completed', [PurchaseOrderController::class, 'completed'])->name('completed');
            Route::get('/cancelled', [PurchaseOrderController::class, 'cancelled'])->name('cancelled');
            Route::get('/import-export', [PurchaseOrderController::class, 'importExport'])->name('import-export');
            Route::post('/import', [PurchaseOrderController::class, 'import'])->name('import');
            Route::get('/export', [PurchaseOrderController::class, 'export'])->name('export');
            Route::get('/export/pdf', [PurchaseOrderController::class, 'exportPdf'])->name('export.pdf');
            Route::get('/export/excel', [PurchaseOrderController::class, 'exportExcel'])->name('export.excel');
            Route::get('/export/csv', [PurchaseOrderController::class, 'exportCsv'])->name('export.csv');
            Route::get('/download-template', [PurchaseOrderController::class, 'downloadTemplate'])->name('download-template');
            Route::get('/reports/summary', [PurchaseOrderController::class, 'summaryReport'])->name('reports.summary');
            Route::get('/reports/vendor', [PurchaseOrderController::class, 'vendorReport'])->name('reports.vendor');
            Route::get('/reports/items', [PurchaseOrderController::class, 'itemsReport'])->name('reports.items');
            Route::get('/reports/analytics', [PurchaseOrderController::class, 'analytics'])->name('reports.analytics');
            Route::post('/bulk-delete', [PurchaseOrderController::class, 'bulkDelete'])->name('bulk-delete');
            Route::post('/bulk-approve', [PurchaseOrderController::class, 'bulkApprove'])->name('bulk-approve');
            Route::post('/bulk-reject', [PurchaseOrderController::class, 'bulkReject'])->name('bulk-reject');
            Route::post('/bulk-complete', [PurchaseOrderController::class, 'bulkComplete'])->name('bulk-complete');
            Route::post('/bulk-cancel', [PurchaseOrderController::class, 'bulkCancel'])->name('bulk-cancel');
        });
    });
    
    // ==================== STAFF (HR) ====================
    Route::middleware(['auth', 'check.module.access:hr'])->group(function () {
        // Numeric {staff} only so paths like /staff/payroll are not treated as show('payroll')
        Route::resource('staff', StaffController::class)->whereNumber('staff');
        Route::prefix('staff')->name('staff.')->group(function () {
            Route::get('/import-export', [StaffController::class, 'importExport'])->name('import-export');
            Route::post('/import', [StaffController::class, 'import'])->name('import');
            Route::get('/export', [StaffController::class, 'export'])->name('export');
            Route::get('/download-template', [StaffController::class, 'downloadTemplate'])->name('download-template');
            Route::get('/backup', [StaffController::class, 'backup'])->name('backup');
            Route::get('/departments', [StaffController::class, 'departmentsIndex'])->name('departments');
            Route::get('/positions', [StaffController::class, 'positionsIndex'])->name('positions');
            Route::get('/{staff}/history', [StaffController::class, 'history'])->name('history');
            Route::get('/{staff}/leaves', [StaffController::class, 'leaves'])->name('leaves');
            Route::get('/{staff}/leave-balance', [StaffController::class, 'leaveBalance'])->name('leave-balance');
            Route::post('/bulk-delete', [StaffController::class, 'bulkDelete'])->name('bulk-delete');
            Route::post('/bulk-deactivate', [StaffController::class, 'bulkDeactivate'])->name('bulk-deactivate');
            Route::post('/bulk-export', [StaffController::class, 'bulkExport'])->name('bulk-export');
            
            // Departments CRUD
            Route::get('/departments/create', [StaffController::class, 'createDepartment'])->name('departments.create');
            Route::post('/departments', [StaffController::class, 'storeDepartment'])->name('departments.store');
            Route::get('/departments/{id}/edit', [StaffController::class, 'editDepartment'])->name('departments.edit');
            Route::put('/departments/{id}', [StaffController::class, 'updateDepartment'])->name('departments.update');
            Route::delete('/departments/{id}', [StaffController::class, 'destroyDepartment'])->name('departments.destroy');
            
            // Positions CRUD
            Route::get('/positions/create', [StaffController::class, 'createPosition'])->name('positions.create');
            Route::post('/positions', [StaffController::class, 'storePosition'])->name('positions.store');
            Route::get('/positions/{id}/edit', [StaffController::class, 'editPosition'])->name('positions.edit');
            Route::put('/positions/{id}', [StaffController::class, 'updatePosition'])->name('positions.update');
            Route::delete('/positions/{id}', [StaffController::class, 'destroyPosition'])->name('positions.destroy');
            
            // Staff Reports
            Route::prefix('reports')->name('reports.')->group(function () {
                Route::get('/turnover', [StaffController::class, 'turnoverReport'])->name('turnover');
                Route::get('/attendance', [StaffController::class, 'attendanceReport'])->name('attendance');
                Route::get('/department', [StaffController::class, 'departmentReport'])->name('department');
                Route::get('/salary', [StaffController::class, 'salaryReport'])->name('salary');
                Route::get('/leave', [StaffController::class, 'leaveReport'])->name('leave');
            });
            
            // API Routes for AJAX
            Route::get('/api/departments/list', [StaffController::class, 'apiDepartments'])->name('api.departments.list');
            Route::post('/api/departments', [StaffController::class, 'apiStoreDepartment'])->name('api.departments.store');
            Route::get('/api/positions/list', [StaffController::class, 'apiPositions'])->name('api.positions.list');
            Route::post('/api/positions', [StaffController::class, 'apiStorePosition'])->name('api.positions.store');
            Route::prefix('payroll')->name('payroll.')->group(function () {
                Route::get('/', [PayrollController::class, 'index'])->name('index');
                Route::get('/create', [PayrollController::class, 'create'])->name('create');
                Route::post('/', [PayrollController::class, 'store'])->name('store');
                Route::get('/{payroll}', [PayrollController::class, 'show'])->name('show');
                Route::post('/{payroll}/mark-paid', [PayrollController::class, 'markPaid'])->name('mark-paid');
            });
        });
        
        // ==================== ATTENDANCE ====================
        Route::prefix('attendance')->name('attendance.')->group(function () {
            Route::get('/record', [AttendanceController::class, 'record'])->name('record');
            Route::post('/store', [AttendanceController::class, 'store'])->name('store');
            Route::post('/bulk-store', [AttendanceController::class, 'bulkStore'])->name('bulk-store');
            Route::get('/report', [AttendanceController::class, 'report'])->name('report');
            Route::get('/edit/{id}', [AttendanceController::class, 'edit'])->name('edit');
            Route::put('/update/{id}', [AttendanceController::class, 'update'])->name('update');
            Route::delete('/destroy/{id}', [AttendanceController::class, 'destroy'])->name('destroy');
            Route::get('/leave-calendar', [AttendanceController::class, 'leaveCalendar'])->name('leave-calendar');
            Route::get('/leave-summary', [AttendanceController::class, 'leaveSummary'])->name('leave-summary');
        });
        
        // ==================== LEAVES ====================
        Route::resource('leaves', LeaveController::class);
        Route::prefix('leaves')->name('leaves.')->group(function () {
            Route::get('/my-leaves', [LeaveController::class, 'myLeaves'])->name('my-leaves');
            Route::get('/calendar', [LeaveController::class, 'calendar'])->name('calendar');
            Route::get('/balance', [LeaveController::class, 'balance'])->name('balance');
            Route::get('/pending', [LeaveController::class, 'pending'])->name('pending');
            Route::get('/approved', [LeaveController::class, 'approved'])->name('approved');
            Route::get('/rejected', [LeaveController::class, 'rejected'])->name('rejected');
            Route::get('/cancelled', [LeaveController::class, 'cancelled'])->name('cancelled');
            Route::post('/{leave}/approve', [LeaveController::class, 'approve'])->name('approve');
            Route::post('/{leave}/reject', [LeaveController::class, 'reject'])->name('reject');
            Route::post('/{leave}/cancel', [LeaveController::class, 'cancel'])->name('cancel');
            Route::get('/import-export', [LeaveController::class, 'importExport'])->name('import-export');
            Route::post('/import', [LeaveController::class, 'import'])->name('import');
            Route::get('/export', [LeaveController::class, 'export'])->name('export');
            Route::get('/download-template', [LeaveController::class, 'downloadTemplate'])->name('download-template');
            Route::post('/bulk-approve', [LeaveController::class, 'bulkApprove'])->name('bulk-approve');
            Route::post('/bulk-reject', [LeaveController::class, 'bulkReject'])->name('bulk-reject');
            Route::post('/bulk-delete', [LeaveController::class, 'bulkDelete'])->name('bulk-delete');
            
            // Leave Reports
            Route::prefix('reports')->name('reports.')->group(function () {
                Route::get('/monthly', [LeaveController::class, 'reportMonthly'])->name('monthly');
                Route::get('/department', [LeaveController::class, 'reportDepartment'])->name('department');
                Route::get('/summary', [LeaveReportController::class, 'summary'])->name('summary');
                Route::get('/staff/{staff}', [LeaveReportController::class, 'staff'])->name('staff');
                Route::get('/export/{type}', [LeaveReportController::class, 'exportReport'])->name('leaves.reports.export');
            });
        });
    });
    
    // ==================== DOCUMENTS ====================
    Route::middleware(['check.module:documents'])->group(function () {
        Route::resource('documents', DocumentController::class);
        Route::prefix('documents')->name('documents.')->group(function () {
            // Core operations
            Route::get('/download/{document}', [DocumentController::class, 'download'])->name('download');
            Route::get('/preview/{document}', [DocumentController::class, 'preview'])->name('preview');
            Route::post('/upload', [DocumentController::class, 'upload'])->name('upload');
            Route::post('/upload-multiple', [DocumentController::class, 'uploadMultiple'])->name('upload-multiple');
            Route::post('/fetch-url', [DocumentController::class, 'fetchFromUrl'])->name('fetch-url');
            Route::post('/filter', [DocumentController::class, 'filter'])->name('filter');
            Route::get('/search', [DocumentController::class, 'search'])->name('search');
            
            // Folders
            Route::post('/folders', [DocumentController::class, 'createFolder'])->name('folders.create');
            Route::get('/folders/tree', [DocumentController::class, 'folderTree'])->name('folders.tree');
            Route::get('/folders/{folder}', [DocumentController::class, 'viewFolder'])->name('folders.view');
            Route::put('/folders/{folder}', [DocumentController::class, 'updateFolder'])->name('folders.update');
            Route::delete('/folders/{folder}', [DocumentController::class, 'deleteFolder'])->name('folders.delete');
            
            // Sharing
            Route::post('/{document}/share', [DocumentController::class, 'share'])->name('share');
            Route::get('/{document}/shares', [DocumentController::class, 'getShares'])->name('get-shares');
            Route::delete('/{document}/share/{user}', [DocumentController::class, 'revokeShare'])->name('revoke-share');
            Route::post('/{document}/share/link', [DocumentController::class, 'createShareLink'])->name('create-share-link');
            Route::get('/shared/{token}', [DocumentController::class, 'accessShared'])->name('access-shared');
            
            // Versions
            Route::post('/{document}/versions', [DocumentController::class, 'createVersion'])->name('versions.create');
            Route::get('/{document}/versions', [DocumentController::class, 'getVersions'])->name('versions');
            Route::get('/{document}/versions/{version}', [DocumentController::class, 'downloadVersion'])->name('versions.download');
            Route::post('/{document}/restore/{version}', [DocumentController::class, 'restoreVersion'])->name('versions.restore');
            
            // Comments
            Route::post('/{document}/comments', [DocumentController::class, 'addComment'])->name('comments.add');
            Route::get('/{document}/comments', [DocumentController::class, 'getComments'])->name('comments');
            Route::delete('/comments/{comment}', [DocumentController::class, 'deleteComment'])->name('comments.delete');
            
            // Tags
            Route::post('/{document}/tags', [DocumentController::class, 'addTags'])->name('tags.add');
            Route::delete('/{document}/tags/{tag}', [DocumentController::class, 'removeTag'])->name('tags.remove');
            Route::get('/tags', [DocumentController::class, 'getPopularTags'])->name('tags.popular');
            
            // Categories and Types
            Route::get('/categories', [DocumentController::class, 'getCategories'])->name('categories');
            Route::post('/categories', [DocumentController::class, 'createCategory'])->name('categories.create');
            Route::put('/categories/{category}', [DocumentController::class, 'updateCategory'])->name('categories.update');
            Route::delete('/categories/{category}', [DocumentController::class, 'deleteCategory'])->name('categories.delete');
            Route::get('/types', [DocumentController::class, 'getTypes'])->name('types');
            
            // Entity search
            Route::get('/search-entities/{type}', [DocumentController::class, 'searchEntities'])->name('search-entities');
            
            // Stats and listings
            Route::get('/statistics', [DocumentController::class, 'getStatistics'])->name('statistics');
            Route::get('/recent', [DocumentController::class, 'getRecent'])->name('recent');
            Route::get('/popular', [DocumentController::class, 'getPopular'])->name('popular');
            
            // Trash
            Route::get('/trash', [DocumentController::class, 'trash'])->name('trash');
            Route::post('/{document}/restore', [DocumentController::class, 'restore'])->name('restore');
            Route::delete('/{document}/force-delete', [DocumentController::class, 'forceDestroy'])->name('force-delete');
            Route::post('/empty-trash', [DocumentController::class, 'emptyTrash'])->name('empty-trash');
            
            // My documents and shared
            Route::get('/my-documents', [DocumentController::class, 'myDocuments'])->name('my-documents');
            Route::get('/shared-with-me', [DocumentController::class, 'sharedWithMe'])->name('shared-with-me');
            
            // Bulk operations
            Route::post('/bulk-delete', [DocumentController::class, 'bulkDelete'])->name('bulk-delete');
            Route::post('/bulk-download', [DocumentController::class, 'bulkDownload'])->name('bulk-download');
            Route::post('/bulk-move', [DocumentController::class, 'bulkMove'])->name('bulk-move');
            Route::post('/bulk-share', [DocumentController::class, 'bulkShare'])->name('bulk-share');
            
            // Public view - this should be last as it's a wildcard
            Route::get('/{document}/public-view', [DocumentController::class, 'publicView'])->name('public.view');
        });
    });
    
    // ==================== MAINTENANCE ====================
    Route::middleware(['check.module:maintenance'])->group(function () {
        Route::resource('maintenance', MaintenanceController::class);
        Route::resource('maintenance-requests', MaintenanceRequestController::class);
        Route::resource('technicians', TechnicianController::class);

        // Additional maintenance routes
        Route::prefix('maintenance')->name('maintenance.')->group(function () {
            // Core maintenance routes
            Route::get('/room/{room}', [MaintenanceController::class, 'byRoom'])->name('by-room');
            Route::get('/schedule', [MaintenanceController::class, 'schedule'])->name('schedule');
            Route::post('/{maintenance}/start', [MaintenanceController::class, 'start'])->name('start');
            Route::post('/{maintenance}/complete', [MaintenanceController::class, 'complete'])->name('complete');
            
            // Export routes
            Route::get('/export', [MaintenanceController::class, 'export'])->name('export');
            Route::get('/export/data', [MaintenanceController::class, 'exportData'])->name('export.data');
            
            // Bulk actions
            Route::post('/bulk-action', [MaintenanceController::class, 'bulkAction'])->name('bulk-action');
            
            // Statistics and reports
            Route::get('/statistics', [MaintenanceController::class, 'statistics'])->name('statistics');
            Route::get('/reports', [MaintenanceController::class, 'reports'])->name('reports');
            
            // Assign technician
            Route::post('/{maintenance}/assign', [MaintenanceController::class, 'assignTechnician'])->name('assign');
            
            // Update status
            Route::patch('/{maintenance}/status', [MaintenanceController::class, 'updateStatus'])->name('update-status');
            
            // Add comment
            Route::post('/{maintenance}/comment', [MaintenanceController::class, 'addComment'])->name('add-comment');
            
            // Upload images
            Route::post('/{maintenance}/images', [MaintenanceController::class, 'uploadImages'])->name('upload-images');
            Route::delete('/{maintenance}/images/{image}', [MaintenanceController::class, 'deleteImage'])->name('delete-image');
        });
    });
    
    // ==================== FOOD & BEVERAGE ====================
    Route::middleware(['check.module:food_beverage'])->group(function () {
        // ==================== MENU CATEGORIES ====================
        Route::resource('menu-categories', MenuCategoryController::class);
        
        // ==================== MENU ITEMS ====================
        Route::resource('menu-items', MenuItemController::class);
        Route::prefix('menu-items')->name('menu-items.')->group(function () {
            Route::post('/{id}/toggle-availability', [MenuItemController::class, 'toggleAvailability'])->name('menu-items.toggle-availability');
            Route::get('/category/{categoryId}', [MenuItemController::class, 'getByCategory'])->name('menu-items.by-category');
        });
        
        // ==================== POS ====================
        Route::get('/pos', [PosController::class, 'index'])->name('pos.index');
        Route::post('/pos/orders', [PosController::class, 'store'])->name('pos.orders.store');
        Route::get('/pos/orders', [PosController::class, 'ordersIndex'])->name('pos.orders.index');
        Route::get('/pos/orders/{id}', [PosController::class, 'ordersShow'])->name('pos.orders.show');
        Route::put('/pos/orders/{id}/status', [PosController::class, 'ordersUpdateStatus'])->name('pos.orders.updateStatus');
        Route::get('/pos/orders/{id}/details', [PosController::class, 'getOrderDetails'])->name('pos.orders.details');
        Route::get('/pos/orders/{id}/receipt', [PosController::class, 'getOrderReceipt'])->name('pos.orders.receipt');
        Route::get('/pos/api/today-stats', [PosController::class, 'getTodayStats'])->name('pos.api.today-stats');
    });
    
    // ==================== REPORTS ====================
    Route::middleware(['check.module:reporting'])->prefix('reports')->name('reports.')->group(function () {
        Route::get('/', [ReportController::class, 'index'])->name('index');
        Route::get('/kpi', [ReportController::class, 'kpiData'])->name('kpi');
        Route::get('/refresh-kpi', [ReportController::class, 'refreshKPI'])->name('refresh-kpi');
        Route::post('/generate', [ReportController::class, 'generate'])->name('generate');
        Route::post('/export', [ReportController::class, 'export'])->name('export');
        Route::get('/scheduler', [ReportController::class, 'scheduler'])->name('scheduler');
        Route::get('/templates', [ReportController::class, 'templates'])->name('templates');
        Route::post('/schedule', [ReportController::class, 'scheduleReport'])->name('schedule');
        Route::get('/download-direct', [ReportController::class, 'downloadDirect'])->name('download-direct');
        Route::get('/temp-download/{filename}', [ReportController::class, 'tempDownload'])->name('temp-download');
    });
    
    // ==================== ACCOUNTING ====================
    Route::middleware(['check.module:accounting'])->prefix('accounting')->name('accounting.')->group(function () {
        // Dashboard
        Route::get('/dashboard', [AccountingController::class, 'dashboard'])->name('dashboard');
        Route::get('/', [AccountingController::class, 'dashboard'])->name('index');
        Route::get('/chart-data', [AccountingController::class, 'chartData'])->name('chart-data');
        
        // Chart of Accounts
        Route::get('/chart-of-accounts', [AccountingController::class, 'chartOfAccounts'])->name('chart-of-accounts');
        Route::post('/accounts', [AccountingController::class, 'storeAccount'])->name('accounts.store');
        Route::get('/accounts/{account}', [AccountingController::class, 'showAccount'])->name('accounts.show');
        Route::get('/accounts/{account}/edit', [AccountingController::class, 'editAccount'])->name('accounts.edit');
        Route::put('/accounts/{account}', [AccountingController::class, 'updateAccount'])->name('accounts.update');
        Route::delete('/accounts/{account}', [AccountingController::class, 'destroyAccount'])->name('accounts.destroy');
        
        // Journal Entries
        Route::get('/journal-entries', [AccountingController::class, 'journalEntries'])->name('journal-entries');
        Route::get('/journal-entries/create', [AccountingController::class, 'createJournalEntry'])->name('journal-entries.create');
        Route::post('/journal-entries', [AccountingController::class, 'storeJournalEntry'])->name('journal-entries.store');
        Route::get('/journal-entries/{journalEntry}', [AccountingController::class, 'showJournalEntry'])->name('journal-entries.show');
        Route::get('/journal-entries/{journalEntry}/edit', [AccountingController::class, 'editJournalEntry'])->name('journal-entries.edit');
        Route::put('/journal-entries/{journalEntry}', [AccountingController::class, 'updateJournalEntry'])->name('journal-entries.update');
        Route::delete('/journal-entries/{journalEntry}', [AccountingController::class, 'destroyJournalEntry'])->name('journal-entries.destroy');
        Route::post('/journal-entries/{journalEntry}/post', [AccountingController::class, 'postJournalEntry'])->name('journal-entries.post');
        Route::post('/journal-entries/{journalEntry}/reverse', [AccountingController::class, 'reverseJournalEntry'])->name('journal-entries.reverse');
        Route::post('/journal-entries/template/{templateId}', [AccountingController::class, 'createFromTemplate'])->name('journal-entries.template');
        
        // Reports
        Route::prefix('reports')->name('reports.')->group(function () {
            Route::get('/trial-balance', [AccountingController::class, 'trialBalance'])->name('trial-balance');
            Route::get('/profit-loss', [AccountingController::class, 'profitLoss'])->name('profit-loss');
            Route::get('/balance-sheet', [AccountingController::class, 'balanceSheet'])->name('balance-sheet');
            Route::get('/general-ledger', [AccountingController::class, 'generalLedger'])->name('general-ledger');
        });
        
        // Budgets
        Route::get('/budgets', [AccountingController::class, 'budgets'])->name('budgets');
        Route::post('/budgets', [AccountingController::class, 'storeBudget'])->name('budgets.store');
        Route::get('/budgets/{id}', [AccountingController::class, 'getBudget'])->name('budgets.get');
        Route::get('/budgets/{id}/edit', [AccountingController::class, 'editBudget'])->name('budgets.edit');
        Route::put('/budgets/{budget}', [AccountingController::class, 'updateBudget'])->name('budgets.update');
        Route::delete('/budgets/{id}', [AccountingController::class, 'deleteBudget'])->name('budgets.delete');
        Route::get('/budgets/variance', [AccountingController::class, 'budgetVariance'])->name('budgets.variance');
        
        // Tags
        Route::get('/tags', [AccountingController::class, 'getTags'])->name('tags');
        Route::post('/tags', [AccountingController::class, 'storeTag'])->name('tags.store');
        Route::post('/accounts/{account}/tags', [AccountingController::class, 'assignTags'])->name('accounts.tags');
        
        // Sync Routes
        Route::post('/sync-pos', [AccountingController::class, 'syncPosRevenue'])->name('sync.pos');
        Route::post('/sync-services', [AccountingController::class, 'syncServiceRevenue'])->name('sync.services');
        Route::post('/sync-rooms', [AccountingController::class, 'syncRoomRevenue'])->name('sync.rooms');
        Route::post('/sync-purchase-orders', [AccountingController::class, 'syncPurchaseOrders'])->name('sync.purchase-orders');
        Route::post('/sync-expenses', [AccountingController::class, 'syncExpenses'])->name('sync.expenses');
        Route::post('/sync-payments', [AccountingController::class, 'syncPayments'])->name('sync.payments');
        Route::post('/sync-all', [AccountingController::class, 'syncAll'])->name('sync.all');
        
        // Status endpoints
        Route::get('/sync-status', [AccountingController::class, 'getSyncStatus'])->name('sync.status');
        Route::get('/pending-counts', [AccountingController::class, 'getPendingSyncCounts'])->name('pending-counts');
        
        // Generic module sync
        Route::post('/sync/{module}', [AccountingController::class, 'syncModule'])->name('sync.module');
    });
    
    // ==================== VENDOR ROUTES ====================
    Route::middleware(['check.module:accounting'])->prefix('contacts')->name('contacts.')->middleware(['auth', 'package.access'])->group(function () {
        // Vendor Categories
        Route::get('/vendor-categories', [App\Http\Controllers\AccountingVendorController::class, 'getVendorCategories'])->name('vendor-categories');
        
        // Vendors
        Route::get('/vendors', [App\Http\Controllers\AccountingVendorController::class, 'index'])->name('vendors.index');
        Route::get('/vendors/list', [App\Http\Controllers\AccountingVendorController::class, 'getVendorsApi'])->name('vendors.list');
        Route::post('/vendors', [App\Http\Controllers\AccountingVendorController::class, 'storeVendorApi'])->name('vendors.store');
        Route::get('/vendors/{id}', [App\Http\Controllers\AccountingVendorController::class, 'showVendorApi'])->name('vendors.show');
        Route::get('/vendors/{id}/edit', [App\Http\Controllers\AccountingVendorController::class, 'editVendorApi'])->name('vendors.edit');
        Route::put('/vendors/{id}', [App\Http\Controllers\AccountingVendorController::class, 'updateVendorApi'])->name('vendors.update');
        Route::delete('/vendors/{id}', [App\Http\Controllers\AccountingVendorController::class, 'destroyVendorApi'])->name('vendors.destroy');
    });
    
    // ==================== SURVEYS ====================
    Route::middleware(['check.module:survey'])->prefix('surveys')->name('surveys.')->group(function () {
        Route::get('/chart-data', [SurveyController::class, 'getChartData'])->name('surveys.chart-data');
        Route::post('/{survey}/activate', [SurveyController::class, 'activate'])->name('surveys.activate');
        Route::post('/{survey}/deactivate', [SurveyController::class, 'deactivate'])->name('surveys.deactivate');
        Route::get('/{survey}/responses', [SurveyController::class, 'responses'])->name('surveys.responses');
        Route::post('/bulk-delete', [SurveyController::class, 'bulkDelete'])->name('surveys.bulk-delete');
        Route::post('/bulk-activate', [SurveyController::class, 'bulkActivate'])->name('surveys.bulk-activate');
        Route::post('/bulk-deactivate', [SurveyController::class, 'bulkDeactivate'])->name('surveys.bulk-deactivate');
        Route::post('/send-emails', [SurveyController::class, 'sendEmails'])->name('surveys.send-emails');
    });
    
    // ==================== ANNOUNCEMENTS ====================
    Route::resource('announcements', AnnouncementController::class);
    Route::prefix('announcements')->name('announcements.')->group(function () {
        Route::post('/{announcement}/pin', [AnnouncementController::class, 'pin'])->name('announcements.pin');
        Route::post('/{announcement}/unpin', [AnnouncementController::class, 'unpin'])->name('announcements.unpin');
        Route::post('/{announcement}/acknowledge', [AnnouncementController::class, 'acknowledge'])->name('announcements.acknowledge');
        Route::get('/pinned', [AnnouncementController::class, 'pinned'])->name('announcements.pinned');
    });
    
    // ==================== FEEDBACK ====================
    Route::resource('feedback', FeedbackController::class)->except(['edit', 'update']);
    Route::prefix('feedback')->name('feedback.')->group(function () {
        Route::post('/{feedback}/respond', [FeedbackController::class, 'respond'])->name('feedback.respond');
        Route::post('/{feedback}/resolve', [FeedbackController::class, 'resolve'])->name('feedback.resolve');
        Route::get('/reports', [FeedbackController::class, 'reports'])->name('feedback.reports');
        Route::get('/export', [FeedbackController::class, 'export'])->name('feedback.export');
    });
    
    // ==================== TASKS ====================
    Route::resource('tasks', TaskController::class);
    Route::prefix('tasks')->name('tasks.')->group(function () {
        Route::get('/my-tasks', [TaskController::class, 'myTasks'])->name('tasks.my-tasks');
        Route::post('/{task}/complete', [TaskController::class, 'complete'])->name('tasks.complete');
        Route::post('/{task}/start', [TaskController::class, 'start'])->name('tasks.start');
        Route::post('/{task}/pause', [TaskController::class, 'pause'])->name('tasks.pause');
        Route::post('/{task}/assign', [TaskController::class, 'assign'])->name('tasks.assign');
        Route::post('/{task}/comment', [TaskController::class, 'addComment'])->name('tasks.add-comment');
        Route::get('/calendar', [TaskController::class, 'calendar'])->name('tasks.calendar');
        Route::get('/calendar/events', [TaskController::class, 'calendarEvents'])->name('tasks.calendar-events');
    });
    
    // ==================== NOTIFICATIONS ====================
    Route::prefix('notifications')->name('notifications.')->group(function () {
        Route::get('/', [NotificationController::class, 'index'])->name('notifications.index');
        Route::post('/{notification}/mark-read', [NotificationController::class, 'markAsRead'])->name('notifications.mark-read');
        Route::post('/mark-all-read', [NotificationController::class, 'markAllAsRead'])->name('notifications.mark-all-read');
        Route::delete('/{notification}', [NotificationController::class, 'destroy'])->name('notifications.destroy');
        Route::delete('/clear/all', [NotificationController::class, 'clearAll'])->name('notifications.clear-all');
        Route::get('/unread/count', [NotificationController::class, 'unreadCount'])->name('notifications.unread-count');
        Route::post('/settings', [NotificationController::class, 'updateSettings'])->name('notifications.update-settings');
    });
    
    // ==================== AUDIT LOGS ====================
    // Route::prefix('audit-logs')->name('audit-logs.')->group(function () {
    //     Route::get('/', [AuditLogController::class, 'index'])->name('audit-logs.index');
    //     Route::get('/{log}', [AuditLogController::class, 'show'])->name('audit-logs.show');
    //     Route::get('/export/csv', [AuditLogController::class, 'exportCsv'])->name('audit-logs.export-csv');
    //     Route::get('/export/pdf', [AuditLogController::class, 'exportPdf'])->name('audit-logs.export-pdf');
    //     Route::delete('/clear', [AuditLogController::class, 'clear'])->name('audit-logs.clear');
    //     Route::get('/user/{user}', [AuditLogController::class, 'byUser'])->name('audit-logs.by-user');
    //     Route::get('/entity/{type}/{id}', [AuditLogController::class, 'byEntity'])->name('audit-logs.by-entity');
    // });
    
    // ==================== HELP ====================
    // Route::prefix('help')->name('help.')->group(function () {
    //     Route::get('/', [HelpController::class, 'index'])->name('help.index');
    //     Route::get('/{topic}', [HelpController::class, 'show'])->name('help.show');
    //     Route::get('/search', [HelpController::class, 'search'])->name('help.search');
    //     Route::post('/contact-support', [HelpController::class, 'contactSupport'])->name('help.contact-support');
    //     Route::get('/faq', [HelpController::class, 'faq'])->name('help.faq');
    // });
    
    // ==================== SETTINGS ====================
    Route::middleware(['check.module:settings'])->prefix('settings')->name('settings.')->group(function () {
        Route::get('/', [SettingController::class, 'index'])->name('index');
        Route::post('/bulk-update', [SettingController::class, 'bulkUpdate'])->name('bulk-update');
        Route::post('/save', [SettingController::class, 'save'])->name('save');
        Route::post('/reset', [SettingController::class, 'reset'])->name('reset');
        Route::get('/modules', [SettingController::class, 'modules'])->name('modules');
        Route::get('/notifications', [SettingController::class, 'notifications'])->name('notifications');
        Route::get('/security', [SettingController::class, 'security'])->name('security');
        Route::get('/appearance', [SettingController::class, 'appearance'])->name('appearance');
        Route::post('/appearance/update', [SettingController::class, 'updateAppearance'])->name('update-appearance');
        Route::post('/appearance/logo', [SettingController::class, 'uploadLogo'])->name('upload-logo');
        Route::delete('/appearance/logo', [SettingController::class, 'removeLogo'])->name('remove-logo');
        Route::post('/update-theme', [SettingController::class, 'updateTheme'])->name('update-theme');
        Route::post('/clear-hotel', [SettingController::class, 'clearHotelSelection'])->name('clear-hotel');
        Route::get('/currency', [SettingController::class, 'currency'])->name('currency');
        Route::post('/currency/update', [SettingController::class, 'updateCurrency'])->name('update-currency');
        Route::get('/currency/rate/{currency}', [SettingController::class, 'getCurrencyRate'])->name('currency.rate');
        Route::get('/email', [SettingController::class, 'email'])->name('email');
        Route::post('/email/update', [SettingController::class, 'updateEmail'])->name('update-email');
        Route::post('/test-smtp', [SettingController::class, 'testSmtp'])->name('test-smtp');
        Route::post('/initialize-defaults', [SettingController::class, 'initializeDefaults'])->name('initialize-defaults');
        Route::post('/payments/pay-now', [SettingController::class, 'paySubscriptionNow'])->name('payments.pay-now');
        
        // Backup
        Route::prefix('backup')->name('backup.')->group(function () {
            Route::post('/create', [SettingController::class, 'createBackup'])->name('create');
            Route::get('/list', [SettingController::class, 'listBackups'])->name('list');
            Route::post('/restore', [SettingController::class, 'restoreBackup'])->name('restore');
            Route::delete('/delete/{filename}', [SettingController::class, 'deleteBackup'])->name('delete');
            Route::get('/download/{filename}', [SettingController::class, 'downloadBackup'])->name('download');
        });
        
        // Users (settings)
        Route::prefix('users')->name('users.')->group(function () {
            Route::get('/', [SettingController::class, 'getUsers'])->name('index');
            Route::post('/', [SettingController::class, 'storeUser'])->name('store');
            Route::get('/{id}', [SettingController::class, 'showUser'])->name('show');
            Route::put('/{id}', [SettingController::class, 'updateUser'])->name('update');
            Route::delete('/{id}', [SettingController::class, 'deleteUser'])->name('destroy');
            Route::post('/{user}/restore', [SettingController::class, 'restoreUser'])->name('restore');
            Route::put('/{user}/password', [SettingController::class, 'updateUserPassword'])->name('update-password');
            Route::put('/{user}/status', [SettingController::class, 'toggleUserStatus'])->name('toggle-status');
        });
        
        // Roles
        Route::prefix('roles')->name('roles.')->group(function () {
            Route::get('/', [SettingController::class, 'getRoles'])->name('index');
            Route::post('/', [SettingController::class, 'storeRole'])->name('store');
            Route::get('/{role}', [SettingController::class, 'showRole'])->name('show');
            Route::put('/{role}', [SettingController::class, 'updateRole'])->name('update');
            Route::delete('/{role}', [SettingController::class, 'deleteRole'])->name('destroy');
        });
    });
});

// Duplicate hotel-prefixed routes removed to fix redirection issues

// ==================== SURVEY ROUTES ====================

// Admin/Protected Survey Routes (with authentication)
Route::middleware(['auth', 'package.access', 'check.module:survey'])->prefix('surveys')->name('surveys.')->group(function () {
    // Resource routes
    Route::get('/', [SurveyController::class, 'index'])->name('index');
    Route::get('/create', [SurveyController::class, 'create'])->name('create');
    Route::post('/', [SurveyController::class, 'store'])->name('store');
    Route::get('/{survey}/edit', [SurveyController::class, 'edit'])->name('edit');
    Route::put('/{survey}', [SurveyController::class, 'update'])->name('update');
    Route::delete('/{survey}', [SurveyController::class, 'destroy'])->name('destroy');
    
    // Survey view and responses
    Route::get('/{survey}', [SurveyController::class, 'show'])->name('show');
    Route::get('/{survey}/responses', [SurveyController::class, 'responses'])->name('responses');
    
    // Survey actions
    Route::post('/{survey}/activate', [SurveyController::class, 'activate'])->name('activate');
    Route::post('/{survey}/deactivate', [SurveyController::class, 'deactivate'])->name('deactivate');
    Route::post('/{survey}/archive', [SurveyController::class, 'archive'])->name('archive');
    
    // Invitations
    Route::post('/{survey}/invitations', [SurveyController::class, 'sendInvitations'])->name('invitations');
    Route::get('/{survey}/invitations/statistics', [SurveyInvitationController::class, 'statistics'])->name('invitations.statistics');
    
    // Bulk actions
    Route::post('/bulk/activate', [SurveyController::class, 'bulkActivate'])->name('bulk.activate');
    Route::post('/bulk/deactivate', [SurveyController::class, 'bulkDeactivate'])->name('bulk.deactivate');
    Route::post('/bulk/delete', [SurveyController::class, 'bulkDelete'])->name('bulk.delete');
    
    // Chart data
    Route::get('/chart-data', [SurveyController::class, 'getChartData'])->name('chart-data');
});

// Public Survey Routes (no authentication required)
Route::prefix('survey')->name('survey.')->group(function () {
    // View public survey by ID
    Route::get('/public/{id}', [SurveyController::class, 'public'])->name('public.show');
    
    // Submit public survey response
    Route::post('/public/{id}/submit', [SurveyController::class, 'submit'])->name('public.submit');
    
    // Thank you page
    Route::get('/thank-you/{id}', [SurveyController::class, 'thankYou'])->name('thank-you');
    
    // Token-based invitation routes
    Route::get('/invitation/{token}', [SurveyInvitationController::class, 'show'])->name('invitation');
    Route::post('/invitation/{token}/submit', [SurveyInvitationController::class, 'submit'])->name('invitation.submit');
    Route::get('/invitation/{token}/status', [SurveyInvitationController::class, 'checkStatus'])->name('invitation.status');
    
    // Invitation management (admin only)
    Route::middleware(['auth'])->group(function () {
        Route::post('/invitation/{id}/resend', [SurveyInvitationController::class, 'resend'])->name('invitation.resend');
        Route::delete('/invitation/{id}/cancel', [SurveyInvitationController::class, 'cancel'])->name('invitation.cancel');
    });
    
    // Error pages
    Route::get('/invalid-token', function () { 
        return view('surveys.invalid-token'); 
    })->name('invalid-token');
    
    Route::get('/expired', function () { 
        return view('surveys.expired'); 
    })->name('expired');
});

// Survey Response routes (admin only)
Route::middleware(['auth', 'check.module:survey'])->prefix('survey-responses')->name('survey-responses.')->group(function () {
    Route::get('/{survey}', [SurveyResponseController::class, 'index'])->name('index');
});

// API routes for surveys
Route::prefix('api')->name('api.')->group(function () {
    Route::get('/surveys/chart-data', [SurveyController::class, 'getChartData'])->name('api.surveys.chart-data');
    Route::get('/recipient-counts', [SurveyController::class, 'getRecipientCounts'])->name('api.recipient.counts');
});

// ==================== PROFILE ROUTES ====================
Route::prefix('profile')->name('profile.')->middleware(['auth'])->group(function () {
    // Route::get('/', [ProfileController::class, 'index'])->name('profile.index');
    // Route::get('/edit', [ProfileController::class, 'edit'])->name('profile.edit');
    // Route::put('/', [ProfileController::class, 'update'])->name('profile.update');
    // Route::put('/password', [ProfileController::class, 'updatePassword'])->name('profile.password.update');
    // Route::post('/avatar', [ProfileController::class, 'updateAvatar'])->name('profile.avatar.update');
});

// ==================== DIRECTOR APPROVAL ROUTES ====================
Route::prefix('director')->name('director.')->middleware(['auth'])->group(function () {
    Route::get('/approval-dashboard', [App\Http\Controllers\Director\ApprovalDashboardController::class, 'index'])->name('approval.dashboard');
    Route::get('/staff-requests', [App\Http\Controllers\Director\StaffRequestController::class, 'index'])->name('staff-requests.index');
    Route::get('/staff-requests/{id}', [App\Http\Controllers\Director\StaffRequestController::class, 'show'])->name('staff-requests.show');
    Route::post('/staff-requests/{id}/approve', [App\Http\Controllers\Director\StaffRequestController::class, 'approve'])->name('staff-requests.approve');
    Route::post('/staff-requests/{id}/reject', [App\Http\Controllers\Director\StaffRequestController::class, 'reject'])->name('staff-requests.reject');
    Route::get('/staff-requests/pending/count', [App\Http\Controllers\Director\StaffRequestController::class, 'getPendingCount'])->name('staff-requests.pending-count');
    Route::get('/staff-requests/approved-today/count', [App\Http\Controllers\Director\StaffRequestController::class, 'getApprovedTodayCount'])->name('staff-requests.approved-today');
});

// ==================== ADDITIONAL PUBLIC ROUTES FOR AJAX ====================
Route::prefix('public')->name('public.')->group(function () {
    // Guest email check - accessible without package.access
    Route::post('/check-guest-email', [GuestController::class, 'checkEmail'])->name('check-guest-email');
});

// ==================== TEMPORARY FIX FOR MALFORMED URLs ====================
Route::get('/{module}.index', function($module) {
    $validModules = [
        'reservations', 'rooms', 'guests', 'inout', 'dashboard', 'home',
        'services', 'service-categories',
        'pos', 'menu-categories', 'menu-items',
        'maintenance', 'technicians', 'maintenance-requests',
        'housekeeping',
        'inventory', 'purchase-orders',
        'staff', 'attendance', 'leaves',
        'documents',
        'surveys', 'survey-responses',
        'reports',
        'accounting',
        'categories', 'contacts', 'expenses', 'installments', 
        'settings', 'profile', 'notifications', 'audit-logs', 
        'help', 'announcements', 'feedback', 'tasks',
        'room-types'
    ];
    
    if (in_array($module, $validModules)) {
        return redirect('/' . $module, 301);
    }
    
    abort(404);
})->where('module', '.*');

// ==================== CUSTOM 404 PAGE ====================
Route::fallback(function () {
    // Avoid missing view errors by returning a simple response directly.
    return response('<h1>404 Not Found</h1><p>The page you are looking for does not exist.</p>', 404);
});