<?php

use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegistrationController;
use App\Http\Controllers\LandingPageController;
use App\Http\Controllers\Platform\BillingController as PlatformBillingController;
use App\Http\Controllers\Platform\CommunicationController as PlatformCommunicationController;
use App\Http\Controllers\Platform\DashboardController as PlatformDashboardController;
use App\Http\Controllers\Platform\ImpersonationController as PlatformImpersonationController;
use App\Http\Controllers\Platform\LandingPageController as PlatformLandingPageController;
use App\Http\Controllers\Platform\PlanController as PlatformPlanController;
use App\Http\Controllers\Platform\ReportController as PlatformReportController;
use App\Http\Controllers\Platform\SecurityController as PlatformSecurityController;
use App\Http\Controllers\Platform\SettingsController as PlatformSettingsController;
use App\Http\Controllers\Platform\SupportController as PlatformSupportController;
use App\Http\Controllers\Platform\TenantController as PlatformTenantController;
use App\Http\Controllers\Platform\UsageController as PlatformUsageController;
use App\Http\Controllers\Tenant\AccountingController;
use App\Http\Controllers\Tenant\Application360Controller;
use App\Http\Controllers\Tenant\ApplicationDirectoryController;
use App\Http\Controllers\Tenant\ApplicationWorkspaceController;
use App\Http\Controllers\Tenant\AttendanceController;
use App\Http\Controllers\Tenant\BillingPosController;
use App\Http\Controllers\Tenant\BillingSettingsController;
use App\Http\Controllers\Tenant\BranchController;
use App\Http\Controllers\Tenant\BulkApplicationController;
use App\Http\Controllers\Tenant\CashSessionController;
use App\Http\Controllers\Tenant\CommunicationCenterController;
use App\Http\Controllers\Tenant\CorporateCompanyController;
use App\Http\Controllers\Tenant\CorporateEmployeeController;
use App\Http\Controllers\Tenant\CrmController;
use App\Http\Controllers\Tenant\CustomerDashboardController;
use App\Http\Controllers\Tenant\CustomerDirectoryController;
use App\Http\Controllers\Tenant\CustomerDocumentVaultController;
use App\Http\Controllers\Tenant\CustomerSearchController;
use App\Http\Controllers\Tenant\DashboardController as TenantDashboardController;
use App\Http\Controllers\Tenant\DepartmentCounterController;
use App\Http\Controllers\Tenant\DuplicateReviewController;
use App\Http\Controllers\Tenant\DynamicFormBuilderController;
use App\Http\Controllers\Tenant\EmployeeDirectoryController;
use App\Http\Controllers\Tenant\FamilyController;
use App\Http\Controllers\Tenant\GlobalSearchController;
use App\Http\Controllers\Tenant\GratuityController;
use App\Http\Controllers\Tenant\LeaveController;
use App\Http\Controllers\Tenant\NotificationController;
use App\Http\Controllers\Tenant\OnboardingController;
use App\Http\Controllers\Tenant\PayrollController;
use App\Http\Controllers\Tenant\ProOperationsController;
use App\Http\Controllers\Tenant\QueueAppointmentController;
use App\Http\Controllers\Tenant\RefundController;
use App\Http\Controllers\Tenant\RenewalCenterController;
use App\Http\Controllers\Tenant\ReportCenterController;
use App\Http\Controllers\Tenant\RoleController;
use App\Http\Controllers\Tenant\RolePanelController;
use App\Http\Controllers\Tenant\ServiceBundlesController;
use App\Http\Controllers\Tenant\ServiceCatalogController;
use App\Http\Controllers\Tenant\ServiceDashboardController;
use App\Http\Controllers\Tenant\ServiceDocumentRulesController;
use App\Http\Controllers\Tenant\ServiceFeeEngineController;
use App\Http\Controllers\Tenant\ServiceMasterController;
use App\Http\Controllers\Tenant\ShiftController;
use App\Http\Controllers\Tenant\TaskApprovalController;
use App\Http\Controllers\Tenant\TenantSettingsHubController;
use App\Http\Controllers\Tenant\UserController;
use App\Http\Controllers\Tenant\WorkflowBuilderController;
use App\Http\Middleware\CheckTenantSubscription;
use App\Http\Middleware\EnforceTenantScope;
use App\Http\Middleware\RequirePasswordChange;
use Illuminate\Support\Facades\Route;

// Public Guest Routes
Route::get('/', [LandingPageController::class, 'index'])->name('home');

Route::middleware('guest')->group(function () {
    Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [LoginController::class, 'login']);
    Route::get('/signup', [RegistrationController::class, 'create'])->name('signup');
    Route::post('/signup', [RegistrationController::class, 'store'])->middleware('throttle:5,1')->name('signup.store');
});
Route::post('/locale/{locale}', function (string $locale) {
    abort_unless(in_array($locale, ['en', 'ar'], true), 404);
    session(['locale' => $locale]);

    return back();
})->name('locale.switch');
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');

// Impersonation Exit Route
Route::post('/platform/impersonate/stop', [PlatformImpersonationController::class, 'stop'])->name('platform.impersonate.stop');

// Authenticated Routes
Route::middleware(['auth', EnforceTenantScope::class, RequirePasswordChange::class])->group(function () {

    // Language switcher
    Route::post('/app/lang/{locale}', [TenantDashboardController::class, 'switchLanguage'])->name('app.switch_language');

    // 1. SaaS Super Admin Control Panel Routes (/platform/*)
    Route::prefix('platform')->name('platform.')->group(function () {
        Route::get('/dashboard', [PlatformDashboardController::class, 'index'])->name('dashboard');

        // Tenants Management
        Route::get('/tenants', [PlatformTenantController::class, 'index'])->name('tenants');
        Route::get('/tenants/create', [PlatformTenantController::class, 'createWizard'])->name('tenants.create');
        Route::post('/tenants', [PlatformTenantController::class, 'storeWizard'])->name('tenants.store');
        Route::get('/tenants/{id}', [PlatformTenantController::class, 'show'])->name('tenants.show');
        Route::post('/tenants/{id}/status', [PlatformTenantController::class, 'updateStatus'])->name('tenants.update_status');
        Route::post('/tenants/{id}/overrides', [PlatformTenantController::class, 'updateFeatureOverrides'])->name('tenants.update_overrides');
        Route::post('/tenants/{id}/notes', [PlatformTenantController::class, 'addNote'])->name('tenants.add_note');
        Route::post('/tenants/{id}/impersonate', [PlatformImpersonationController::class, 'start'])->name('tenants.impersonate');

        // Subscriptions & Plans
        Route::get('/subscriptions', [PlatformTenantController::class, 'index'])->name('subscriptions');
        Route::get('/plans', [PlatformPlanController::class, 'index'])->name('plans');
        Route::get('/plans/create', [PlatformPlanController::class, 'create'])->name('plans.create');
        Route::post('/plans', [PlatformPlanController::class, 'store'])->name('plans.store');
        Route::get('/plans/{id}/edit', [PlatformPlanController::class, 'edit'])->name('plans.edit');
        Route::put('/plans/{id}', [PlatformPlanController::class, 'update'])->name('plans.update');

        // SaaS Billing & Invoices
        Route::get('/billing/invoices', [PlatformBillingController::class, 'invoices'])->name('billing.invoices');
        Route::get('/billing/payments', [PlatformBillingController::class, 'payments'])->name('billing.payments');
        Route::get('/billing/payments/create', [PlatformBillingController::class, 'createPayment'])->name('billing.create_payment');
        Route::post('/billing/payments', [PlatformBillingController::class, 'storeManualPayment'])->name('billing.store_payment');

        // Usage & Credit Wallets
        Route::get('/usage', [PlatformUsageController::class, 'index'])->name('usage');
        Route::post('/usage/credits', [PlatformUsageController::class, 'adjustCredits'])->name('usage.adjust_credits');

        // Support Desk
        Route::get('/support', [PlatformSupportController::class, 'index'])->name('support');
        Route::get('/support/{id}', [PlatformSupportController::class, 'show'])->name('support.show');
        Route::post('/support/{id}/reply', [PlatformSupportController::class, 'reply'])->name('support.reply');

        // Communications & Announcements
        Route::get('/communications', [PlatformCommunicationController::class, 'announcements'])->name('communications');
        Route::post('/communications/announcement', [PlatformCommunicationController::class, 'storeAnnouncement'])->name('communications.store_announcement');

        // Security & Audit
        Route::get('/security', [PlatformSecurityController::class, 'index'])->name('security');
        Route::get('/security/audit', [PlatformSecurityController::class, 'auditLogs'])->name('security.audit');

        // Analytics & Reports
        Route::get('/reports', [PlatformReportController::class, 'index'])->name('reports');

        // Settings
        Route::get('/settings', [PlatformSettingsController::class, 'index'])->name('settings');
        Route::post('/settings', [PlatformSettingsController::class, 'update'])->name('settings.update');

        // Public Landing Page CMS (super admin only)
        Route::get('/landing-page', [PlatformLandingPageController::class, 'edit'])->name('landing.edit');
        Route::put('/landing-page', [PlatformLandingPageController::class, 'update'])->name('landing.update');
    });

    // 2. Tenant ERP Routes (/app/*)
    Route::prefix('app')->name('app.')->middleware([CheckTenantSubscription::class])->group(function () {
        // Guided Tenant Onboarding System
        Route::get('/onboarding/welcome', [OnboardingController::class, 'welcome'])->name('onboarding.welcome');
        Route::get('/onboarding/wizard', [OnboardingController::class, 'wizard'])->name('onboarding.wizard');
        Route::post('/onboarding/go-live', [OnboardingController::class, 'goLive'])->name('onboarding.go_live');

        // Main Executive Dashboard & Branch Switcher
        Route::get('/dashboard', [TenantDashboardController::class, 'index'])->name('dashboard');
        Route::post('/branch/switch', [TenantDashboardController::class, 'switchBranch'])->name('switch_branch');
        Route::get('/global-search', GlobalSearchController::class)->name('global_search')->middleware('permission:dashboard.view');
        Route::get('/notifications', [NotificationController::class, 'index'])->name('notifications.index');
        Route::post('/notifications/read-all', [NotificationController::class, 'readAll'])->name('notifications.read_all');
        Route::post('/notifications/{id}/read', [NotificationController::class, 'read'])->name('notifications.read');

        // Specialized Role Dashboards
        Route::get('/front-desk', [RolePanelController::class, 'frontDesk'])->name('front_desk')->middleware('permission:dashboard.view');
        Route::get('/work-queue', [RolePanelController::class, 'workQueue'])->name('work_queue')->middleware('permission:applications.view');
        Route::get('/processing', [RolePanelController::class, 'processing'])->name('processing')->middleware('permission:applications.view');
        Route::get('/pro', [ProOperationsController::class, 'index'])->name('pro')->middleware('permission:pro.view');
        Route::get('/cashier', [BillingPosController::class, 'index'])->name('cashier')->middleware('permission:payments.view');
        Route::get('/accounting', [AccountingController::class, 'index'])->name('accounting')->middleware('permission:invoices.view');
        Route::get('/hr', [RolePanelController::class, 'hr'])->name('hr')->middleware('permission:employees.view');
        Route::get('/crm', [CrmController::class, 'index'])->name('crm')->middleware('permission:crm.view');
        Route::get('/renewals', [RenewalCenterController::class, 'index'])->name('renewals')->middleware('permission:renewals.view');
        Route::get('/customer-service', [RolePanelController::class, 'customerService'])->name('customer_service')->middleware('permission:customers.view');
        Route::get('/documents', [RolePanelController::class, 'documents'])->name('documents')->middleware('permission:documents.view');
        Route::get('/audit', [RolePanelController::class, 'audit'])->name('audit')->middleware('permission:audit.view');

        // Advanced Operations Suite
        Route::post('/crm/leads', [CrmController::class, 'store'])->name('crm.leads.store')->middleware('permission:crm.manage');
        Route::post('/crm/leads/{id}/stage', [CrmController::class, 'updateStage'])->name('crm.leads.stage')->middleware('permission:crm.manage');
        Route::post('/crm/leads/{id}/activities', [CrmController::class, 'addActivity'])->name('crm.leads.activities')->middleware('permission:crm.manage');

        Route::get('/communication-center', [CommunicationCenterController::class, 'index'])->name('communications.index')->middleware('permission:communications.view');
        Route::post('/communication-center/templates', [CommunicationCenterController::class, 'storeTemplate'])->name('communications.templates.store')->middleware('permission:communications.manage');
        Route::post('/communication-center/messages', [CommunicationCenterController::class, 'queueMessage'])->name('communications.messages.store')->middleware('permission:communications.manage');

        Route::post('/pro/jobs', [ProOperationsController::class, 'storeJob'])->name('pro.jobs.store')->middleware('permission:pro.manage');
        Route::post('/pro/jobs/{id}/status', [ProOperationsController::class, 'updateJob'])->name('pro.jobs.status')->middleware('permission:pro.manage');
        Route::post('/pro/custody', [ProOperationsController::class, 'storeCustody'])->name('pro.custody.store')->middleware('permission:pro.manage');
        Route::post('/pro/custody/{id}/handover', [ProOperationsController::class, 'handover'])->name('pro.custody.handover')->middleware('permission:pro.manage');

        Route::get('/queue', [QueueAppointmentController::class, 'index'])->name('queue.index')->middleware('permission:queue.view');
        Route::post('/queue/tokens', [QueueAppointmentController::class, 'storeToken'])->name('queue.tokens.store')->middleware('permission:queue.manage');
        Route::post('/queue/tokens/{id}/status', [QueueAppointmentController::class, 'updateToken'])->name('queue.tokens.status')->middleware('permission:queue.manage');
        Route::post('/appointments', [QueueAppointmentController::class, 'storeAppointment'])->name('appointments.store')->middleware('permission:appointments.manage');
        Route::post('/appointments/{id}/status', [QueueAppointmentController::class, 'updateAppointment'])->name('appointments.status')->middleware('permission:appointments.manage');

        Route::get('/tasks-approvals', [TaskApprovalController::class, 'index'])->name('tasks.index')->middleware('permission:tasks.view');
        Route::post('/tasks', [TaskApprovalController::class, 'storeTask'])->name('tasks.store')->middleware('permission:tasks.manage');
        Route::post('/tasks/{id}/status', [TaskApprovalController::class, 'updateTask'])->name('tasks.status')->middleware('permission:tasks.manage');
        Route::post('/approvals', [TaskApprovalController::class, 'storeApproval'])->name('approvals.store')->middleware('permission:approvals.view');
        Route::post('/approvals/{id}/decision', [TaskApprovalController::class, 'decideApproval'])->name('approvals.decision')->middleware('permission:approvals.manage');

        Route::get('/reports', [ReportCenterController::class, 'index'])->name('reports.index')->middleware('permission:reports.view');

        // Personal Profile & Security Settings
        Route::get('/profile', [RolePanelController::class, 'profile'])->name('profile');
        Route::post('/profile/update', [RolePanelController::class, 'updateProfile'])->name('profile.update');
        Route::post('/profile/password', [RolePanelController::class, 'updatePassword'])->name('profile.password');

        // Phase 4: Customer 360 & Corporate CRM Routes
        Route::get('/customers/dashboard', [CustomerDashboardController::class, 'dashboard'])->name('customers.dashboard')->middleware('permission:customers.view');
        Route::get('/customers/search', [CustomerSearchController::class, 'search'])->name('customers.search')->middleware('permission:customers.view');
        Route::get('/customers', [CustomerDirectoryController::class, 'index'])->name('customers.index')->middleware('permission:customers.view');
        Route::get('/customers/create', [CustomerDirectoryController::class, 'create'])->name('customers.create')->middleware('permission:customers.create');
        Route::post('/customers', [CustomerDirectoryController::class, 'store'])->name('customers.store')->middleware('permission:customers.create');
        Route::get('/customers/documents', [CustomerDocumentVaultController::class, 'index'])->name('customers.documents.index')->middleware('permission:documents.view');
        Route::get('/customers/documents/{id}/download', [CustomerDocumentVaultController::class, 'download'])->name('customers.documents.download')->middleware('permission:documents.download');
        Route::get('/customers/duplicates', [DuplicateReviewController::class, 'index'])->name('customers.duplicates')->middleware('permission:customers.view');
        Route::post('/customers/merge', [DuplicateReviewController::class, 'merge'])->name('customers.merge')->middleware('permission:customers.edit');
        Route::get('/customers/families', [FamilyController::class, 'index'])->name('customers.families.index')->middleware('permission:customers.view');
        Route::post('/customers/families', [FamilyController::class, 'store'])->name('customers.families.store')->middleware('permission:customers.create');
        Route::get('/customers/families/{id}', [FamilyController::class, 'show'])->name('customers.families.show')->middleware('permission:customers.view');
        Route::post('/customers/families/{id}/add-member', [FamilyController::class, 'addMember'])->name('customers.families.add_member')->middleware('permission:customers.edit');
        Route::get('/customers/{id}', [CustomerDirectoryController::class, 'show'])->name('customers.show')->middleware('permission:customers.view');
        Route::post('/customers/{id}/note', [CustomerDirectoryController::class, 'storeNote'])->name('customers.store_note')->middleware('permission:customers.edit');
        Route::post('/customers/{id}/flag', [CustomerDirectoryController::class, 'storeFlag'])->name('customers.store_flag')->middleware('permission:customers.edit');
        Route::post('/customers/{id}/documents', [CustomerDocumentVaultController::class, 'store'])->name('customers.documents.store')->middleware('permission:documents.upload');

        Route::get('/corporate/companies', [CorporateCompanyController::class, 'index'])->name('corporate.companies.index')->middleware('permission:customers.view');
        Route::get('/corporate/companies/create', [CorporateCompanyController::class, 'create'])->name('corporate.companies.create')->middleware('permission:customers.create');
        Route::post('/corporate/companies', [CorporateCompanyController::class, 'store'])->name('corporate.companies.store')->middleware('permission:customers.create');
        Route::get('/corporate/companies/{id}', [CorporateCompanyController::class, 'show'])->name('corporate.companies.show')->middleware('permission:customers.view');
        Route::post('/corporate/companies/{id}/contact', [CorporateCompanyController::class, 'addContact'])->name('corporate.companies.add_contact')->middleware('permission:customers.edit');
        Route::get('/corporate/employees', [CorporateEmployeeController::class, 'index'])->name('corporate.employees.index')->middleware('permission:customers.view');
        Route::get('/corporate/employees/create', [CorporateEmployeeController::class, 'create'])->name('corporate.employees.create')->middleware('permission:customers.create');
        Route::post('/corporate/employees', [CorporateEmployeeController::class, 'store'])->name('corporate.employees.store')->middleware('permission:customers.create');
        Route::get('/corporate/employees/{id}', [CorporateEmployeeController::class, 'show'])->name('corporate.employees.show')->middleware('permission:customers.view');
        Route::put('/corporate/employees/{id}', [CorporateEmployeeController::class, 'update'])->name('corporate.employees.update')->middleware('permission:customers.edit');
        Route::post('/corporate/employees/{id}/documents', [CorporateEmployeeController::class, 'storeDocument'])->name('corporate.employees.documents.store')->middleware('permission:customers.edit');
        Route::get('/corporate/employees/{id}/documents/{documentId}/download', [CorporateEmployeeController::class, 'downloadDocument'])->name('corporate.employees.documents.download')->middleware('permission:customers.view');
        Route::get('/corporate/expiries', [CorporateEmployeeController::class, 'expiries'])->name('corporate.expiries')->middleware('permission:customers.view');
        Route::post('/corporate/expiries/{documentId}/renewal', [CorporateEmployeeController::class, 'createRenewal'])->name('corporate.expiries.renewal')->middleware('permission:renewals.manage');

        // Phase 5: Advanced Service Configuration & Workflow Engine Routes
        Route::get('/services/dashboard', [ServiceDashboardController::class, 'dashboard'])->name('services.dashboard')->middleware('permission:settings.view');
        Route::get('/services/bundles', [ServiceBundlesController::class, 'index'])->name('services.bundles.index')->middleware('permission:settings.view');
        Route::post('/services/bundles', [ServiceBundlesController::class, 'store'])->name('services.bundles.store')->middleware('permission:settings.edit');
        Route::get('/services/{id}/show', [ServiceMasterController::class, 'show'])->name('services.show')->middleware('permission:settings.view');
        Route::post('/services/{id}/duplicate', [ServiceMasterController::class, 'duplicate'])->name('services.duplicate')->middleware('permission:settings.edit');
        Route::get('/services/{id}/test-mode', [ServiceMasterController::class, 'testMode'])->name('services.test_mode')->middleware('permission:settings.view');
        Route::post('/services/{id}/publish', [ServiceMasterController::class, 'publish'])->name('services.publish')->middleware('permission:settings.edit');
        Route::post('/services/{id}/sections', [DynamicFormBuilderController::class, 'storeSection'])->name('services.sections.store')->middleware('permission:settings.edit');
        Route::post('/services/sections/{id}/fields', [DynamicFormBuilderController::class, 'storeField'])->name('services.fields.store')->middleware('permission:settings.edit');
        Route::post('/services/{id}/document-rules', [ServiceDocumentRulesController::class, 'storeRule'])->name('services.document_rules.store')->middleware('permission:settings.edit');
        Route::post('/services/{id}/fee-components', [ServiceFeeEngineController::class, 'storeComponent'])->name('services.fee_components.store')->middleware('permission:settings.edit');
        Route::post('/services/{id}/price-overrides', [ServiceFeeEngineController::class, 'storeOverride'])->name('services.price_overrides.store')->middleware('permission:settings.edit');
        Route::post('/services/{id}/stages', [WorkflowBuilderController::class, 'storeStage'])->name('services.stages.store')->middleware('permission:settings.edit');
        Route::post('/services/{id}/transitions', [WorkflowBuilderController::class, 'storeTransition'])->name('services.transitions.store')->middleware('permission:settings.edit');
        Route::post('/services/{id}/install-uae-workflow', [WorkflowBuilderController::class, 'installUaeWorkflow'])->name('services.workflow.install_uae')->middleware('permission:settings.edit');

        // Phase 6: Universal Application Creation & Processing Routes
        Route::get('/applications/create', [ApplicationWorkspaceController::class, 'create'])->name('applications.create')->middleware('permission:applications.create');
        Route::get('/applications/search-customer', [ApplicationWorkspaceController::class, 'searchCustomer'])->name('applications.search_customer')->middleware('permission:applications.create');
        Route::post('/applications/calculate-fees', [ApplicationWorkspaceController::class, 'calculateFees'])->name('applications.calculate_fees')->middleware('permission:applications.create');
        Route::post('/applications', [ApplicationWorkspaceController::class, 'store'])->name('applications.store')->middleware('permission:applications.create');
        Route::get('/applications', [ApplicationDirectoryController::class, 'index'])->name('applications.index')->middleware('permission:applications.view');
        Route::get('/applications/work-queue', [ApplicationDirectoryController::class, 'workQueue'])->name('applications.work_queue')->middleware('permission:applications.view');
        Route::get('/applications/kanban', [ApplicationDirectoryController::class, 'kanban'])->name('applications.kanban')->middleware('permission:applications.view');
        Route::post('/applications/{id}/claim', [ApplicationDirectoryController::class, 'claimQueue'])->name('applications.claim')->middleware('permission:applications.assign');
        Route::get('/applications/bulk', [BulkApplicationController::class, 'index'])->name('applications.bulk.index')->middleware('permission:applications.create');
        Route::post('/applications/bulk', [BulkApplicationController::class, 'store'])->name('applications.bulk.store')->middleware('permission:applications.create');
        Route::get('/applications/{id}', [Application360Controller::class, 'show'])->name('applications.show')->middleware('permission:applications.view');
        Route::post('/applications/{id}/transition', [Application360Controller::class, 'transition'])->name('applications.transition')->middleware('permission:applications.view');
        Route::post('/applications/{id}/submission', [Application360Controller::class, 'recordSubmission'])->name('applications.submission')->middleware('permission:applications.submit');
        Route::post('/applications/{id}/return', [Application360Controller::class, 'recordReturn'])->name('applications.return')->middleware('permission:applications.edit');
        Route::post('/applications/{id}/approval', [Application360Controller::class, 'recordApproval'])->name('applications.approval')->middleware('permission:applications.approve');
        Route::post('/applications/{id}/rejection', [Application360Controller::class, 'recordRejection'])->name('applications.rejection')->middleware('permission:applications.reject');
        Route::post('/applications/{id}/documents', [Application360Controller::class, 'uploadDocument'])->name('applications.documents.upload')->middleware('permission:documents.upload');
        Route::post('/applications/{id}/documents/{documentId}/review', [Application360Controller::class, 'reviewDocument'])->name('applications.documents.review')->middleware('permission:documents.upload');
        Route::post('/applications/{id}/outputs', [Application360Controller::class, 'uploadOutput'])->name('applications.outputs.store')->middleware('permission:documents.upload');
        Route::post('/applications/{id}/notify', [Application360Controller::class, 'notifyCustomer'])->name('applications.notify')->middleware('permission:communications.manage');
        Route::post('/applications/{id}/deliver', [Application360Controller::class, 'deliver'])->name('applications.deliver')->middleware('permission:communications.manage');
        Route::post('/applications/{id}/sla/pause', [Application360Controller::class, 'pauseSla'])->name('applications.sla.pause')->middleware('permission:applications.edit');
        Route::post('/applications/{id}/sla/resume', [Application360Controller::class, 'resumeSla'])->name('applications.sla.resume')->middleware('permission:applications.edit');
        Route::post('/applications/{id}/note', [Application360Controller::class, 'storeNote'])->name('applications.note')->middleware('permission:applications.edit');

        // Phase 7: Tenant Billing, POS, Refunds, Cash Drawer & Accounting
        Route::prefix('billing')->name('billing.')->group(function () {
            Route::get('/pos', [BillingPosController::class, 'index'])->name('pos')->middleware('permission:payments.view');
            Route::get('/invoices', [BillingPosController::class, 'invoices'])->name('invoices.index')->middleware('permission:invoices.view');
            Route::post('/invoices', [BillingPosController::class, 'storeInvoice'])->name('invoices.store')->middleware('permission:invoices.create');
            Route::get('/invoices/{id}', [BillingPosController::class, 'showInvoice'])->name('invoices.show')->middleware('permission:invoices.view');
            Route::post('/invoices/{id}/payments', [BillingPosController::class, 'collectPayment'])->name('invoices.payments.store')->middleware('permission:payments.collect');
            Route::get('/receipts/{id}', [BillingPosController::class, 'receipt'])->name('receipts.show')->middleware('permission:invoices.print');

            Route::get('/refunds', [RefundController::class, 'index'])->name('refunds.index')->middleware('permission:payments.view');
            Route::post('/refunds', [RefundController::class, 'store'])->name('refunds.store')->middleware('permission:payments.refund_request');
            Route::post('/refunds/{id}/approve', [RefundController::class, 'approve'])->name('refunds.approve')->middleware('permission:payments.refund_approve');
            Route::post('/refunds/{id}/process', [RefundController::class, 'process'])->name('refunds.process')->middleware('permission:payments.refund_approve');

            Route::get('/cash-sessions', [CashSessionController::class, 'index'])->name('cash_sessions.index')->middleware('permission:payments.view');
            Route::post('/cash-sessions', [CashSessionController::class, 'open'])->name('cash_sessions.open')->middleware('permission:payments.collect');
            Route::post('/cash-sessions/{id}/close', [CashSessionController::class, 'close'])->name('cash_sessions.close')->middleware('permission:payments.collect');
        });

        // Phase 8: Renewal & Expiry Automation Center
        Route::prefix('renewal-center')->name('renewals.')->group(function () {
            Route::get('/', [RenewalCenterController::class, 'index'])->name('index')->middleware('permission:renewals.view');
            Route::post('/scan', [RenewalCenterController::class, 'scan'])->name('scan')->middleware('permission:renewals.manage');
            Route::get('/{id}', [RenewalCenterController::class, 'show'])->name('show')->middleware('permission:renewals.view');
            Route::post('/{id}/transition', [RenewalCenterController::class, 'transition'])->name('transition')->middleware('permission:renewals.manage');
            Route::post('/{id}/follow-up', [RenewalCenterController::class, 'followUp'])->name('follow_up')->middleware('permission:renewals.manage');
            Route::post('/{id}/document-status', [RenewalCenterController::class, 'updateDocumentStatus'])->name('document_status')->middleware('permission:renewals.manage');
            Route::post('/{id}/reminders', [RenewalCenterController::class, 'scheduleReminder'])->name('reminders.store')->middleware('permission:renewals.manage');
            Route::post('/{id}/application', [RenewalCenterController::class, 'createApplication'])->name('application')->middleware('permission:renewals.manage');
            Route::post('/{id}/complete', [RenewalCenterController::class, 'complete'])->name('complete')->middleware('permission:renewals.manage');
        });

        // Roles & Permissions Matrix Management
        Route::get('/roles', [RoleController::class, 'index'])->name('roles.index')->middleware('permission:roles.view');
        Route::get('/roles/create', [RoleController::class, 'create'])->name('roles.create')->middleware('permission:roles.create');
        Route::post('/roles', [RoleController::class, 'store'])->name('roles.store')->middleware('permission:roles.create');
        Route::get('/roles/{id}/edit', [RoleController::class, 'edit'])->name('roles.edit')->middleware('permission:roles.edit');
        Route::put('/roles/{id}', [RoleController::class, 'update'])->name('roles.update')->middleware('permission:roles.edit');
        Route::post('/roles/{id}/duplicate', [RoleController::class, 'duplicate'])->name('roles.duplicate')->middleware('permission:roles.create');
        Route::delete('/roles/{id}', [RoleController::class, 'destroy'])->name('roles.destroy')->middleware('permission:roles.delete');

        // User Accounts Management
        Route::get('/users', [UserController::class, 'index'])->name('users.index')->middleware('permission:employees.view');
        Route::get('/users/create', [UserController::class, 'create'])->name('users.create')->middleware('permission:employees.create');
        Route::post('/users', [UserController::class, 'store'])->name('users.store')->middleware('permission:employees.create');
        Route::get('/users/{id}/edit', [UserController::class, 'edit'])->name('users.edit')->middleware('permission:employees.edit');
        Route::put('/users/{id}', [UserController::class, 'update'])->name('users.update')->middleware('permission:employees.edit');
        Route::get('/users/{id}/overrides', [UserController::class, 'overrides'])->name('users.overrides')->middleware('permission:roles.edit');
        Route::post('/users/{id}/overrides', [UserController::class, 'updateOverrides'])->name('users.overrides.update')->middleware('permission:roles.edit');
        Route::post('/users/{id}/reset-password', [UserController::class, 'resetPassword'])->name('users.reset_password')->middleware('permission:employees.edit');
        Route::post('/users/{id}/toggle-status', [UserController::class, 'toggleStatus'])->name('users.toggle_status')->middleware('permission:employees.edit');
        Route::get('/users/{id}/login-history', [UserController::class, 'loginHistory'])->name('users.login_history')->middleware('permission:audit.view');

        // HR & Employee Directory
        Route::get('/employees', [EmployeeDirectoryController::class, 'index'])->name('employees.index')->middleware('permission:employees.view');
        Route::get('/employees/create', [EmployeeDirectoryController::class, 'create'])->name('employees.create')->middleware('permission:employees.create');
        Route::post('/employees', [EmployeeDirectoryController::class, 'store'])->name('employees.store')->middleware('permission:employees.create');
        Route::get('/employees/expiries', [EmployeeDirectoryController::class, 'expiries'])->name('employees.expiries')->middleware('permission:employees.view');
        Route::get('/employees/{id}', [EmployeeDirectoryController::class, 'show'])->name('employees.show')->middleware('permission:employees.view');
        Route::put('/employees/{id}', [EmployeeDirectoryController::class, 'update'])->name('employees.update')->middleware('permission:employees.edit');
        Route::get('/employees/{id}/give-access', [EmployeeDirectoryController::class, 'giveAccess'])->name('employees.give_access')->middleware('permission:employees.edit');
        Route::post('/employees/{id}/give-access', [EmployeeDirectoryController::class, 'storeAccess'])->name('employees.store_access')->middleware('permission:employees.edit');
        Route::post('/employees/{id}/documents', [EmployeeDirectoryController::class, 'storeDocument'])->name('employees.documents.store')->middleware('permission:employees.edit');
        Route::put('/employees/{id}/documents/{documentId}', [EmployeeDirectoryController::class, 'updateDocument'])->name('employees.documents.update')->middleware('permission:employees.edit');
        Route::post('/employees/{id}/documents/{documentId}/verify', [EmployeeDirectoryController::class, 'verifyDocument'])->name('employees.documents.verify')->middleware('permission:employees.edit');
        Route::get('/employees/{id}/documents/{documentId}/download', [EmployeeDirectoryController::class, 'downloadDocument'])->name('employees.documents.download')->middleware('permission:employees.view');

        // Complete HR lifecycle: shifts, attendance, leave, payroll, WPS, loans and gratuity
        Route::get('/shifts', [ShiftController::class, 'index'])->name('shifts.index')->middleware('permission:shifts.view');
        Route::post('/shifts', [ShiftController::class, 'store'])->name('shifts.store')->middleware('permission:shifts.manage');
        Route::put('/shifts/{id}', [ShiftController::class, 'update'])->name('shifts.update')->middleware('permission:shifts.manage');
        Route::post('/shifts/{id}/assignments', [ShiftController::class, 'assign'])->name('shifts.assign')->middleware('permission:shifts.manage');

        Route::get('/attendance', [AttendanceController::class, 'index'])->name('attendance.index')->middleware('permission:attendance.view');
        Route::post('/attendance', [AttendanceController::class, 'store'])->name('attendance.store')->middleware('permission:attendance.manage');
        Route::post('/attendance/punch', [AttendanceController::class, 'punch'])->name('attendance.punch')->middleware('permission:attendance.view');
        Route::post('/attendance/import', [AttendanceController::class, 'import'])->name('attendance.import')->middleware('permission:attendance.manage');
        Route::post('/attendance/{id}/corrections', [AttendanceController::class, 'requestCorrection'])->name('attendance.corrections.store')->middleware('permission:attendance.view');
        Route::post('/attendance/corrections/{id}/review', [AttendanceController::class, 'reviewCorrection'])->name('attendance.corrections.review')->middleware('permission:attendance.approve');

        Route::get('/leave', [LeaveController::class, 'index'])->name('leave.index')->middleware('permission:leave.view');
        Route::post('/leave', [LeaveController::class, 'store'])->name('leave.store')->middleware('permission:leave.create');
        Route::post('/leave/types', [LeaveController::class, 'storeType'])->name('leave.types.store')->middleware('permission:leave.approve');
        Route::post('/leave/{id}/review', [LeaveController::class, 'review'])->name('leave.review')->middleware('permission:leave.approve');
        Route::post('/leave/{id}/cancel', [LeaveController::class, 'cancel'])->name('leave.cancel')->middleware('permission:leave.create');

        Route::get('/payroll', [PayrollController::class, 'index'])->name('payroll.index')->middleware('permission:payroll.view');
        Route::post('/payroll', [PayrollController::class, 'store'])->name('payroll.store')->middleware('permission:payroll.process');
        Route::get('/payroll/{id}', [PayrollController::class, 'show'])->name('payroll.show')->middleware('permission:payroll.view');
        Route::post('/payroll/{id}/recalculate', [PayrollController::class, 'recalculate'])->name('payroll.recalculate')->middleware('permission:payroll.process');
        Route::post('/payroll/{id}/transition/{action}', [PayrollController::class, 'transition'])->name('payroll.transition')->middleware('permission:payroll.view');
        Route::post('/payroll/items/{itemId}/adjustments', [PayrollController::class, 'adjustment'])->name('payroll.adjustments.store')->middleware('permission:payroll.process');
        Route::get('/payroll/items/{itemId}/payslip', [PayrollController::class, 'payslip'])->name('payroll.payslip')->middleware('permission:payroll.view');
        Route::get('/payroll/items/{itemId}/payslip.pdf', [PayrollController::class, 'downloadPayslip'])->name('payroll.payslip.pdf')->middleware('permission:payroll.view');
        Route::post('/payroll/{id}/wps', [PayrollController::class, 'prepareWps'])->name('payroll.wps.prepare')->middleware('permission:payroll.wps.export');
        Route::get('/payroll/wps/{batchId}/download', [PayrollController::class, 'downloadWps'])->name('payroll.wps.download')->middleware('permission:payroll.wps.export');
        Route::post('/employees/{employeeId}/salary', [PayrollController::class, 'storeSalary'])->name('employees.salary.store')->middleware('permission:payroll.salary.edit');
        Route::post('/employees/{employeeId}/loans', [PayrollController::class, 'storeLoan'])->name('employees.loans.store')->middleware('permission:payroll.process');
        Route::post('/loans/{loanId}/approve', [PayrollController::class, 'approveLoan'])->name('loans.approve')->middleware('permission:payroll.approve');

        Route::get('/gratuity', [GratuityController::class, 'index'])->name('gratuity.index')->middleware('permission:gratuity.view');
        Route::post('/gratuity/employees/{employeeId}', [GratuityController::class, 'store'])->name('gratuity.store')->middleware('permission:gratuity.manage');
        Route::post('/gratuity/{id}/approve', [GratuityController::class, 'approve'])->name('gratuity.approve')->middleware('permission:gratuity.approve');
        Route::post('/gratuity/{id}/settlement', [GratuityController::class, 'settlement'])->name('gratuity.settlement')->middleware('permission:gratuity.approve');

        // Comprehensive Tenant Settings Portal
        Route::prefix('settings')->name('settings.')->middleware('permission:settings.view')->group(function () {
            Route::get('/', [TenantSettingsHubController::class, 'overview'])->name('index');
            Route::get('/company', [TenantSettingsHubController::class, 'companyProfile'])->name('company.profile');
            Route::post('/company', [TenantSettingsHubController::class, 'updateCompanyProfile'])->name('company.update')->middleware('permission:settings.edit');
            Route::get('/branches', [BranchController::class, 'index'])->name('branches.index');
            Route::post('/branches', [BranchController::class, 'store'])->name('branches.store')->middleware('permission:settings.edit');
            Route::delete('/branches/{id}', [BranchController::class, 'destroy'])->name('branches.destroy')->middleware('permission:settings.edit');
            Route::post('/branches/{id}/working-hours', [BranchController::class, 'updateWorkingHours'])->name('branches.working_hours')->middleware('permission:settings.edit');
            Route::get('/departments', [DepartmentCounterController::class, 'departments'])->name('departments.index');
            Route::post('/departments', [DepartmentCounterController::class, 'storeDepartment'])->name('departments.store')->middleware('permission:settings.edit');
            Route::get('/counters', [DepartmentCounterController::class, 'counters'])->name('counters.index');
            Route::post('/counters', [DepartmentCounterController::class, 'storeCounter'])->name('counters.store')->middleware('permission:settings.edit');
            Route::post('/counters/{id}/status', [DepartmentCounterController::class, 'toggleCounterStatus'])->name('counters.toggle_status')->middleware('permission:settings.edit');
            Route::get('/billing', [BillingSettingsController::class, 'billing'])->name('billing.index');
            Route::post('/billing', [BillingSettingsController::class, 'updateBillingProfile'])->name('billing.update')->middleware('permission:settings.edit');
            Route::get('/invoice-design', [BillingSettingsController::class, 'invoiceDesign'])->name('invoice_design');
            Route::post('/invoice-design', [BillingSettingsController::class, 'updateInvoiceDesign'])->name('invoice_design.update')->middleware('permission:settings.edit');
            Route::get('/services', [ServiceCatalogController::class, 'index'])->name('services.index');
            Route::get('/services/create', [ServiceCatalogController::class, 'create'])->name('services.create');
            Route::post('/services', [ServiceCatalogController::class, 'store'])->name('services.store')->middleware('permission:settings.edit');
            Route::get('/documents', [TenantSettingsHubController::class, 'documentTypes'])->name('documents.index');
            Route::get('/renewals', [TenantSettingsHubController::class, 'renewals'])->name('renewals.index');
            Route::get('/communication', [TenantSettingsHubController::class, 'communication'])->name('communication.index');
            Route::post('/communication', [TenantSettingsHubController::class, 'updateCommunication'])->name('communication.update')->middleware('permission:settings.edit');
            Route::get('/branding', [TenantSettingsHubController::class, 'branding'])->name('branding.index');
            Route::get('/operations', [TenantSettingsHubController::class, 'operations'])->name('operations.index');
            Route::get('/hr-payroll', [TenantSettingsHubController::class, 'hr'])->name('hr.index');
            Route::post('/hr-payroll', [TenantSettingsHubController::class, 'updateHr'])->name('hr.update')->middleware('permission:settings.edit');
            Route::get('/search', [TenantSettingsHubController::class, 'searchSettings'])->name('search');
        });
    });

    // 3. External Portals Placeholders (/portal/* and /corporate/*)
    Route::get('/portal/dashboard', fn () => view('portal.dashboard'))->name('portal.dashboard');
    Route::get('/corporate/dashboard', fn () => view('corporate.dashboard'))->name('corporate.dashboard');
});
