<?php

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Route;
use App\Http\Middleware\VerifyCsrfToken;

/*
|--------------------------------------------------------------------------
| Controllers
|--------------------------------------------------------------------------
*/
use App\Http\Controllers\Admin\DepositCaptureController;
use App\Http\Controllers\Admin\VevsImportController;
// FIXED namespace here ↓
use App\Http\Controllers\Jobs\ImportReservationController;
use App\Http\Controllers\CustomerPortalController;
use App\Http\Controllers\DepositController;
use App\Http\Controllers\JobReservationImportController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\Portal\PayController;
use App\Http\Controllers\PortalAuthController;
use App\Http\Controllers\PortalController;
use App\Http\Controllers\Payments\PublicPayController;
use App\Http\Controllers\StripeWebhookController;
use App\Http\Controllers\Webhooks\SendgridWebhookController;
use App\Http\Controllers\OpsController;
use App\Http\Controllers\Api\FleetCalendarController;
use App\Http\Controllers\PublicBookingPortalController;

Route::get('/book/jimny', [PublicBookingPortalController::class, 'showJimnyForm'])
    ->name('book.jimny.show');

Route::post('/book/jimny', [PublicBookingPortalController::class, 'storeJimny'])
    ->name('book.jimny.store');

Route::get('/book/dream-drives', [PublicBookingPortalController::class, 'showDreamDrivesForm'])
    ->name('book.dreamdrives.show');

Route::post('/book/dream-drives', [PublicBookingPortalController::class, 'storeDreamDrives'])
    ->name('book.dreamdrives.store');

Route::get('/book/thank-you/{ref}', function (string $ref) {
    return view('public-booking.thank-you', ['reference' => $ref]);
})->name('public.booking.thank-you');



Route::prefix('book')->group(function () {
    // Jimny NZ booking portal
    Route::get('jimny', [PublicBookingPortalController::class, 'showJimnyForm'])
        ->name('book.jimny.show');
    Route::post('jimny', [PublicBookingPortalController::class, 'storeJimny'])
        ->name('book.jimny.store');

    // Dream Drives booking portal
    Route::get('dream-drives', [PublicBookingPortalController::class, 'showDreamDrivesForm'])
        ->name('book.dreamdrives.show');
    Route::post('dream-drives', [PublicBookingPortalController::class, 'storeDreamDrives'])
        ->name('book.dreamdrives.store');

    // Generic thank-you page after successful booking
    Route::get('thank-you', [PublicBookingPortalController::class, 'thankYou'])
        ->name('public.booking.thank-you');
});



Route::post('/ops/jobs/{ref_id}/mark-returned', [OpsController::class, 'markReturned'])
    ->name('ops.mark-returned');

Route::post('/ops/vehicles/{vehicle}/mark-cleaned', [OpsController::class, 'markCleaned'])
    ->name('ops.mark-cleaned');
    
    Route::get('/fleet-calendar/resources', [FleetCalendarController::class, 'resources'])
    ->name('fleet-calendar.resources');

Route::get('/fleet-calendar/events', [FleetCalendarController::class, 'events'])
    ->name('fleet-calendar.events');



/*
|--------------------------------------------------------------------------
| Global route parameter patterns
|--------------------------------------------------------------------------
*/
Route::pattern('booking',  '[0-9]+');
Route::pattern('deposit',  '[0-9]+');
Route::pattern('customer', '[0-9]+');
Route::pattern('payment',  '[0-9]+');
Route::pattern('job',      '[0-9]+');

/*
|--------------------------------------------------------------------------
| Home
|--------------------------------------------------------------------------
*/
Route::get('/', fn () => view('welcome'))->name('home');

Route::get('p/login-smoke', fn() => 'ok')->name('portal.login.smoke');


/*
|--------------------------------------------------------------------------
| Hosted Payment Page (token-based, public)
|--------------------------------------------------------------------------
| - GET /pay/{token}       : show hosted payment page
| - GET /pay/{token}/done  : landing after Stripe redirect/3DS
| - POST /pay/session      : returns/creates a PaymentIntent and client_secret
|   (CSRF-exempt because it’s called via fetch from a public page)
*/
Route::name('payments.public.')->group(function () {
    Route::get('/pay/{token}', [PublicPayController::class, 'show'])->name('show');
    Route::get('/pay/{token}/done', [PublicPayController::class, 'done'])->name('done');

    Route::post('/pay/session', [PublicPayController::class, 'session'])
        ->name('session')
        ->withoutMiddleware([VerifyCsrfToken::class]);
});

/*
|--------------------------------------------------------------------------
| Portal Hold (Bond) – public token flow
|--------------------------------------------------------------------------
| If the form used on /portal/pay/{token}/hold posts without @csrf,
| either add @csrf to the Blade form OR exempt the POST below.
| Here we exempt it for safety in public-token contexts.
*/
Route::get('/portal/pay/{token}/hold', function (string $token) {
    $booking = \App\Models\Booking::where('portal_token', $token)->firstOrFail();
    return view('portal.hold', compact('booking'));
})->name('portal.pay.hold.page');

Route::post('/portal/pay/{token}/hold/intent', [PaymentController::class, 'portalCreateHoldIntentByToken'])
    ->name('portal.pay.hold.intent')
    ->withoutMiddleware([VerifyCsrfToken::class]);

Route::get('/portal/pay/{token}/hold/complete', [PaymentController::class, 'portalCompleteHoldByToken'])
    ->name('portal.pay.hold.complete');

/*
|--------------------------------------------------------------------------
| Webhooks (CSRF-exempt)
|--------------------------------------------------------------------------
*/
Route::post('/stripe/webhook', [StripeWebhookController::class, 'handle'])
    ->name('stripe.webhook')
    ->withoutMiddleware([VerifyCsrfToken::class]);

Route::post('/webhooks/sendgrid', [SendgridWebhookController::class, 'handle'])
    ->name('webhooks.sendgrid')
    ->withoutMiddleware([VerifyCsrfToken::class]);

/*
|--------------------------------------------------------------------------
| VEVS Admin Import Endpoint (secured)
|--------------------------------------------------------------------------
*/
Route::post('/admin/vevs/import', [VevsImportController::class, 'fetch'])
    ->middleware(['auth', 'verified', 'throttle:30,1'])
    ->name('admin.vevs.import');

/*
|--------------------------------------------------------------------------
| Debug / SMTP smoke tests (rate-limited)
|--------------------------------------------------------------------------
*/
Route::get('/mail-test', function () {
    try {
        Mail::raw('Hello from Holds app!', function ($m) {
            $m->to('your-test@email.com')->subject('SMTP test');
        });
        return '✅ Mail sent';
    } catch (\Throwable $e) {
        return '❌ Mail failed: ' . $e->getMessage();
    }
})->middleware('throttle:3,1')->name('debug.mail_test');

Route::get('/test-mail', function () {
    try {
        Mail::raw('Test from Holds app route', function ($msg) {
            $msg->to('apcrouchley@gmail.com')->subject('Holds Route Test');
        });
        return 'Mail dispatched — check inbox (or logs if using mailer=log).';
    } catch (\Throwable $e) {
        Log::error('Mail test failed: ' . $e->getMessage());
        return 'Mail failed: ' . $e->getMessage();
    }
})->middleware('throttle:3,1')->name('debug.mail_test_alt');

/*
|--------------------------------------------------------------------------
| VEVS landing
|--------------------------------------------------------------------------
*/
Route::get('/vevs/landing', [PortalController::class, 'vevsLanding'])->name('vevs.landing');

/*
|--------------------------------------------------------------------------
| Background / Jobs (auth)
|--------------------------------------------------------------------------
*/
Route::post('/jobs/import-reservation', ImportReservationController::class)
    ->middleware(['auth'])
    ->name('jobs.import-reservation');

Route::post('/jobs/import-reservation-legacy', JobReservationImportController::class)
    ->middleware(['auth'])
    ->name('jobs.importReservation');

/*
|--------------------------------------------------------------------------
| Portal login (magic link) – /p/login/*
|--------------------------------------------------------------------------
*/
Route::prefix('p')->middleware('guest:portal')->group(function () {
    Route::get('/login',          [PortalController::class, 'showLogin'])->name('portal.login');
    Route::post('/login',         [PortalController::class, 'sendLoginLink'])->name('portal.login.send');
    Route::get('/login-classic',  [PortalAuthController::class, 'show'])->name('portal.login.classic');
    Route::post('/login-classic', [PortalAuthController::class, 'attempt'])->name('portal.login.classic.attempt');
    Route::get('/login/magic',    [PortalAuthController::class, 'magic'])->name('portal.magic'); // placeholder
});

Route::middleware('auth:portal')->group(function () {
    Route::get('/p',         [CustomerPortalController::class, 'dashboard'])->name('portal.home');
    Route::post('/p/logout', [PortalAuthController::class, 'logout'])->name('portal.logout');
});

Route::get('/p/login', fn () => redirect()->route('portal.login.classic'))
    ->middleware('guest:portal')
    ->name('portal.login');

Route::get('/login', fn () => redirect()->route('portal.login'))->name('login');
Route::get('/customer/login', fn () => redirect()->route('portal.login'))->name('customer.login');



/*
|--------------------------------------------------------------------------
| Route aliases to login
|--------------------------------------------------------------------------
*/
Route::get('/login',          fn () => redirect()->route('portal.login'))->name('login');

/*
|--------------------------------------------------------------------------
| Canonical Job-based customer payment flow (/p/job/{job})
|--------------------------------------------------------------------------
*/
Route::prefix('p/job/{job}')->name('portal.pay.')->group(function () {
    Route::get('pay',          [PayController::class, 'showJob'])->name('show.job')->middleware('signed');
    Route::post('intent',      [PayController::class, 'intent'])->name('intent')->withoutMiddleware([VerifyCsrfToken::class]);
    Route::post('bundle',      [PayController::class, 'bundle'])->name('bundle.job')->withoutMiddleware([VerifyCsrfToken::class]);
    Route::post('record-paid', [PayController::class, 'recordPaid'])->name('recordPaid')->withoutMiddleware([VerifyCsrfToken::class]);
    Route::get('complete',     [PayController::class, 'complete'])->name('job.complete');
});

/*
|--------------------------------------------------------------------------
| Booking-aware portal pay (legacy)
|--------------------------------------------------------------------------
*/
Route::get('/p/home', [PortalController::class, 'home'])->name('portal.legacy.home');
Route::get('/p/dashboard', fn () => redirect()->route('portal.home'))->name('portal.dashboard');

Route::get('/p/pay/{booking}', [PortalController::class, 'pay'])->name('portal.pay');

Route::post('/p/pay/{booking}/intent', [PaymentController::class, 'portalCreateIntent'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('portal.pay.intent.booking');

Route::post('/p/pay/{booking}/setup', [PaymentController::class, 'createSetupIntent'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('portal.pay.setup');

Route::post('/p/pay/{booking}/finalize', [PaymentController::class, 'finalizeCheckout'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('portal.pay.finalize');

Route::get('/p/pay/{booking}/complete', [PaymentController::class, 'portalComplete'])
    ->name('portal.pay.complete.booking');

/*
|--------------------------------------------------------------------------
| Tokenized hosted payment pages (legacy token flow under /p/)
|--------------------------------------------------------------------------
*/
Route::get('/p/pay/{token}',          [PaymentController::class, 'showPortalPay'])->name('portal.pay.token');
Route::post('/p/pay/{token}/intent',  [PaymentController::class, 'createOrReuseBalanceIntent'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('portal.pay.intent.token');
Route::post('/p/pay/{token}/confirm', [PaymentController::class, 'markPaid'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('portal.pay.confirm');

/*
|--------------------------------------------------------------------------
| Generic token landing under /p/{token} (MUST REMAIN LAST)
|--------------------------------------------------------------------------
*/
Route::get('/p/{token}', [PortalController::class, 'show'])->name('portal.show');

/*
|--------------------------------------------------------------------------
| Admin / Staff – Holds
|--------------------------------------------------------------------------
*/
Route::middleware(['web', 'auth'])->group(function () {
    Route::post('/admin/jobs/{job}/hold', [DepositCaptureController::class, 'createHold'])->name('admin.jobs.hold.create');
    Route::post('/admin/deposits/{deposit}/capture', [DepositCaptureController::class, 'capture'])->name('admin.deposits.capture');
    Route::post('/admin/deposits/{deposit}/cancel', [DepositCaptureController::class, 'cancel'])->name('admin.deposits.cancel');
    Route::post('/admin/bookings/{booking}/post-charge', [PaymentController::class, 'postHireCharge'])->name('admin.bookings.post_charge');

    Route::post('/admin/hold/{payment}/capture', [PaymentController::class, 'captureHold'])->name('admin.hold.capture');
    Route::post('/admin/hold/{payment}/release', [PaymentController::class, 'releaseHold'])->name('admin.hold.release');

    Route::get('/admin/holds', [PaymentController::class, 'holdsIndex'])->name('admin.holds.index');
});

/*
|--------------------------------------------------------------------------
| Legacy Booking payments
|--------------------------------------------------------------------------
*/
Route::post('/bookings/{booking}/deposit', [PaymentController::class, 'deposit'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('booking.deposit');

Route::post('/bookings/{booking}/balance', [PaymentController::class, 'balance'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('booking.balance');

/*
|--------------------------------------------------------------------------
| Legacy Card deposit "hold" & capture/void
|--------------------------------------------------------------------------
*/
Route::post('/bookings/{booking}/hold', [DepositController::class, 'authorise'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('booking.hold');

Route::post('/deposits/{deposit}/capture', [DepositController::class, 'capture'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('deposit.capture');

Route::post('/deposits/{deposit}/void', [DepositController::class, 'void'])
    ->withoutMiddleware([VerifyCsrfToken::class])
    ->name('deposit.void');

/*
|--------------------------------------------------------------------------
| Staff account area
|--------------------------------------------------------------------------
*/
Route::get('/customer/dashboard', fn () => view('customer.dashboard'))
    ->middleware(['auth'])
    ->name('customer.dashboard');

