<?php

use App\Http\Controllers\Admin\AccountController;
use App\Http\Controllers\Admin\BookingController;
use App\Http\Controllers\Admin\CallController;
use App\Http\Controllers\Admin\ChangelogController;
use App\Http\Controllers\Admin\CompanyController;
use App\Http\Controllers\Admin\CompanySettingsController;
use App\Http\Controllers\Admin\CustomerController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\DemoRequestController;
use App\Http\Controllers\Admin\DriverController;
use App\Http\Controllers\Admin\DriverDocumentController;
use App\Http\Controllers\Admin\DriverShiftController;
use App\Http\Controllers\Admin\HelpController;
use App\Http\Controllers\Admin\PayoutController;
use App\Http\Controllers\Admin\PlatformController;
use App\Http\Controllers\Admin\FareRuleController;
use App\Http\Controllers\Admin\MarketingScreenshotController;
use App\Http\Controllers\Admin\NotificationController;
use App\Http\Controllers\Admin\ReportController;
use App\Http\Controllers\Admin\RoleController;
use App\Http\Controllers\Admin\SupportTicketController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\VehicleController;
use App\Http\Controllers\Admin\VehicleDocumentController;
use App\Http\Controllers\Admin\VehicleTypeController;
use App\Http\Controllers\DemoRequestController as PublicDemoRequestController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\WebhookController;
use Illuminate\Support\Facades\Route;

Route::get('/', [HomeController::class, 'index'])->name('home');
Route::get('/request-a-demo', [PublicDemoRequestController::class, 'create'])->name('demo-requests.create');
Route::post('/request-a-demo', [PublicDemoRequestController::class, 'store'])->name('demo-requests.store');

// Twilio webhooks — public, but every handler independently verifies the
// X-Twilio-Signature header against the target company's auth token.
Route::prefix('twilio')->name('twilio.')->group(function () {
    Route::post('voice/{company}', [CallController::class, 'voice'])->name('voice');
    Route::post('status/{company}', [CallController::class, 'statusCallback'])->name('status');
});

// Stripe webhook — public, independently verified per-request against the
// target company's own webhook secret (App\Services\StripePaymentService).
Route::post('webhooks/stripe/{company}', [WebhookController::class, 'stripe'])->name('webhooks.stripe');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
    Route::put('/profile/notification-preferences', [ProfileController::class, 'updateNotificationPreferences'])->name('profile.notification-preferences.update');
});

Route::middleware(['auth', 'verified'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/dashboard', DashboardController::class)->name('dashboard');
    Route::post('changelog/dismiss', [ChangelogController::class, 'dismiss'])->name('changelog.dismiss');

    // Platform-level concerns: only a Super Admin (company_id = null) may
    // create companies or define roles/permissions. Company Admins only
    // assign existing roles to their own company's staff (Users CRUD below).
    Route::middleware('super_admin')->group(function () {
        Route::get('platform', [PlatformController::class, 'index'])->name('platform.index');

        Route::resource('companies', CompanyController::class)->except('show');
        Route::resource('roles', RoleController::class)->except('show');

        Route::get('marketing-screenshots', [MarketingScreenshotController::class, 'index'])->name('marketing-screenshots.index');
        Route::post('marketing-screenshots', [MarketingScreenshotController::class, 'store'])->name('marketing-screenshots.store');
        Route::patch('marketing-screenshots/{screenshot}/move-up', [MarketingScreenshotController::class, 'moveUp'])->name('marketing-screenshots.move-up');
        Route::patch('marketing-screenshots/{screenshot}/move-down', [MarketingScreenshotController::class, 'moveDown'])->name('marketing-screenshots.move-down');
        Route::delete('marketing-screenshots/{screenshot}', [MarketingScreenshotController::class, 'destroy'])->name('marketing-screenshots.destroy');

        Route::get('demo-requests', [DemoRequestController::class, 'index'])->name('demo-requests.index');
        Route::patch('demo-requests/{demoRequest}', [DemoRequestController::class, 'updateStatus'])->name('demo-requests.update-status');
        Route::delete('demo-requests/{demoRequest}', [DemoRequestController::class, 'destroy'])->name('demo-requests.destroy');
        Route::get('demo-requests/{demoRequest}/convert', [DemoRequestController::class, 'convertForm'])->name('demo-requests.convert-form');
        Route::post('demo-requests/{demoRequest}/convert', [DemoRequestController::class, 'convert'])->name('demo-requests.convert');

        Route::get('support-tickets', [SupportTicketController::class, 'index'])->name('support-tickets.index');
        Route::patch('support-tickets/{supportTicket}', [SupportTicketController::class, 'updateStatus'])->name('support-tickets.update-status');
    });

    // RBAC-01: index/create/edit stay open to any authenticated staff member
    // (viewing a form isn't itself a mutation); the actual write actions
    // require the module's "manage" permission. Splitting one resource()
    // call into two — one per middleware group — is a supported Laravel
    // pattern and doesn't create duplicate/colliding route names as long as
    // the action lists don't overlap.
    Route::resource('users', UserController::class)->only(['index', 'create', 'edit']);
    Route::resource('users', UserController::class)->only(['store', 'update', 'destroy'])->middleware('permission:users.manage');

    // Individual driver/customer/booking records — including customer PII —
    // are per-company data a Super Admin must never see or touch. Their view
    // into this is the aggregate counts on Platform Overview, not records.
    Route::middleware('company_scoped')->group(function () {
        Route::resource('drivers', DriverController::class)->only(['index', 'create', 'edit']);
        Route::resource('drivers', DriverController::class)->only(['store', 'update', 'destroy'])->middleware('permission:drivers.manage');
        Route::post('drivers/{driver}/documents', [DriverDocumentController::class, 'store'])->name('drivers.documents.store')->middleware('permission:drivers.manage');
        Route::patch('drivers/{driver}/documents/{document}', [DriverDocumentController::class, 'updateStatus'])->name('drivers.documents.update-status')->middleware('permission:drivers.manage');
        Route::get('drivers/{driver}/documents/{document}/download', [DriverDocumentController::class, 'download'])->name('drivers.documents.download');
        Route::delete('drivers/{driver}/documents/{document}', [DriverDocumentController::class, 'destroy'])->name('drivers.documents.destroy')->middleware('permission:drivers.manage');

        Route::resource('customers', CustomerController::class)->only(['index', 'create', 'edit']);
        Route::resource('customers', CustomerController::class)->only(['store', 'update', 'destroy'])->middleware('permission:customers.manage');

        Route::post('bookings/quote', [BookingController::class, 'quote'])->name('bookings.quote');
        Route::post('bookings/quote-all', [BookingController::class, 'quoteAll'])->name('bookings.quote-all');
        Route::get('bookings/driver-locations', [BookingController::class, 'driverLocations'])->name('bookings.driver-locations');
        Route::post('bookings/check-driver', [BookingController::class, 'checkDriver'])->name('bookings.check-driver');
        Route::get('bookings/live', [BookingController::class, 'live'])->name('bookings.live');
        Route::get('bookings/{booking}/receipt', [BookingController::class, 'receipt'])->name('bookings.receipt');
        Route::get('bookings/{booking}/history', [BookingController::class, 'history'])->name('bookings.history');
        Route::get('bookings/{booking}/rebook', [BookingController::class, 'rebookData'])->name('bookings.rebook');
        Route::get('bookings/{booking}/edit-data', [BookingController::class, 'editFormData'])->name('bookings.edit-data');
        Route::put('bookings/{booking}/full', [BookingController::class, 'updateFull'])->name('bookings.update-full')->middleware('permission:bookings.manage');
        Route::post('bookings/bulk-action', [BookingController::class, 'bulkAction'])->name('bookings.bulk-action')->middleware('permission:bookings.manage');
        Route::resource('bookings', BookingController::class)->only(['index', 'create', 'edit']);
        Route::resource('bookings', BookingController::class)->only(['store', 'update', 'destroy'])->middleware('permission:bookings.manage');

        // A vehicle belongs to a company's fleet just like a driver — same
        // cross-tenant leak (Super Admin's company_id=null no-ops the
        // ->when() scope in VehicleController@index), same fix.
        Route::resource('vehicles', VehicleController::class)->only(['index', 'create', 'edit']);
        Route::resource('vehicles', VehicleController::class)->only(['store', 'update', 'destroy'])->middleware('permission:vehicles.manage');
        Route::post('vehicles/{vehicle}/documents', [VehicleDocumentController::class, 'store'])->name('vehicles.documents.store')->middleware('permission:vehicles.manage');
        Route::patch('vehicles/{vehicle}/documents/{document}', [VehicleDocumentController::class, 'updateStatus'])->name('vehicles.documents.update-status')->middleware('permission:vehicles.manage');
        Route::get('vehicles/{vehicle}/documents/{document}/download', [VehicleDocumentController::class, 'download'])->name('vehicles.documents.download');
        Route::delete('vehicles/{vehicle}/documents/{document}', [VehicleDocumentController::class, 'destroy'])->name('vehicles.documents.destroy')->middleware('permission:vehicles.manage');

        // Each company has its own Twilio account (CallController::voice/
        // statusCallback are already keyed per-company) — call history is
        // just as company-scoped as bookings, and has the exact same
        // ->when($companyId, ...) no-op leak for a Super Admin.
        Route::get('calls', [CallController::class, 'history'])->name('calls.index');

        // Same leak again: DriverShiftController@index scopes through the
        // driver's company via ->when($companyId, ...), which no-ops for a
        // Super Admin the same way every other module here did.
        Route::get('shifts', [DriverShiftController::class, 'index'])->name('shifts.index');
        Route::patch('shifts/{shift}/force-end', [DriverShiftController::class, 'forceEnd'])->name('shifts.force-end')->middleware('permission:shifts.manage');
    });

    Route::resource('vehicle-types', VehicleTypeController::class)->only(['index', 'create', 'edit']);
    Route::resource('vehicle-types', VehicleTypeController::class)->only(['store', 'update', 'destroy'])->middleware('permission:fare-rules.manage');
    Route::post('vehicle-types/{vehicleType}/fare-rules', [FareRuleController::class, 'store'])->name('vehicle-types.fare-rules.store')->middleware('permission:fare-rules.manage');
    Route::put('vehicle-types/{vehicleType}/fare-rules/{fareRule}', [FareRuleController::class, 'update'])->name('vehicle-types.fare-rules.update')->middleware('permission:fare-rules.manage');
    Route::delete('vehicle-types/{vehicleType}/fare-rules/{fareRule}', [FareRuleController::class, 'destroy'])->name('vehicle-types.fare-rules.destroy')->middleware('permission:fare-rules.manage');

    Route::resource('accounts', AccountController::class)->only(['index', 'create', 'edit']);
    Route::resource('accounts', AccountController::class)->only(['store', 'update', 'destroy'])->middleware('permission:accounts.manage');

    Route::get('settings', [CompanySettingsController::class, 'edit'])->name('settings.edit');
    Route::put('settings', [CompanySettingsController::class, 'update'])->name('settings.update')->middleware('permission:settings.manage');

    Route::get('notifications', [NotificationController::class, 'index'])->name('notifications.index');
    Route::post('notifications/{notification}/read', [NotificationController::class, 'markRead'])->name('notifications.read');
    Route::post('notifications/read-all', [NotificationController::class, 'markAllRead'])->name('notifications.read-all');

    Route::get('help', [HelpController::class, 'index'])->name('help.index');
    Route::post('help/ticket', [HelpController::class, 'submitTicket'])->name('help.submit-ticket');


    Route::get('payouts', [PayoutController::class, 'index'])->name('payouts.index');
    Route::post('payouts/generate', [PayoutController::class, 'generate'])->name('payouts.generate')->middleware('permission:payouts.manage');
    Route::patch('payouts/{payout}/mark-paid', [PayoutController::class, 'markPaid'])->name('payouts.mark-paid')->middleware('permission:payouts.manage');

    Route::get('calls/token', [CallController::class, 'token'])->name('calls.token');

    Route::get('reports', [ReportController::class, 'index'])->name('reports.index');
    Route::get('reports/export', [ReportController::class, 'export'])->name('reports.export');
    Route::get('reports/drivers', [ReportController::class, 'drivers'])->name('reports.drivers');
    Route::get('reports/customers', [ReportController::class, 'customers'])->name('reports.customers');
});

require __DIR__.'/auth.php';
