<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Portal\AuthController;
use App\Http\Controllers\Portal\DashboardController;
use App\Http\Controllers\Portal\ConsignmentController;
use App\Http\Controllers\TrackingController;
use App\Http\Controllers\DocumentController;

// ─── Guest tracking ───────────────────────────────────────────────
Route::get('/', [TrackingController::class, 'index'])->name('track.index');
Route::post('/track', [TrackingController::class, 'search'])->name('track.search');

// ─── Auth (guest only) ────────────────────────────────────────────
Route::middleware('guest')->group(function () {
    Route::get('/login',     [AuthController::class, 'showLogin'])->name('login');
    Route::post('/login',    [AuthController::class, 'login']);
    Route::get('/register',  [AuthController::class, 'showRegister'])->name('register');
    Route::post('/register', [AuthController::class, 'register']);
});

Route::post('/logout', [AuthController::class, 'logout'])
    ->name('logout')
    ->middleware('auth');

// ─── Client portal ────────────────────────────────────────────────
Route::middleware(['auth', 'client'])
    ->prefix('portal')
    ->name('portal.')
    ->group(function () {
        Route::get('/dashboard', [DashboardController::class, 'index'])
            ->name('dashboard');

        Route::get('/consignment/{tracking_code}',
            [ConsignmentController::class, 'show'])
            ->name('consignment.show');
        Route::get('/consignment/{tracking_code}/delivery-note', function ($tracking_code) {

            $consignment = \App\Models\Consignment::where('tracking_code', $tracking_code)->firstOrFail();

            return redirect()->route('documents.print', [
                'type' => 'delivery-note',
                'consignmentId' => $consignment->id,
            ]);

        })->name('consignment.delivery-note');
    });

// ─── Document print (staff only) ─────────────────────────────────
// Uses integer ID — avoids model binding memory overhead
Route::middleware('auth')
    ->get('/documents/{type}/{consignmentId}/print',
        [DocumentController::class, 'print'])
    ->name('documents.print')
    ->where('consignmentId', '[0-9]+');