<?php

use Illuminate\Support\Facades\Route;
use Modules\Vrc\Http\Controllers\AppointmentController;
use Modules\Vrc\Http\Controllers\BayController;
use Modules\Vrc\Http\Controllers\EstimateController;
use Modules\Vrc\Http\Controllers\InspectionController;
use Modules\Vrc\Http\Controllers\PortalEstimateController;
use Modules\Vrc\Http\Controllers\PortalTrackController;
use Modules\Vrc\Http\Controllers\InspectionTemplateController;
use Modules\Vrc\Http\Controllers\RepairOrderController;
use Modules\Vrc\Http\Controllers\ServiceCategoryController;
use Modules\Vrc\Http\Controllers\ServiceController;
use Modules\Vrc\Http\Controllers\ServicePackageController;
use Modules\Vrc\Http\Controllers\SettingController;
use Modules\Vrc\Http\Controllers\TechnicianController;
use Modules\Vrc\Http\Controllers\VehicleController;
use Modules\Vrc\Http\Controllers\VehicleMakeController;
use Modules\Vrc\Http\Controllers\VehicleModelController;
use Modules\Vrc\Http\Controllers\VrcController;

/*
|--------------------------------------------------------------------------
| VRC Back-Office (Blade, inside the ERP UI)
|--------------------------------------------------------------------------
| Session-authenticated routes rendered with the ERP master layout. Mirrors
| the BMS module's web route group (same middleware stack). All routes are
| prefixed `vrc/` and named `vrc.*` and guarded by `vrc.*` permissions inside
| the controllers. New resource routes are added phase-by-phase (spec §10).
*/
Route::middleware(['web', 'auth', 'SetSessionData', 'language', 'timezone', 'AdminSidebarMenu', 'module:Vrc', 'vrc.2fa'])
    ->prefix('vrc')
    ->name('vrc.')
    ->group(function () {
        Route::get('/', [VrcController::class, 'index'])->name('dashboard');

        // Vehicles (on ERP customers)
        Route::get('vehicle-models', [VehicleController::class, 'models'])->name('vehicle-models'); // JSON dependent dropdown
        Route::get('vehicles', [VehicleController::class, 'index'])->name('vehicles.index');
        Route::get('vehicles/create', [VehicleController::class, 'create'])->name('vehicles.create');
        Route::post('vehicles', [VehicleController::class, 'store'])->name('vehicles.store');
        Route::get('vehicles/{id}', [VehicleController::class, 'show'])->name('vehicles.show');
        Route::get('vehicles/{id}/edit', [VehicleController::class, 'edit'])->name('vehicles.edit');
        Route::put('vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update');
        Route::delete('vehicles/{id}', [VehicleController::class, 'destroy'])->name('vehicles.destroy');
        Route::get('vehicles/{id}/history', [VehicleController::class, 'history'])->name('vehicles.history');
        Route::get('vehicles/{id}/warranties', [VehicleController::class, 'warranties'])->name('vehicles.warranties');
        Route::get('customers/{erpId}/vehicles', [VehicleController::class, 'customerVehicles'])->name('customers.vehicles'); // JSON
        Route::post('vehicles/{id}/transfer', [VehicleController::class, 'transfer'])->name('vehicles.transfer');

        // Vehicle makes & models (catalog admin)
        Route::resource('vehicle-makes', VehicleMakeController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
        Route::resource('vehicle-models-admin', VehicleModelController::class)
            ->parameters(['vehicle-models-admin' => 'id'])
            ->names('vehicle-models')
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);

        // Repair orders / job cards (core, state machine)
        Route::get('parts/lookup', [RepairOrderController::class, 'partsLookup'])->name('parts.lookup'); // JSON (ERP products)
        Route::get('procurement/to-order', [\Modules\Vrc\Http\Controllers\ProcurementController::class, 'toOrder'])->name('procurement.to-order');
        Route::get('procurement/low-stock', [\Modules\Vrc\Http\Controllers\ProcurementController::class, 'lowStock'])->name('procurement.low-stock');
        Route::get('repair-orders', [RepairOrderController::class, 'index'])->name('repair-orders.index');
        Route::get('repair-orders/create', [RepairOrderController::class, 'create'])->name('repair-orders.create');
        Route::post('repair-orders', [RepairOrderController::class, 'store'])->name('repair-orders.store');
        Route::get('repair-orders/{id}', [RepairOrderController::class, 'show'])->name('repair-orders.show');
        Route::get('repair-orders/{id}/timeline', [RepairOrderController::class, 'timeline'])->name('repair-orders.timeline'); // JSON
        Route::get('vehicles/{vehicle}/repair-orders', [RepairOrderController::class, 'priorOrders'])->name('repair-orders.prior'); // JSON
        Route::post('repair-orders/{id}/escalate-rework', [RepairOrderController::class, 'escalateRework'])->name('repair-orders.escalate-rework');
        Route::get('repair-orders/{id}/job-card', [RepairOrderController::class, 'jobCardPdf'])->name('repair-orders.job-card'); // PDF
        Route::post('repair-orders/{id}/transition', [RepairOrderController::class, 'transition'])->name('repair-orders.transition');
        Route::post('repair-orders/{id}/invoice', [RepairOrderController::class, 'invoice'])->name('repair-orders.invoice');
        Route::post('repair-orders/{id}/services', [RepairOrderController::class, 'storeService'])->name('repair-orders.services.store');
        Route::delete('repair-orders/{id}/services/{line}', [RepairOrderController::class, 'destroyService'])->name('repair-orders.services.destroy');
        Route::post('repair-orders/{id}/services/{line}/status', [RepairOrderController::class, 'serviceStatus'])->name('repair-orders.services.status');
        Route::post('repair-orders/{id}/apply-package', [RepairOrderController::class, 'applyPackage'])->name('repair-orders.apply-package');
        Route::post('repair-orders/{id}/parts', [RepairOrderController::class, 'storePart'])->name('repair-orders.parts.store');
        Route::delete('repair-orders/{id}/parts/{line}', [RepairOrderController::class, 'destroyPart'])->name('repair-orders.parts.destroy');
        Route::post('repair-orders/{id}/ai-assist', [RepairOrderController::class, 'aiAssist'])->name('repair-orders.ai-assist'); // JSON
        Route::get('repair-orders/{id}/suggested-parts', [RepairOrderController::class, 'suggestedParts'])->name('repair-orders.suggested-parts'); // JSON
        Route::post('repair-orders/{id}/assign', [RepairOrderController::class, 'assign'])->name('repair-orders.assign');
        Route::post('repair-orders/{id}/labor/start', [RepairOrderController::class, 'laborStart'])->name('repair-orders.labor.start');
        Route::post('repair-orders/{id}/labor/stop', [RepairOrderController::class, 'laborStop'])->name('repair-orders.labor.stop');

        // Insurance & warranty
        Route::resource('insurance-companies', \Modules\Vrc\Http\Controllers\InsuranceCompanyController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
        Route::get('repair-orders/{id}/insurance-claim', [\Modules\Vrc\Http\Controllers\InsuranceClaimController::class, 'form'])->name('insurance-claims.form');
        Route::post('repair-orders/{id}/insurance-claims', [\Modules\Vrc\Http\Controllers\InsuranceClaimController::class, 'store'])->name('insurance-claims.store');
        Route::put('insurance-claims/{id}', [\Modules\Vrc\Http\Controllers\InsuranceClaimController::class, 'update'])->name('insurance-claims.update');

        // Estimates / quotations & approval
        Route::get('estimates', [EstimateController::class, 'index'])->name('estimates.index');
        Route::post('repair-orders/{id}/estimate', [EstimateController::class, 'createFromRo'])->name('estimates.from-ro');
        Route::get('estimates/{id}', [EstimateController::class, 'show'])->name('estimates.show');
        Route::get('estimates/{id}/pdf', [EstimateController::class, 'pdf'])->name('estimates.pdf');
        Route::post('estimates/{id}/items', [EstimateController::class, 'addItem'])->name('estimates.items.store');
        Route::delete('estimates/{id}/items/{item}', [EstimateController::class, 'removeItem'])->name('estimates.items.destroy');
        Route::post('estimates/{id}/send', [EstimateController::class, 'send'])->name('estimates.send');
        Route::post('estimates/{id}/approve', [EstimateController::class, 'approve'])->name('estimates.approve');
        Route::post('estimates/{id}/decline', [EstimateController::class, 'decline'])->name('estimates.decline');

        // Digital Vehicle Inspection (DVI)
        Route::resource('inspection-templates', InspectionTemplateController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
        Route::post('repair-orders/{id}/inspections', [InspectionController::class, 'store'])->name('inspections.store');
        Route::get('repair-orders/{id}/inspections/create', [InspectionController::class, 'create'])->name('inspections.create');
        Route::get('inspections/{id}/edit', [InspectionController::class, 'edit'])->name('inspections.edit');
        Route::get('inspections/{id}/pdf', [InspectionController::class, 'reportPdf'])->name('inspections.pdf');
        Route::post('inspections/{id}/results', [InspectionController::class, 'saveResults'])->name('inspections.results');
        Route::post('inspections/{id}/photos', [InspectionController::class, 'photos'])->name('inspections.photos');
        Route::post('inspections/{id}/sign', [InspectionController::class, 'sign'])->name('inspections.sign');
        Route::post('inspections/{id}/push-to-estimate', [InspectionController::class, 'pushToEstimate'])->name('inspections.push');

        // Service catalog (labor operations), categories & packages
        Route::resource('service-categories', ServiceCategoryController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
        Route::resource('services', ServiceController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
        Route::post('service-packages/{id}/apply', [ServicePackageController::class, 'apply'])->name('service-packages.apply');
        Route::resource('service-packages', ServicePackageController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);

        // Reports & reminders
        Route::get('reports', [\Modules\Vrc\Http\Controllers\ReportController::class, 'index'])->name('reports.index');
        Route::get('reports/revenue', [\Modules\Vrc\Http\Controllers\ReportController::class, 'revenue'])->name('reports.revenue');
        Route::get('reports/estimate-conversion', [\Modules\Vrc\Http\Controllers\ReportController::class, 'estimateConversion'])->name('reports.estimate-conversion');
        Route::get('reports/turnaround', [\Modules\Vrc\Http\Controllers\ReportController::class, 'turnaround'])->name('reports.turnaround');
        Route::get('reports/parts-consumption', [\Modules\Vrc\Http\Controllers\ReportController::class, 'partsConsumption'])->name('reports.parts-consumption');
        Route::get('reports/profit', [\Modules\Vrc\Http\Controllers\ReportController::class, 'profit'])->name('reports.profit');
        Route::get('reports/revenue-by-service', [\Modules\Vrc\Http\Controllers\ReportController::class, 'revenueByService'])->name('reports.revenue-by-service');
        Route::get('reports/receivables', [\Modules\Vrc\Http\Controllers\ReportController::class, 'receivables'])->name('reports.receivables');
        Route::get('reports/rework', [\Modules\Vrc\Http\Controllers\ReportController::class, 'rework'])->name('reports.rework');

        // Loyalty / prepaid service plans
        Route::post('service-plans/enroll', [\Modules\Vrc\Http\Controllers\ServicePlanController::class, 'enroll'])->name('service-plans.enroll');
        Route::post('repair-orders/{id}/redeem-plan', [\Modules\Vrc\Http\Controllers\ServicePlanController::class, 'redeem'])->name('service-plans.redeem');
        Route::resource('service-plans', \Modules\Vrc\Http\Controllers\ServicePlanController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);
        Route::get('service-reminders', [\Modules\Vrc\Http\Controllers\ReminderController::class, 'index'])->name('service-reminders.index');
        Route::post('service-reminders', [\Modules\Vrc\Http\Controllers\ReminderController::class, 'store'])->name('service-reminders.store');
        Route::delete('service-reminders/{id}', [\Modules\Vrc\Http\Controllers\ReminderController::class, 'destroy'])->name('service-reminders.destroy');

        // Technicians & productivity
        Route::get('reports/technician-productivity', [TechnicianController::class, 'productivity'])->name('reports.technician-productivity');
        Route::get('technicians/{id}/jobs', [TechnicianController::class, 'jobs'])->name('technicians.jobs');
        Route::resource('technicians', TechnicianController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);

        // Workshop bays
        Route::get('bays/utilization', [BayController::class, 'utilization'])->name('bays.utilization');
        Route::resource('bays', BayController::class)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);

        // Appointments & service calendar
        Route::get('appointments', [AppointmentController::class, 'index'])->name('appointments.index');
        Route::get('appointments/events', [AppointmentController::class, 'events'])->name('appointments.events');
        Route::post('appointments', [AppointmentController::class, 'store'])->name('appointments.store');
        Route::get('appointments/{id}/edit', [AppointmentController::class, 'edit'])->name('appointments.edit');
        Route::put('appointments/{id}', [AppointmentController::class, 'update'])->name('appointments.update');
        Route::post('appointments/{id}/check-in', [AppointmentController::class, 'checkIn'])->name('appointments.check-in');
        Route::post('appointments/{id}/{action}', [AppointmentController::class, 'transition'])
            ->whereIn('action', ['confirm', 'reschedule', 'cancel', 'no-show'])->name('appointments.transition');

        // Repair-specific settings (vrc.* keys in vrc_settings)
        Route::get('settings', [SettingController::class, 'edit'])->name('settings.edit');
        Route::put('settings', [SettingController::class, 'update'])->name('settings.update');

        /*
        |----------------------------------------------------------------------
        | Phase 1-5 expansion (workshop routing, support, ISO compliance, RMI,
        | forecasting, step-up 2FA). Register-style screens use the schema-driven
        | Registers\* controllers; the rest are bespoke.
        |----------------------------------------------------------------------
        */
        $reg = fn ($uri, $ctrl) => Route::resource($uri, $ctrl)
            ->names(str_replace('/', '.', $uri)) // nested uris → dotted names (vrc.quality.documents.*)
            ->only(['index', 'create', 'store', 'edit', 'update', 'destroy']);

        // Phase 2 — workshop routing
        $reg('work-centers', \Modules\Vrc\Http\Controllers\Registers\WorkCenterController::class);
        Route::get('workflow/board', [\Modules\Vrc\Http\Controllers\WorkflowBoardController::class, 'board'])->name('workflow.board');
        Route::get('workflow/board-data', [\Modules\Vrc\Http\Controllers\WorkflowBoardController::class, 'data'])->name('workflow.board-data');
        Route::post('workflow/route-line/{line}', [\Modules\Vrc\Http\Controllers\WorkflowBoardController::class, 'routeLine'])->name('workflow.route-line');

        // Phase 2 — technician competence + storage
        $reg('technician-certifications', \Modules\Vrc\Http\Controllers\Registers\TechnicianCertificationController::class);
        $reg('storage-bins', \Modules\Vrc\Http\Controllers\Registers\StorageBinController::class);

        // Phase 3 — support / complaints / CSAT
        Route::resource('tickets', \Modules\Vrc\Http\Controllers\TicketController::class)
            ->only(['index', 'create', 'store', 'show', 'edit', 'update', 'destroy']);
        Route::post('tickets/{id}/messages', [\Modules\Vrc\Http\Controllers\TicketController::class, 'postMessage'])->name('tickets.messages.store');
        Route::post('tickets/{id}/status', [\Modules\Vrc\Http\Controllers\TicketController::class, 'changeStatus'])->name('tickets.status');
        Route::post('tickets/{id}/escalate', [\Modules\Vrc\Http\Controllers\TicketController::class, 'escalate'])->name('tickets.escalate');
        Route::get('satisfaction', [\Modules\Vrc\Http\Controllers\SatisfactionController::class, 'index'])->name('satisfaction.index');

        // Phase 3 — customer portal accounts (admin)
        Route::get('portal-accounts', [\Modules\Vrc\Http\Controllers\PortalAccountController::class, 'index'])->name('portal-accounts.index');
        Route::post('portal-accounts', [\Modules\Vrc\Http\Controllers\PortalAccountController::class, 'store'])->name('portal-accounts.store');
        Route::post('portal-accounts/{id}/toggle', [\Modules\Vrc\Http\Controllers\PortalAccountController::class, 'toggle'])->name('portal-accounts.toggle');

        // Phase 4 — ISO 9001 quality
        $reg('quality/documents', \Modules\Vrc\Http\Controllers\Registers\DocumentController::class);
        $reg('quality/ncrs', \Modules\Vrc\Http\Controllers\Registers\NcrController::class);
        $reg('quality/capas', \Modules\Vrc\Http\Controllers\Registers\CapaController::class);

        // Phase 4 — ISO 14001 environmental
        $reg('env/waste-streams', \Modules\Vrc\Http\Controllers\Registers\WasteStreamController::class);
        $reg('env/waste-disposals', \Modules\Vrc\Http\Controllers\Registers\WasteDisposalController::class);
        $reg('env/aspects', \Modules\Vrc\Http\Controllers\Registers\EnvironmentalAspectController::class);

        // Phase 4 — ISO 45001 safety
        $reg('safety/hazards', \Modules\Vrc\Http\Controllers\Registers\HazardController::class);
        $reg('safety/incidents', \Modules\Vrc\Http\Controllers\Registers\IncidentController::class);
        $reg('safety/trainings', \Modules\Vrc\Http\Controllers\Registers\SafetyTrainingController::class);

        // Phase 5 — ISO 18541 RMI + forecasting
        Route::get('rmi', [\Modules\Vrc\Http\Controllers\RmiController::class, 'index'])->name('rmi.index');
        Route::post('rmi/decode-vin', [\Modules\Vrc\Http\Controllers\RmiController::class, 'decodeVin'])->name('rmi.decode');
        Route::post('rmi/lookup', [\Modules\Vrc\Http\Controllers\RmiController::class, 'lookup'])->name('rmi.lookup');
        Route::get('reports/forecast', [\Modules\Vrc\Http\Controllers\ForecastController::class, 'index'])->name('reports.forecast');

        // Phase 1 — VRC step-up two-factor auth (self-service)
        Route::get('security/2fa', [\Modules\Vrc\Http\Controllers\TwoFactorController::class, 'show'])->name('security.2fa');
        Route::post('security/2fa/enable', [\Modules\Vrc\Http\Controllers\TwoFactorController::class, 'enable'])->name('security.2fa.enable');
        Route::post('security/2fa/disable', [\Modules\Vrc\Http\Controllers\TwoFactorController::class, 'disable'])->name('security.2fa.disable');
        Route::get('security/2fa/challenge', [\Modules\Vrc\Http\Controllers\TwoFactorController::class, 'challenge'])->name('security.2fa.challenge');
        Route::post('security/2fa/verify', [\Modules\Vrc\Http\Controllers\TwoFactorController::class, 'verify'])->name('security.2fa.verify');
    });

/*
|--------------------------------------------------------------------------
| Public customer portal — tokenized estimate approval (no login, §6.6)
|--------------------------------------------------------------------------
| Rate-limited; the token is the only credential. Lives outside the auth
| group on purpose so a customer can approve from an emailed link.
*/
Route::middleware(['web', 'throttle:30,1'])
    ->prefix('vrc/portal')
    ->name('vrc.portal.')
    ->group(function () {
        Route::get('estimates/{token}', [PortalEstimateController::class, 'show'])->name('estimate');
        Route::post('estimates/{token}/approve', [PortalEstimateController::class, 'approve'])->name('estimate.approve');
        Route::post('estimates/{token}/decline', [PortalEstimateController::class, 'decline'])->name('estimate.decline');

        Route::get('track/{token}', [PortalTrackController::class, 'show'])->name('track');

        Route::get('book', [\Modules\Vrc\Http\Controllers\PortalBookingController::class, 'show'])->name('book');
        Route::post('book', [\Modules\Vrc\Http\Controllers\PortalBookingController::class, 'store'])->name('book.store');

        // Phase 3 — post-delivery satisfaction survey (tokenised, no login)
        Route::get('survey/{token}', [\Modules\Vrc\Http\Controllers\SatisfactionController::class, 'show'])->name('survey');
        Route::post('survey/{token}', [\Modules\Vrc\Http\Controllers\SatisfactionController::class, 'submit'])->name('survey.submit');

        // Phase 3 — authenticated vehicle-owner portal (phone-OTP). The owner
        // session is managed by the controller (not the ERP auth guard).
        Route::get('account', [\Modules\Vrc\Http\Controllers\OwnerPortalController::class, 'loginForm'])->name('account.login');
        Route::post('account/request-otp', [\Modules\Vrc\Http\Controllers\OwnerPortalController::class, 'requestOtp'])->name('account.request-otp');
        Route::post('account/verify-otp', [\Modules\Vrc\Http\Controllers\OwnerPortalController::class, 'verifyOtp'])->name('account.verify-otp');
        Route::get('account/dashboard', [\Modules\Vrc\Http\Controllers\OwnerPortalController::class, 'dashboard'])->name('account.dashboard');
        Route::get('account/vehicle/{id}', [\Modules\Vrc\Http\Controllers\OwnerPortalController::class, 'vehicle'])->name('account.vehicle');
        Route::get('account/logout', [\Modules\Vrc\Http\Controllers\OwnerPortalController::class, 'logout'])->name('account.logout');
    });
