<?php

use App\Livewire\Activities\ActivityForm;
use App\Livewire\Activities\ActivityList;
use App\Livewire\Admin\SuperAdminPanel;
use App\Livewire\Receptionist\CollectPaymentWizard;
use App\Livewire\Receptionist\EnrollExistingWizard;
use App\Livewire\Receptionist\NewRegistrationWizard;
use App\Livewire\Receptionist\ReceptionistDashboard;
use App\Livewire\Guardian\GuardianDashboard;
use App\Livewire\Trainer\TrainerDashboard;
use App\Livewire\Wizards\SetupWizard;
use App\Livewire\Assignments\AssignmentForm;
use App\Livewire\Assignments\AssignmentList;
use App\Livewire\Attendance\AttendanceList;
use App\Livewire\Attendance\TakeAttendance;
use App\Livewire\Audit\AuditLogList;
use App\Livewire\Evaluations\EvaluationCriteriaList;
use App\Livewire\Evaluations\EvaluationForm;
use App\Livewire\Evaluations\EvaluationList;
use App\Livewire\Evaluations\EvaluationShow;
use App\Livewire\Facilities\FacilityForm;
use App\Livewire\Facilities\FacilityList;
use App\Livewire\Facilities\FacilityShow;
use App\Livewire\Facilities\VisualScheduleBuilder;
use App\Livewire\Financial\FinancialOverview;
use App\Livewire\Auth\Login;
use App\Livewire\CashSessions\CashSessionList;
use App\Livewire\CashSessions\CashSessionManage;
use App\Livewire\Dashboard;
use App\Livewire\Enrollments\EnrollmentForm;
use App\Livewire\Enrollments\EnrollmentList;
use App\Livewire\Enrollments\TransferGroup;
use App\Livewire\Enrollments\WaitlistManager;
use App\Livewire\Groups\GroupForm;
use App\Livewire\Groups\GroupList;
use App\Livewire\Groups\GroupShow;
use App\Livewire\Invoices\InvoiceCreate;
use App\Livewire\Invoices\InvoiceList;
use App\Livewire\Invoices\InvoiceShow;
use App\Livewire\Notifications\NotificationCenter;
use App\Livewire\Notifications\NotificationLogList;
use App\Livewire\Notifications\NotificationTemplateForm;
use App\Livewire\Notifications\NotificationTemplateList;
use App\Livewire\Participants\ParticipantForm;
use App\Livewire\Participants\ParticipantList;
use App\Livewire\Participants\ParticipantShow;
use App\Livewire\People\PersonForm;
use App\Livewire\People\PersonList;
use App\Livewire\People\PersonShow;
use App\Livewire\POS\POSHistory;
use App\Livewire\POS\POSTerminal;
use App\Livewire\Pricing\BasePriceForm;
use App\Livewire\Pricing\BasePriceList;
use App\Livewire\Pricing\PricingRuleForm;
use App\Livewire\Pricing\PricingRuleList;
use App\Livewire\Pricing\PromotionForm;
use App\Livewire\Pricing\PromotionList;
use App\Livewire\Programs\ProgramForm;
use App\Livewire\Programs\ProgramList;
use App\Livewire\Programs\ProgramShow;
use App\Livewire\Settings\ReceiptSettings;
use App\Livewire\Inventory\MovementList;
use App\Livewire\Inventory\ProductForm as InventoryProductForm;
use App\Livewire\Inventory\ProductList as InventoryProductList;
use App\Livewire\Inventory\StockAdjustmentWizard;
use App\Livewire\Inventory\WarehouseForm as InventoryWarehouseForm;
use App\Livewire\Inventory\WarehouseList as InventoryWarehouseList;
use App\Livewire\Wallets\WalletList;
use App\Livewire\Wallets\WalletShow;
use App\Http\Controllers\ContactFormController;
use App\Http\Controllers\PublicDocumentController;
use App\Http\Controllers\PublicWebsiteController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Public Routes
|--------------------------------------------------------------------------
*/
Route::get('/health', \App\Http\Controllers\HealthController::class)->name('health');

// Public document routes (signed URLs, no auth required)
Route::prefix('public')->name('public.')->group(function () {
    Route::get('/invoice/{uuid}', [PublicDocumentController::class, 'invoice'])->name('invoice');
    Route::get('/receipt/{uuid}', [PublicDocumentController::class, 'receipt'])->name('receipt');
    Route::get('/pos-receipt/{uuid}', [PublicDocumentController::class, 'posReceipt'])->name('pos-receipt');
});

// Public Academy Website — serves as home page
Route::get('/', [\App\Http\Controllers\WebsitePageController::class, 'homeOrLegacy'])->name('home');
Route::middleware(\App\Http\Middleware\ResolveAcademyFromSlug::class)
    ->prefix('site/{slug}')
    ->name('website.')
    ->group(function () {
        Route::get('/', [PublicWebsiteController::class, 'show'])->name('show');
        Route::post('/contact', [ContactFormController::class, 'submit'])->name('contact.submit');
        Route::get('/events', [\App\Http\Controllers\PublicEventController::class, 'index'])->name('events.index');
        Route::get('/events/{eventSlug}', [\App\Http\Controllers\PublicEventController::class, 'show'])->name('events.show');
        Route::get('/news', [PublicWebsiteController::class, 'newsIndex'])->name('news.index');
        Route::get('/news/{news}', [PublicWebsiteController::class, 'newsShow'])->name('news.show');
    });

/*
|--------------------------------------------------------------------------
| Guest Routes
|--------------------------------------------------------------------------
*/
Route::middleware('guest')->group(function () {
    Route::get('/login', Login::class)->name('login');
});

/*
|--------------------------------------------------------------------------
| Authenticated Routes
|--------------------------------------------------------------------------
*/
Route::middleware('auth')->group(function () {
    // Setup Wizard
    Route::get('/setup', SetupWizard::class)->name('setup.wizard')
        ->middleware('permission:settings.manage');

    // Dashboard
    Route::get('/dashboard', Dashboard::class)->name('dashboard');

    // Profile
    Route::get('/profile', \App\Livewire\Profile\UserProfile::class)->name('profile');
    Route::get('/profile/notifications', \App\Livewire\Profile\NotificationPreferences::class)->name('profile.notifications');

    // Logout
    Route::post('/logout', function () {
        Auth::logout();
        session()->invalidate();
        session()->regenerateToken();
        return redirect()->route('login');
    })->name('logout');

    // Branches
    Route::get('/branches', \App\Livewire\Branches\BranchList::class)->name('branches.list')
        ->middleware('permission:branches.list');
    Route::get('/branches/create', \App\Livewire\Branches\BranchForm::class)->name('branches.create')
        ->middleware('permission:branches.create');
    Route::get('/branches/{branch}/edit', \App\Livewire\Branches\BranchForm::class)->name('branches.edit')
        ->middleware('permission:branches.update');

    // People
    Route::get('/people', PersonList::class)->name('people.list')
        ->middleware('permission:participants.list');
    Route::get('/people/create', PersonForm::class)->name('people.create')
        ->middleware('permission:participants.create');
    Route::get('/people/{person}', PersonShow::class)->name('people.show')
        ->middleware('permission:participants.view');
    Route::get('/people/{person}/edit', PersonForm::class)->name('people.edit')
        ->middleware('permission:participants.update');

    // Users
    Route::get('/users', \App\Livewire\Users\UserList::class)->name('users.list')
        ->middleware('permission:users.list');
    Route::get('/users/create', \App\Livewire\Users\UserForm::class)->name('users.create')
        ->middleware('permission:users.create');
    Route::get('/users/{user}/edit', \App\Livewire\Users\UserForm::class)->name('users.edit')
        ->middleware('permission:users.update');

    // Roles
    Route::get('/roles', \App\Livewire\Roles\RoleList::class)->name('roles.list')
        ->middleware('permission:roles.list');
    Route::get('/roles/matrix', \App\Livewire\Roles\PermissionMatrix::class)->name('roles.matrix')
        ->middleware('permission:roles.list');
    Route::get('/roles/compare', \App\Livewire\Roles\RoleComparison::class)->name('roles.compare')
        ->middleware('permission:roles.list');
    Route::get('/roles/create', \App\Livewire\Roles\RoleForm::class)->name('roles.create')
        ->middleware('permission:roles.create');
    Route::get('/roles/{role}/edit', \App\Livewire\Roles\RoleForm::class)->name('roles.edit')
        ->middleware('permission:roles.update');

    // Participants
    Route::get('/participants', ParticipantList::class)->name('participants.list')
        ->middleware('permission:participants.list');
    Route::get('/participants/import', \App\Livewire\Participants\ParticipantImport::class)->name('participants.import')
        ->middleware('permission:participants.create');
    Route::get('/participants/create', ParticipantForm::class)->name('participants.create')
        ->middleware('permission:participants.create');
    // Must stay above /participants/{participant}: a literal segment
    // registered after a wildcard never matches — the wildcard takes 'pending'
    // and fails resolving it as a model, which is a 500 rather than a 404 and
    // so does not even look like a routing problem.
    Route::get('/participants/pending', \App\Livewire\Participants\PendingRegistrations::class)
        ->middleware('permission:participants.update')
        ->name('participants.pending');

    Route::get('/participants/{participant}', ParticipantShow::class)->name('participants.show')
        ->middleware('permission:participants.view');
    Route::get('/participants/{participant}/edit', ParticipantForm::class)->name('participants.edit')
        ->middleware('permission:participants.update');

    // Activities
    Route::get('/activities', ActivityList::class)->name('activities.list')
        ->middleware('permission:activities.list');
    Route::get('/activities/create', ActivityForm::class)->name('activities.create')
        ->middleware('permission:activities.create');
    Route::get('/activities/{activity}/edit', ActivityForm::class)->name('activities.edit')
        ->middleware('permission:activities.update');

    // Training Programs
    Route::get('/programs', ProgramList::class)->name('programs.list')
        ->middleware('permission:programs.list');
    Route::get('/programs/create', ProgramForm::class)->name('programs.create')
        ->middleware('permission:programs.create');
    Route::get('/programs/{program}', ProgramShow::class)->name('programs.show')
        ->middleware('permission:programs.list');
    Route::get('/programs/{program}/edit', ProgramForm::class)->name('programs.edit')
        ->middleware('permission:programs.update');

    // Training Groups
    Route::get('/groups', GroupList::class)->name('groups.list')
        ->middleware('permission:groups.list');
    Route::get('/groups/wizard', \App\Livewire\Groups\CreateGroupWizard::class)->name('groups.wizard')
        ->middleware('permission:groups.create');
    Route::get('/groups/create', GroupForm::class)->name('groups.create')
        ->middleware('permission:groups.create');
    Route::get('/groups/{group}', GroupShow::class)->name('groups.show')
        ->middleware('permission:groups.list');
    Route::get('/groups/{group}/edit', GroupForm::class)->name('groups.edit')
        ->middleware('permission:groups.update');

    // Enrollments
    Route::get('/enrollments', EnrollmentList::class)->name('enrollments.list')
        ->middleware('permission:enrollments.list');
    Route::get('/enrollments/waitlist', WaitlistManager::class)->name('enrollments.waitlist')
        ->middleware('permission:enrollments.list');
    Route::get('/enrollments/create', EnrollmentForm::class)->name('enrollments.create')
        ->middleware('permission:enrollments.create');
    Route::get('/enrollments/transfer', TransferGroup::class)->name('enrollments.transfer')
        ->middleware('permission:enrollments.create');
    Route::get('/enrollments/transfer-wizard', \App\Livewire\Enrollments\TransferParticipantWizard::class)->name('enrollments.transfer-wizard')
        ->middleware('permission:enrollments.create');

    // Wallets
    Route::get('/wallets', WalletList::class)->name('wallets.list')
        ->middleware('permission:wallets.list');
    Route::get('/wallets/{wallet}', WalletShow::class)->name('wallets.show')
        ->middleware('permission:wallets.view');

    // Cash Sessions
    Route::get('/cash-sessions', CashSessionList::class)->name('cash-sessions.list')
        ->middleware('permission:cash_sessions.list');
    Route::get('/cash-sessions/manage', CashSessionManage::class)->name('cash-sessions.manage')
        ->middleware('permission:cash_sessions.manage');

    // Financial Overview
    Route::get('/financial-overview', FinancialOverview::class)->name('financial.overview')
        ->middleware('permission:invoices.list');

    // Revenue routing — which ledger account every collected pound lands in,
    // and what part of it was tax. Gated on view; the screen itself hides every
    // control that writes unless the user also holds revenue_routing.manage.
    Route::get('/revenue-routing', \App\Livewire\Financial\RevenueRouting::class)->name('financial.revenue-routing')
        ->middleware('permission:revenue_routing.view');

    // Expenses
    Route::get('/expenses', \App\Livewire\Financial\ExpenseList::class)->name('expenses.list')
        ->middleware('permission:expenses.create');
    Route::get('/expenses/create', \App\Livewire\Financial\ExpenseForm::class)->name('expenses.create')
        ->middleware('permission:expenses.create');
    Route::get('/expenses/{expense}/attachment', [\App\Http\Controllers\ExpenseAttachmentController::class, 'show'])
        ->name('expenses.attachment')->middleware('permission:expenses.create');
    Route::get('/expenses/{expense}/attachment/download', [\App\Http\Controllers\ExpenseAttachmentController::class, 'download'])
        ->name('expenses.attachment.download')->middleware('permission:expenses.create');
    Route::get('/expenses/rent', \App\Livewire\Financial\FacilityRentList::class)->name('expenses.rent.list')
        ->middleware('permission:facilities.update');
    Route::get('/expenses/rent/create', \App\Livewire\Financial\FacilityRentForm::class)->name('expenses.rent.create')
        ->middleware('permission:facilities.update');
    // Registered after the literal /expenses/* routes so `create` and `rent`
    // are not swallowed by the {uuid} wildcard.
    Route::get('/expenses/{uuid}', \App\Livewire\Financial\ExpenseShow::class)->name('expenses.show')
        ->middleware('permission:expenses.create');
    Route::get('/revenue/external', \App\Livewire\Financial\ExternalRevenueForm::class)->name('revenue.external.create')
        ->middleware('permission:expenses.create');

    // Invoices
    Route::get('/invoices', InvoiceList::class)->name('invoices.list')
        ->middleware('permission:invoices.list');
    Route::get('/invoices/wizard', \App\Livewire\Invoices\CreateInvoiceWizard::class)->name('invoices.wizard')
        ->middleware('permission:invoices.create');
    Route::get('/invoices/create', InvoiceCreate::class)->name('invoices.create')
        ->middleware('permission:invoices.create');
    Route::get('/invoices/{invoice}', InvoiceShow::class)->name('invoices.show')
        ->middleware('permission:invoices.view');

    // Facilities — static segments MUST come before {facility} wildcard
    Route::get('/facilities', FacilityList::class)->name('facilities.list')
        ->middleware('permission:facilities.list');
    Route::get('/facilities/wizard', \App\Livewire\Facilities\CreateFacilityWizard::class)->name('facilities.wizard')
        ->middleware('permission:facilities.create');
    Route::get('/facilities/create', FacilityForm::class)->name('facilities.create')
        ->middleware('permission:facilities.create');
    Route::get('/facilities/space-assignment', \App\Livewire\Facilities\SpaceAssignmentWizard::class)->name('facilities.space-assignment')
        ->middleware('permission:facilities.manage_layouts');
    Route::get('/facilities/schedule-builder', VisualScheduleBuilder::class)->name('facilities.schedule-builder')
        ->middleware('permission:schedules.manage');
    Route::get('/facilities/{facility}', FacilityShow::class)->name('facilities.show')
        ->middleware('permission:facilities.list');
    Route::get('/facilities/{facility}/edit', FacilityForm::class)->name('facilities.edit')
        ->middleware('permission:facilities.update');
    Route::get('/facilities/{facility}/layouts', \App\Livewire\Facilities\SpaceLayoutManager::class)->name('facilities.layouts')
        ->middleware('permission:facilities.manage_layouts');

    // Schedule
    Route::get('/schedule', \App\Livewire\Schedule\WeeklySchedule::class)->name('schedule.weekly')
        ->middleware('permission:schedules.view');

    // Attendance
    Route::get('/attendance', AttendanceList::class)->name('attendance.list')
        ->middleware('permission:attendance.list');
    Route::get('/attendance/quick', \App\Livewire\Attendance\QuickAttendance::class)->name('attendance.quick')
        ->middleware('permission:attendance.mark');
    // Must stay above /attendance/{session}: that route binds its parameter to
    // a uuid, so a literal segment registered after it never matches — the
    // wildcard takes 'scan' first and dies casting it to a uuid.
    Route::get('/attendance/scan', \App\Livewire\Attendance\CheckInScanner::class)->name('attendance.scan')
        ->middleware('permission:attendance.scan');
    Route::get('/attendance/{session}', TakeAttendance::class)->name('attendance.take')
        ->middleware('permission:attendance.mark');

    // HR - Employees
    Route::get('/hr/employees', \App\Livewire\HR\EmployeeList::class)->name('employees.list')
        ->middleware('permission:employees.list');
    Route::get('/hr/employees/wizard', \App\Livewire\HR\CreateEmployeeWizard::class)->name('employees.wizard')
        ->middleware('permission:employees.create');
    Route::get('/hr/employees/create', \App\Livewire\HR\EmployeeForm::class)->name('employees.create')
        ->middleware('permission:employees.create');
    Route::get('/hr/employees/{employee}', \App\Livewire\HR\EmployeeShow::class)->name('employees.show')
        ->middleware('permission:employees.list');
    Route::get('/hr/employees/{employee}/edit', \App\Livewire\HR\EmployeeForm::class)->name('employees.edit')
        ->middleware('permission:employees.update');

    // HR - Trainers
    Route::get('/hr/trainers', \App\Livewire\HR\TrainerList::class)->name('trainers.list')
        ->middleware('permission:trainers.list');
    Route::get('/hr/trainers/wizard', \App\Livewire\HR\CreateTrainerWizard::class)->name('trainers.wizard')
        ->middleware('permission:trainers.create');
    Route::get('/hr/trainers/create', \App\Livewire\HR\TrainerForm::class)->name('trainers.create')
        ->middleware('permission:trainers.create');
    Route::get('/hr/trainers/{trainer}', \App\Livewire\HR\TrainerShow::class)->name('trainers.show')
        ->middleware('permission:trainers.list');
    Route::get('/hr/trainers/{trainer}/edit', \App\Livewire\HR\TrainerForm::class)->name('trainers.edit')
        ->middleware('permission:trainers.update');

    // Events
    Route::get('/events', \App\Livewire\Events\EventList::class)->name('events.list')
        ->middleware('permission:events.list');
    Route::get('/events/create', \App\Livewire\Events\CreateEventWizard::class)->name('events.create')
        ->middleware('permission:events.create');
    Route::get('/events/{event}', \App\Livewire\Events\EventShow::class)->name('events.show')
        ->middleware('permission:events.view');
    Route::get('/events/{event}/edit', \App\Livewire\Events\CreateEventWizard::class)->name('events.edit')
        ->middleware('permission:events.update');
    Route::get('/events/{event}/registrations', \App\Livewire\Events\EventRegistrationList::class)->name('events.registrations')
        ->middleware('permission:events.view');

    // HR - Payroll
    Route::get('/hr/payroll', \App\Livewire\HR\PayrollDashboard::class)->name('payroll.dashboard')
        ->middleware('permission:payroll.manage');
    Route::get('/hr/payroll/trainer/{trainer}/compensations', \App\Livewire\HR\TrainerCompensations::class)->name('payroll.trainer-compensations')
        ->middleware('permission:payroll.manage');
    Route::get('/hr/payroll/payslip/{payslip}', \App\Livewire\HR\PayslipDetail::class)->name('payroll.payslip-detail')
        ->middleware('permission:payroll.manage');
    Route::get('/hr/advances', \App\Livewire\HR\TrainerAdvances::class)->name('payroll.advances')
        ->middleware('permission:payroll.manage');

    // Assignments
    Route::get('/assignments', AssignmentList::class)->name('assignments.list')
        ->middleware('permission:assignments.list');
    Route::get('/assignments/create', AssignmentForm::class)->name('assignments.create')
        ->middleware('permission:assignments.create');

    // Pricing — Base Prices
    Route::get('/pricing/base-prices', BasePriceList::class)->name('pricing.base-prices')
        ->middleware('permission:pricing.list');
    Route::get('/pricing/base-prices/create', BasePriceForm::class)->name('pricing.base-prices.create')
        ->middleware('permission:pricing.create');
    Route::get('/pricing/base-prices/{basePrice}/edit', BasePriceForm::class)->name('pricing.base-prices.edit')
        ->middleware('permission:pricing.update');

    // Pricing — Rules
    Route::get('/pricing/rules', PricingRuleList::class)->name('pricing.rules')
        ->middleware('permission:pricing.list');
    Route::get('/pricing/rules/wizard', \App\Livewire\Pricing\CreatePricingRuleWizard::class)->name('pricing.rules.wizard')
        ->middleware('permission:pricing.create');
    Route::get('/pricing/rules/create', PricingRuleForm::class)->name('pricing.rules.create')
        ->middleware('permission:pricing.create');
    Route::get('/pricing/rules/{pricingRule}/edit', PricingRuleForm::class)->name('pricing.rules.edit')
        ->middleware('permission:pricing.update');

    // Pricing — Promotions
    Route::get('/pricing/promotions', PromotionList::class)->name('pricing.promotions')
        ->middleware('permission:pricing.list');
    Route::get('/pricing/promotions/create', PromotionForm::class)->name('pricing.promotions.create')
        ->middleware('permission:pricing.create');
    Route::get('/pricing/promotions/{promotion}/edit', PromotionForm::class)->name('pricing.promotions.edit')
        ->middleware('permission:pricing.update');

    // POS
    Route::get('/pos', POSTerminal::class)->name('pos.terminal')
        ->middleware('permission:pos.sell');
    Route::get('/pos/history', POSHistory::class)->name('pos.history')
        ->middleware('permission:pos.list');

    // Inventory
    Route::get('/inventory/products', InventoryProductList::class)->name('inventory.products')
        ->middleware('permission:inventory.list');
    Route::get('/inventory/products/wizard', \App\Livewire\Inventory\CreateProductWizard::class)->name('inventory.products.wizard')
        ->middleware('permission:inventory.create');
    Route::get('/inventory/products/create', InventoryProductForm::class)->name('inventory.products.create')
        ->middleware('permission:inventory.create');
    Route::get('/inventory/products/{product}', \App\Livewire\Inventory\ProductShow::class)->name('inventory.products.show')
        ->middleware('permission:inventory.list');
    Route::get('/inventory/products/{product}/edit', InventoryProductForm::class)->name('inventory.products.edit')
        ->middleware('permission:inventory.update');
    Route::get('/inventory/warehouses', InventoryWarehouseList::class)->name('inventory.warehouses')
        ->middleware('permission:inventory.list');
    Route::get('/inventory/warehouses/create', InventoryWarehouseForm::class)->name('inventory.warehouses.create')
        ->middleware('permission:inventory.create');
    Route::get('/inventory/warehouses/{warehouse}/edit', InventoryWarehouseForm::class)->name('inventory.warehouses.edit')
        ->middleware('permission:inventory.update');
    Route::get('/inventory/movements', MovementList::class)->name('inventory.movements')
        ->middleware('permission:inventory.list');
    Route::get('/inventory/adjustments', StockAdjustmentWizard::class)->name('inventory.adjustments')
        ->middleware('permission:inventory.adjust');
    Route::get('/inventory/kits', \App\Livewire\Inventory\KitList::class)->name('inventory.kits')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/kits/create', \App\Livewire\Inventory\KitForm::class)->name('inventory.kits.create')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/kits/{kit}/edit', \App\Livewire\Inventory\KitForm::class)->name('inventory.kits.edit')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/stock-counts', \App\Livewire\Inventory\StockCountList::class)->name('inventory.stock-counts')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/stock-counts/create', \App\Livewire\Inventory\StockCountForm::class)->name('inventory.stock-counts.create')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/stock-counts/{stockCount}/edit', \App\Livewire\Inventory\StockCountForm::class)->name('inventory.stock-counts.edit')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/purchase-orders', \App\Livewire\Inventory\PurchaseOrderList::class)->name('inventory.purchase-orders')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/purchase-orders/create', \App\Livewire\Inventory\CreatePurchaseOrderWizard::class)->name('inventory.purchase-orders.create')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/purchase-orders/{purchaseOrder}', \App\Livewire\Inventory\PurchaseOrderShow::class)->name('inventory.purchase-orders.show')
        ->middleware('permission:inventory.list');
    Route::get('/inventory/purchase-orders/{purchaseOrder}/edit', \App\Livewire\Inventory\PurchaseOrderForm::class)->name('inventory.purchase-orders.edit')
        ->middleware('permission:inventory.manage');
    Route::get('/inventory/essential-deliveries', \App\Livewire\Inventory\EssentialDeliveries::class)->name('inventory.essential-deliveries')
        ->middleware('permission:inventory.list');

    // Settings
    Route::get('/settings', \App\Livewire\Settings\AcademySettings::class)->name('settings.academy')
        ->middleware('permission:settings.view');

    // Messaging
    Route::get('/messaging', \App\Livewire\Messaging\BulkMessage::class)->name('messaging.bulk')
        ->middleware('permission:notifications.manage');

    // WhatsApp
    Route::get('/whatsapp/send', \App\Livewire\WhatsApp\SendMessage::class)->name('whatsapp.send')
        ->middleware('permission:notifications.manage');
    Route::get('/whatsapp/templates', \App\Livewire\WhatsApp\SendTemplate::class)->name('whatsapp.templates')
        ->middleware('permission:notifications.manage');
    Route::get('/whatsapp/log', \App\Livewire\WhatsApp\MessageLog::class)->name('whatsapp.log')
        ->middleware('permission:notifications.manage');

    // Notifications
    Route::get('/notifications', NotificationCenter::class)->name('notifications.center');
    Route::get('/notifications/templates', NotificationTemplateList::class)->name('notifications.templates')
        ->middleware('permission:notifications.manage');
    Route::get('/notifications/templates/create', NotificationTemplateForm::class)->name('notifications.templates.create')
        ->middleware('permission:notifications.manage');
    Route::get('/notifications/templates/{template}/edit', NotificationTemplateForm::class)->name('notifications.templates.edit')
        ->middleware('permission:notifications.manage');
    Route::get('/notifications/logs', NotificationLogList::class)->name('notifications.logs')
        ->middleware('permission:notifications.manage');

    // Reports
    Route::get('/reports', \App\Livewire\Reports\ReportsHub::class)->name('reports.hub')
        ->middleware('permission:reports.view');
    Route::get('/reports/view', \App\Livewire\Reports\ReportViewer::class)->name('reports.viewer')
        ->middleware('permission:reports.view');
    Route::get('/reports/legacy', \App\Livewire\Reports\ReportsPage::class)->name('reports.view')
        ->middleware('permission:reports.view');
    Route::get('/reports/financial', \App\Livewire\Reports\FinancialReport::class)->name('reports.financial')
        ->middleware('permission:reports.view');
    Route::get('/reports/attendance', \App\Livewire\Reports\AttendanceReport::class)->name('reports.attendance')
        ->middleware('permission:reports.attendance');
    Route::get('/reports/daily-print', [\App\Http\Controllers\ReportPrintController::class, 'dailyFinancial'])
        ->name('reports.daily-print')->middleware('permission:reports.view');

    // Evaluations
    Route::get('/evaluations', EvaluationList::class)->name('evaluations.list')
        ->middleware('permission:evaluations.list');
    Route::get('/evaluations/criteria', EvaluationCriteriaList::class)->name('evaluations.criteria')
        ->middleware('permission:evaluations.manage');
    Route::get('/evaluations/create', EvaluationForm::class)->name('evaluations.create')
        ->middleware('permission:evaluations.create');
    Route::get('/evaluations/{evaluation}', EvaluationShow::class)->name('evaluations.show')
        ->middleware('permission:evaluations.list');
    Route::get('/evaluations/{evaluation}/edit', EvaluationForm::class)->name('evaluations.edit')
        ->middleware('permission:evaluations.update');

    // System Settings
    Route::get('/settings/system', \App\Livewire\Admin\SystemSettings::class)->name('settings.system')
        ->middleware('permission:settings.manage');
    Route::get('/settings/branding', \App\Livewire\Settings\BrandingSettings::class)->name('settings.branding')
        ->middleware('permission:settings.manage');
    Route::get('/settings/receipts', ReceiptSettings::class)->name('settings.receipts')
        ->middleware('permission:settings.manage');
    Route::get('/settings/terminology', \App\Livewire\Settings\TerminologySettings::class)->name('settings.terminology')
        ->middleware('permission:settings.manage');

    // Receipt Print
    Route::get('/receipts/pos/{transaction}', [\App\Http\Controllers\ReceiptController::class, 'posPrint'])
        ->name('receipts.pos.print')
        ->middleware('permission:pos.sell');
    Route::get('/receipts/payment/{payment}', [\App\Http\Controllers\ReceiptController::class, 'paymentPrint'])
        ->name('receipts.payment.print')
        ->middleware('permission:invoices.view');

    // SuperAdmin
    Route::get('/admin', SuperAdminPanel::class)->name('admin.panel')
        ->middleware('permission:super_admin.access');
    Route::get('/admin/reconciliation', \App\Livewire\Admin\ReconciliationWizard::class)->name('admin.reconciliation')
        ->middleware('permission:super_admin.access');
    Route::get('/admin/invoice-correction', \App\Livewire\Admin\InvoiceCorrectionWizard::class)->name('admin.invoice-correction')
        ->middleware('permission:super_admin.access');

    // Account settlement — the worklist of accounts that do not add up, and the
    // wizard that settles one. Gated on settlements.manage rather than
    // super_admin.access: waiving a month is the academy's call to make, and an
    // owner should not need a platform administrator to make it.
    Route::get('/admin/settlements', \App\Livewire\Admin\SettlementWorklist::class)->name('admin.settlement-worklist')
        ->middleware('permission:settlements.manage');
    Route::get('/admin/settlements/account/{participant?}', \App\Livewire\Admin\AccountSettlementWizard::class)->name('admin.account-settlement')
        ->middleware('permission:settlements.manage');

    // Exports
    Route::get('/export/report', [\App\Http\Controllers\ExportController::class, 'report'])
        ->name('export.report')->middleware('permission:reports.view');
    Route::get('/export/participants', [\App\Http\Controllers\ExportController::class, 'participants'])
        ->name('export.participants')->middleware('permission:participants.list');
    Route::get('/export/payments', [\App\Http\Controllers\ExportController::class, 'payments'])
        ->name('export.payments')->middleware('permission:invoices.list');
    Route::get('/export/invoices', [\App\Http\Controllers\ExportController::class, 'invoices'])
        ->name('export.invoices')->middleware('permission:invoices.list');
    Route::get('/export/enrollments', [\App\Http\Controllers\ExportController::class, 'enrollments'])
        ->name('export.enrollments')->middleware('permission:enrollments.list');

    // Audit
    Route::get('/audit', AuditLogList::class)->name('audit.list')
        ->middleware('permission:audit.list');

    // Trainer Dashboard
    Route::get('/trainer', TrainerDashboard::class)->name('trainer.dashboard')
        ->middleware('permission:attendance.mark');

    // Receptionist Desk
    Route::get('/receptionist', ReceptionistDashboard::class)->name('receptionist.dashboard')
        ->middleware('permission:participants.list');
    Route::get('/receptionist/new-registration', NewRegistrationWizard::class)->name('receptionist.new-registration')
        ->middleware('permission:participants.create');
    Route::get('/receptionist/enroll-existing', EnrollExistingWizard::class)->name('receptionist.enroll-existing')
        ->middleware('permission:enrollments.create');
    Route::get('/receptionist/collect-payment', CollectPaymentWizard::class)->name('receptionist.collect-payment')
        ->middleware('permission:invoices.create');
    Route::get('/receptionist/retroactive-enrollment', \App\Livewire\Receptionist\RetroactiveEnrollmentWizard::class)->name('receptionist.retroactive-enrollment')
        ->middleware('permission:enrollments.create');

    // Financial — Payment Plans
    Route::get('/payment-plans/create', \App\Livewire\Financial\PaymentPlanCreate::class)->name('payment-plans.create')
        ->middleware('permission:invoices.create');

    // Print — Group Schedule, Participant Card, Invoice
    // Printable schedule sheets — branded HTML, printed from the browser.
    Route::get('/facilities/{facility}/print/day', [\App\Http\Controllers\SchedulePrintController::class, 'facilityDay'])
        ->name('facilities.print.day')->middleware('permission:schedules.view');
    Route::get('/facilities/{facility}/print/week', [\App\Http\Controllers\SchedulePrintController::class, 'facilityWeek'])
        ->name('facilities.print.week')->middleware('permission:schedules.view');
    Route::get('/schedule/print/trainers', [\App\Http\Controllers\SchedulePrintController::class, 'trainerDay'])
        ->name('schedule.print.trainers')->middleware('permission:schedules.view');

    Route::get('/groups/{group}/print', \App\Http\Controllers\GroupSchedulePrintController::class)->name('groups.print')
        ->middleware('permission:groups.list');
    Route::get('/participants/{participant}/card', \App\Http\Controllers\ParticipantCardController::class)->name('participants.card')
        ->middleware('permission:participants.view');
    Route::get('/invoices/{invoice}/print', \App\Http\Controllers\InvoicePrintController::class)->name('invoices.print')
        ->middleware('permission:invoices.view');


    // Certificates
    Route::get('/participants/{participant}/certificate/{enrollment}', [\App\Http\Controllers\CertificateController::class, 'attendance'])
        ->name('participants.certificate')
        ->middleware('permission:participants.view');

    // Activity Log (Admin)
    Route::get('/admin/activity-log', \App\Livewire\Admin\ActivityLog::class)->name('admin.activity-log')
        ->middleware('permission:audit.view');
    Route::get('/admin/system-settings', \App\Livewire\Admin\SystemSettings::class)->name('admin.system-settings')
        ->middleware('permission:settings.manage');

    // Documents
    Route::get('/documents/upload/{documentableType}/{documentableId}', \App\Livewire\Documents\DocumentUploadWizard::class)
        ->name('documents.upload')->middleware('permission:documents.upload');
    Route::get('/documents/approvals', \App\Livewire\Documents\DocumentApprovalList::class)
        ->name('documents.approvals')->middleware('permission:documents.approve');
    Route::get('/documents/{document}/review', \App\Livewire\Documents\DocumentApproval::class)
        ->name('documents.review')->middleware('permission:documents.approve');
    Route::get('/documents/{document}/view', [\App\Http\Controllers\DocumentController::class, 'show'])
        ->name('documents.view')->middleware('permission:documents.view');
    Route::get('/documents/{document}/download', [\App\Http\Controllers\DocumentController::class, 'download'])
        ->name('documents.download')->middleware('permission:documents.view');

    // Guardian Portal (legacy — redirects to new parent portal)
    Route::get('/guardian', GuardianDashboard::class)->name('guardian.dashboard')
        ->middleware('permission:dashboard.view');

    // ─── Website CMS ─────────────────────────────────────────────
    Route::prefix('website')->name('website.manage.')->middleware('permission:settings.manage')->group(function () {
        Route::get('/', \App\Livewire\Website\SectionManager::class)->name('sections');
        Route::get('/pages', \App\Livewire\Website\PageManager::class)->name('pages');
        Route::get('/pages/{page}/builder', \App\Livewire\Website\PageBuilder::class)->name('builder');
        Route::get('/menus', \App\Livewire\Website\MenuManager::class)->name('menus');
        Route::get('/theme', \App\Livewire\Website\ThemeEditor::class)->name('theme');
        Route::get('/preview', [PublicWebsiteController::class, 'preview'])->name('preview');
        Route::get('/pages/{page}/preview', [\App\Http\Controllers\WebsitePageController::class, 'preview'])->name('pages.preview');
        Route::get('/testimonials', \App\Livewire\Website\TestimonialManager::class)->name('testimonials');
        Route::get('/faqs', \App\Livewire\Website\FaqManager::class)->name('faqs');
        Route::get('/news', \App\Livewire\Website\NewsManager::class)->name('news');
        Route::get('/partners', \App\Livewire\Website\PartnerManager::class)->name('partners');
        Route::get('/gallery', \App\Livewire\Website\GalleryManager::class)->name('gallery');
        Route::get('/contacts', \App\Livewire\Website\ContactSubmissionList::class)->name('contacts');
    });

    // ─── Transfer reconciliation ────────────────────────────────
    // A screenshot is not evidence; reconciliation is. This is where the
    // system's transfer total meets the academy's own bank statement.
    Route::get('/reports/transfer-reconciliation', \App\Livewire\Financial\TransferReconciliation::class)
        ->middleware('permission:reports.financial')
        ->name('reports.transfer-reconciliation');

    // ─── Member requests ────────────────────────────────────────
    // One queue for freezes, transfers, cancellations, renewals and excuses.
    // They are one interaction, and two queues is how one of them ends up
    // built and the other left as a TODO.
    Route::get('/service-requests', \App\Livewire\Requests\ServiceRequestQueue::class)
        ->middleware('permission:participants.update')
        ->name('service-requests.index');

    // ─── Portal invitations & duplicate merge ───────────────────
    Route::get('/portal-invitations', \App\Livewire\Portal\PortalInvitationManager::class)
        ->middleware('permission:users.create')
        ->name('portal-invitations.index');

    Route::get('/users/duplicates', \App\Livewire\Users\DuplicateAccountMerge::class)
        ->middleware('permission:users.merge')
        ->name('users.duplicates');

    // ─── InstaPay transfer proofs ───────────────────────────────
    // The review queue ships before the member-facing upload: a proof that can
    // be submitted and never reviewed is a promise nobody is keeping.
    Route::get('/payment-proofs', \App\Livewire\Financial\PaymentProofQueue::class)
        ->middleware('permission:payments.approve_proof')
        ->name('payment-proofs.index');

    /*
    | ─── Parents Portal — retired, redirecting ──────────────────
    |
    | The member portal at /app replaces this. Two member portals must not
    | coexist: they diverge, and the one nobody is updating is the one a member
    | happens to have bookmarked.
    |
    | These are permanent redirects rather than deletions because members have
    | these URLs in their history, in WhatsApp messages and on paper. The
    | components stay in the tree for one release so a redirect that turns out
    | to be wrong can be answered by reading what the old screen did.
    |
    | ParentExcuseForm is the one route that is NOT redirected to an equivalent:
    | it validated an excuse, stored the attachment to the public disk and then
    | discarded the record behind a `// TODO` while telling the parent
    | "تم تقديم العذر بنجاح". It never worked, so there is nothing to preserve
    | — its members go to the request form, which does.
    */
    Route::prefix('parent')->name('parent.')->group(function () {
        Route::redirect('/', '/app')->name('home');
        Route::redirect('/schedule', '/app/training')->name('schedule');
        Route::redirect('/attendance', '/app/training?v=past')->name('attendance');
        Route::redirect('/finances', '/app/payments')->name('finances');
        Route::redirect('/profile', '/app/account')->name('profile');
        Route::redirect('/notifications', '/app/notifications')->name('notifications');
        Route::redirect('/programs', '/app/academy?tab=programs')->name('programs');
        Route::redirect('/excuses/create', '/app/requests/new')->name('excuses.create');

        // Detail routes keep their parameter so a bookmarked invoice still
        // lands on that invoice rather than on a list.
        Route::get('/finances/{invoice}', fn (string $invoice) => redirect()->route('portal.invoice', $invoice))
            ->name('finances.invoice');
        Route::get('/profile/child/{participant}', fn () => redirect()->route('portal.account'))
            ->name('profile.child');
        Route::get('/evaluations/{evaluation}', fn () => redirect()->route('portal.training'))
            ->name('evaluations.show');
    });
});

/*
|--------------------------------------------------------------------------
| Member portal  (/app)
|--------------------------------------------------------------------------
| The member-facing portal — players and guardians — session-authenticated on
| the web guard, so CSRF and one logout path come free.
|
| It replaces /parent, which stays live and redirects until the portal reaches
| parity. Two member portals must not coexist any longer than that.
|
| The manifest is deliberately outside the auth group: a PWA fetches it before
| anyone signs in, and it carries only public branding.
*/
Route::get('/app/manifest.webmanifest', \App\Http\Controllers\Portal\ManifestController::class)
    ->name('portal.manifest');

// The worker is under /app/ because a worker's scope is its own directory: at
// the root it would control /dashboard and /api too.
Route::get('/app/sw.js', \App\Http\Controllers\Portal\ServiceWorkerController::class)
    ->name('portal.sw');

// The only offline artifact. Static, session-free, no CSRF token — it is
// cached and served to whoever opens the app next.
Route::view('/app/offline', 'portal.offline')->name('portal.offline');

/*
| The native shell's two endpoints, and deliberately only two.
|
| The shell wraps the web portal, so it needs no API — it needs somewhere to
| keep a credential across launches and a way to turn that into the ordinary
| web session everything else already uses. `/app/*` is never exempted from
| CSRF: the shell exchanges its token for a session and then behaves like a
| browser, which is the whole reason this is safe.
|
| These are the only routes on the sanctum guard. The deleted API minted tokens
| with `mobile:*` — every endpoint it would ever grow; this one issues
| `portal:session` and nothing else.
*/
// Deep-link verification. nginx serves both through PHP with an exact-match
// location and no redirect — a 301 to a canonical host is enough for the
// platform to refuse verification, silently.
Route::get('/.well-known/assetlinks.json', [\App\Http\Controllers\Portal\AppAssociationController::class, 'assetlinks'])
    ->name('portal.assetlinks');
Route::get('/.well-known/apple-app-site-association', [\App\Http\Controllers\Portal\AppAssociationController::class, 'appleAppSiteAssociation'])
    ->name('portal.aasa');

Route::post('/app/native/token', [\App\Http\Controllers\Portal\NativeSessionController::class, 'issueToken'])
    ->middleware('throttle:10,1')
    ->name('portal.native.token');

Route::middleware(['auth:sanctum', 'ability:portal:session'])->group(function () {
    Route::get('/app/session-exchange', [\App\Http\Controllers\Portal\NativeSessionController::class, 'exchange'])
        ->name('portal.session-exchange');
    Route::post('/app/native/revoke', [\App\Http\Controllers\Portal\NativeSessionController::class, 'revoke'])
        ->name('portal.native.revoke');
});

// Public self-registration. Shipped OFF: the middleware 404s unless an academy
// has deliberately enabled it, so no client's signup form opens because a
// deploy happened. 404 rather than 403 — a disabled feature should be
// indistinguishable from one that does not exist.
Route::middleware(['guest', 'self_registration', 'throttle:20,1'])
    ->get('/app/join', \App\Livewire\Portal\PortalSignUp::class)
    ->name('portal.join');

// Activation is a plain controller, not Livewire: a single-use token held in a
// public property is serialised into the page on every round-trip.
Route::middleware('guest')->group(function () {
    Route::get('/app/activate/{token}', [\App\Http\Controllers\Portal\InvitationController::class, 'show'])
        ->name('portal.activate');
    Route::post('/app/activate/{token}', [\App\Http\Controllers\Portal\InvitationController::class, 'store'])
        ->name('portal.activate.store');
});

Route::middleware(['auth', 'permission:portal.access'])
    ->prefix('app')
    ->name('portal.')
    ->group(function () {
        Route::get('/', \App\Livewire\Portal\PortalHome::class)->name('home');
        Route::get('/training', \App\Livewire\Portal\PortalTraining::class)->name('training');
        Route::get('/payments', \App\Livewire\Portal\PortalPayments::class)->name('payments');
        Route::get('/payments/invoice/{invoice}', \App\Livewire\Portal\PortalInvoice::class)->name('invoice');
        Route::get('/academy', \App\Livewire\Portal\PortalAcademy::class)->name('academy');
        Route::get('/account', \App\Livewire\Portal\PortalAccount::class)->name('account');
        Route::get('/notifications', \App\Livewire\Portal\PortalNotifications::class)->name('notifications');
        Route::get('/pass', \App\Livewire\Portal\PortalPass::class)->name('pass');
        Route::get('/dues', \App\Livewire\Portal\PortalDues::class)->name('dues');
        Route::get('/privacy', \App\Livewire\Portal\PortalPrivacy::class)->name('privacy');
        Route::get('/preferences', \App\Livewire\Portal\PortalPreferences::class)->name('preferences');

        Route::get('/documents', \App\Livewire\Portal\PortalDocuments::class)
            ->middleware('permission:portal.documents')
            ->name('documents');

        Route::get('/requests/new/{session?}', \App\Livewire\Portal\PortalRequests::class)
            ->middleware('permission:portal.requests')
            ->name('requests.create');

        Route::get('/payments/invoice/{invoice}/transfer', \App\Livewire\Portal\PortalPayProof::class)
            ->middleware('permission:portal.pay')
            ->name('invoice.transfer');

        // Push registration is a session route with CSRF, not an API endpoint:
        // the portal is session-authenticated and the native shell carries the
        // portal's own cookie, so there is nothing for a second identity system
        // to do.
        Route::get('/push/config', [\App\Http\Controllers\Portal\DeviceTokenController::class, 'config'])->name('push.config');
        Route::post('/push/token', [\App\Http\Controllers\Portal\DeviceTokenController::class, 'store'])->name('push.token');
        Route::delete('/push/token', [\App\Http\Controllers\Portal\DeviceTokenController::class, 'destroy'])->name('push.token.destroy');
    });

// Member uploads live on the private disk and are streamed, never linked. A
// transfer proof carries a phone number, a name and a bank balance; a medical
// certificate is the most sensitive thing this product holds.
Route::middleware('auth')->group(function () {
    Route::get('/proofs/{uuid}', \App\Http\Controllers\Financial\PaymentProofFileController::class)
        ->name('proofs.file');
    Route::get('/request-files/{uuid}', [\App\Http\Controllers\MemberFileController::class, 'requestAttachment'])
        ->name('requests.attachment');
    Route::get('/document-files/{uuid}', [\App\Http\Controllers\MemberFileController::class, 'document'])
        ->name('documents.file');
});

/*
|--------------------------------------------------------------------------
| Website builder pages (must stay last)
|--------------------------------------------------------------------------
| Registered after every other web route so an editor-created slug can never
| shadow a real application route. WebsitePageService also rejects reserved
| slugs at creation time, so this is defence in depth rather than the only guard.
*/
Route::fallback([\App\Http\Controllers\WebsitePageController::class, 'fallback'])
    ->name('website.page.show');
