<?php

use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\AlmacenController;
use App\Http\Controllers\AdministracionController;
use App\Http\Controllers\Administracion\Crud\CrudRouterController;
use App\Http\Controllers\AsignacionController;
use App\Http\Controllers\AsignacionOperacionController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\GraficasController;
use App\Http\Controllers\ReporteLegacyController;
use App\Http\Controllers\ReporteInventarioController;
use App\Http\Controllers\ReporteShipChandlerController;
use App\Http\Controllers\ShipMarketController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return redirect()->route('dashboard');
})->middleware('auth');

Route::middleware('guest')->group(function (): void {
    Route::get('/login', [AuthenticatedSessionController::class, 'create'])->name('login');
    Route::post('/login', [AuthenticatedSessionController::class, 'store'])->name('login.store');
});

Route::middleware('auth')->group(function (): void {
    Route::post('/logout', [AuthenticatedSessionController::class, 'destroy'])
        ->name('logout');

    Route::get('/dashboard', [DashboardController::class, 'index'])
        ->name('dashboard');

    Route::prefix('ship-market')
        ->middleware('user.role:administrador,solicitante')
        ->name('ship-market.')
        ->group(function (): void {
            Route::get('/', [ShipMarketController::class, 'index'])->name('index');
            Route::get('/ayuda', [ShipMarketController::class, 'help'])->name('help');
            Route::post('/solicitudes', [ShipMarketController::class, 'generateSolicitud'])->name('solicitudes.store');
            Route::post('/carrito', [ShipMarketController::class, 'addToCart'])->name('cart.add');
            Route::patch('/carrito', [ShipMarketController::class, 'updateCart'])->name('cart.update');
            Route::delete('/carrito/vaciar', [ShipMarketController::class, 'clearCart'])->name('cart.clear');
            Route::delete('/carrito/{code}', [ShipMarketController::class, 'removeFromCart'])->name('cart.remove');
        });

    Route::view('/manual-administrador', 'manual.administrador')
        ->middleware('user.role:administrador,almacenista,gestor')
        ->name('manual.administrador');

    Route::get('/manual-administrador/pdf', function () {
        $filePath = storage_path('app/private/manual/manual-de-usuario.pdf');

        if (! is_file($filePath)) {
            $filePath = public_path('docs/manual-de-usuario.pdf');
        }

        abort_unless(is_file($filePath), 404);

        return response()->file($filePath, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; filename="manual-de-usuario.pdf"',
        ]);
    })->middleware('user.role:administrador,almacenista,gestor')
        ->name('manual.administrador.pdf');

    Route::get('/manual-administrador/pdf/descargar', function () {
        $filePath = storage_path('app/private/manual/manual-de-usuario.pdf');

        if (! is_file($filePath)) {
            $filePath = public_path('docs/manual-de-usuario.pdf');
        }

        abort_unless(is_file($filePath), 404);

        return response()->download(
            $filePath,
            'manual-de-usuario.pdf',
            ['Content-Type' => 'application/pdf']
        );
    })->middleware('user.role:administrador,almacenista,gestor')
        ->name('manual.administrador.pdf.download');

    Route::get('/manual-administrador/markdown', function () {
        $filePath = storage_path('app/private/manual/manual-de-usuario.md');

        abort_unless(is_file($filePath), 404);

        return response()->download(
            $filePath,
            'manual-de-usuario.md',
            ['Content-Type' => 'text/markdown; charset=UTF-8']
        );
    })->middleware('user.role:administrador,almacenista,gestor')
        ->name('manual.administrador.markdown');

    Route::get('/administracion', [AdministracionController::class, 'index'])
        ->middleware('admin.tipo:administrador,almacenista,gestor')
        ->name('administracion.index');

    Route::get('/administracion/barcode-generator', [AdministracionController::class, 'barcodeGenerator'])
        ->middleware('admin.tipo:administrador,gestor')
        ->name('administracion.barcode-generator');

    Route::get('/administracion/barcode-generator/{bien}/barcode', [AdministracionController::class, 'barcodeImage'])
        ->middleware('admin.tipo:administrador,gestor')
        ->name('administracion.barcode-generator.barcode');

    Route::get('/administracion/comprobante/numero/{numero}', [AsignacionOperacionController::class, 'showByOperationNumber'])
        ->middleware('admin.tipo')
        ->name('administracion.comprobante.by-number');

    Route::get('/administracion/comprobante/{id}', [AsignacionOperacionController::class, 'showByOperationId'])
        ->middleware('admin.tipo')
        ->name('administracion.comprobante.show');

    Route::get('/administracion/comprobante/{id}/barcode', [AsignacionOperacionController::class, 'barcodeByOperationId'])
        ->middleware('admin.tipo')
        ->name('administracion.comprobante.barcode');

    Route::prefix('almacen')
        ->middleware('user.role:administrador,almacenista')
        ->name('almacen.')
        ->group(function (): void {
            Route::get('/', [AlmacenController::class, 'index'])->name('index');
            Route::get('/inventario', [AlmacenController::class, 'inventario'])->name('inventario');
            Route::put('/inventario/{id}', [AlmacenController::class, 'updateInventarioItem'])->name('inventario.update');
            Route::delete('/inventario/{id}', [AlmacenController::class, 'destroyInventarioItem'])->name('inventario.destroy');
            Route::post('/actualizar', [AlmacenController::class, 'actualizar'])
                ->middleware('count.operation:action')
                ->name('actualizar');
        });

    Route::prefix('asignacion')
        ->middleware('user.role:administrador,gestor')
        ->name('asignacion.')
        ->group(function (): void {
            Route::get('/iniciar', [AsignacionController::class, 'iniciar'])->name('iniciar');
            Route::get('/', [AsignacionController::class, 'solicitante'])
                ->name('solicitante');
            Route::post('/solicitante', [AsignacionController::class, 'validarSolicitante'])->name('solicitante.validar');
            Route::get('/tipo-operacion', [AsignacionController::class, 'tipoOperacion'])->name('tipo-operacion');
            Route::get('/alimentos', [AsignacionController::class, 'alimentos'])->name('alimentos');
            Route::post('/alimentos/entregar', [AsignacionController::class, 'entregarAlimentos'])
                ->middleware('count.operation:action')
                ->name('alimentos.entregar');
            Route::get('/dotacion', [AsignacionController::class, 'dotacion'])->name('dotacion');
            Route::post('/dotacion/entregar', [AsignacionController::class, 'entregarDotacion'])
                ->middleware('count.operation:action')
                ->name('dotacion.entregar');
            Route::get('/transferencia', [AsignacionController::class, 'transferencia'])->name('transferencia');
            Route::post('/transferencia/entregar', [AsignacionController::class, 'entregarTransferencia'])
                ->middleware('count.operation:action')
                ->name('transferencia.entregar');
            Route::get('/devolucion', [AsignacionController::class, 'devolucion'])->name('devolucion');
            Route::get('/devolucion/prestamos', [AsignacionController::class, 'devolucionPrestamos'])->name('devolucion.prestamos');
            Route::post('/devolucion/prestamos/procesar', [AsignacionController::class, 'procesarDevolucionPrestamos'])
                ->middleware('count.operation:action')
                ->name('devolucion.prestamos.procesar');
            Route::get('/devolucion/transferencias', [AsignacionController::class, 'devolucionTransferencias'])->name('devolucion.transferencias');
            Route::post('/devolucion/transferencias/procesar', [AsignacionController::class, 'procesarDevolucionTransferencias'])
                ->middleware('count.operation:action')
                ->name('devolucion.transferencias.procesar');
            Route::get('/operacion/{tipo}/{numero}', [AsignacionOperacionController::class, 'show'])->name('operacion.show');
            Route::get('/operacion/{tipo}/{numero}/barcode', [AsignacionOperacionController::class, 'barcode'])->name('operacion.barcode');
            Route::get('/operacion/{tipo}/{numero}/export', [AsignacionOperacionController::class, 'export'])->name('operacion.export');
        });

    Route::prefix('administracion/crud')
        ->middleware('admin.tipo:administrador,almacenista,gestor')
        ->name('administracion.crud.')
        ->group(function (): void {
            Route::get('/', [CrudRouterController::class, 'entities'])->name('entities');
            Route::get('/{entity}', [CrudRouterController::class, 'index'])->name('index');
            Route::get('/precios-por-bien/asignacion-masiva', [\App\Http\Controllers\Administracion\Crud\Entidades\PreciosPorBienCrudController::class, 'bulkForm'])
                ->name('precios-por-bien.bulk-form');
            Route::post('/precios-por-bien/asignacion-masiva', [\App\Http\Controllers\Administracion\Crud\Entidades\PreciosPorBienCrudController::class, 'storeBulk'])
                ->middleware('count.operation:action')
                ->name('precios-por-bien.bulk-store');
            Route::get('/{entity}/importar-lote', [CrudRouterController::class, 'importForm'])->name('import.form');
            Route::get('/{entity}/importar-lote/plantilla', [CrudRouterController::class, 'importTemplate'])->name('import.template');
            Route::post('/{entity}/importar-lote', [CrudRouterController::class, 'importStore'])
                ->middleware('count.operation:action')
                ->name('import.store');
            Route::get('/{entity}/create', [CrudRouterController::class, 'create'])->name('create');
            Route::post('/{entity}', [CrudRouterController::class, 'store'])
                ->middleware('count.operation:action')
                ->name('store');
            Route::get('/{entity}/{id}/edit', [CrudRouterController::class, 'edit'])->name('edit');
            Route::put('/{entity}/{id}', [CrudRouterController::class, 'update'])
                ->middleware('count.operation:action')
                ->name('update');
            Route::delete('/{entity}/{id}', [CrudRouterController::class, 'destroy'])
                ->middleware('count.operation:action')
                ->name('destroy');
        });

    Route::prefix('reportes')
        ->middleware('user.role:administrador,almacenista,gestor')
        ->name('reportes.')
        ->group(function (): void {
            Route::get('/', [ReporteInventarioController::class, 'index'])->name('index');
            Route::get('/inventario', [ReporteInventarioController::class, 'index'])->name('inventario');
            Route::get('/inventario/export', [ReporteInventarioController::class, 'export'])->name('inventario.export');
            Route::get('/inventario/print', [ReporteInventarioController::class, 'print'])->name('inventario.print');

            Route::get('/inventario-mensual', [ReporteLegacyController::class, 'inventarioMensual'])->name('inventario-mensual');
            Route::get('/inventario-mensual/export', [ReporteLegacyController::class, 'inventarioMensualExport'])->name('inventario-mensual.export');
            Route::get('/inventario-mensual/print', [ReporteLegacyController::class, 'inventarioMensualPrint'])->name('inventario-mensual.print');

            Route::get('/stock', [ReporteLegacyController::class, 'stock'])->name('stock');
            Route::get('/stock/export', [ReporteLegacyController::class, 'stockExport'])->name('stock.export');
            Route::get('/stock/print', [ReporteLegacyController::class, 'stockPrint'])->name('stock.print');

            Route::get('/salidasap', [ReporteLegacyController::class, 'salidasap'])->name('salidasap');
            Route::get('/salidasap/export', [ReporteLegacyController::class, 'salidasapExport'])->name('salidasap.export');
            Route::get('/salidasap/print', [ReporteLegacyController::class, 'salidasapPrint'])->name('salidasap.print');
            Route::post('/salidasap/clear', [ReporteLegacyController::class, 'salidasapClear'])
                ->middleware('admin.tipo')
                ->name('salidasap.clear');

            Route::get('/operaciones', [ReporteLegacyController::class, 'operaciones'])->name('operaciones');
            Route::get('/operaciones/export', [ReporteLegacyController::class, 'operacionesExport'])->name('operaciones.export');
            Route::get('/operaciones/print', [ReporteLegacyController::class, 'operacionesPrint'])->name('operaciones.print');

            Route::get('/transferencias', [ReporteLegacyController::class, 'transferencias'])->name('transferencias');
            Route::get('/transferencias/export', [ReporteLegacyController::class, 'transferenciasExport'])->name('transferencias.export');
            Route::get('/transferencias/print', [ReporteLegacyController::class, 'transferenciasPrint'])->name('transferencias.print');

            Route::get('/prestamos', [ReporteLegacyController::class, 'prestamos'])->name('prestamos');
            Route::get('/prestamos/export', [ReporteLegacyController::class, 'prestamosExport'])->name('prestamos.export');
            Route::get('/prestamos/print', [ReporteLegacyController::class, 'prestamosPrint'])->name('prestamos.print');

            Route::get('/seguimiento', [ReporteLegacyController::class, 'seguimiento'])->name('seguimiento');
            Route::get('/seguimiento/export', [ReporteLegacyController::class, 'seguimientoExport'])->name('seguimiento.export');
            Route::get('/seguimiento/print', [ReporteLegacyController::class, 'seguimientoPrint'])->name('seguimiento.print');

            Route::get('/dotaciones', [ReporteLegacyController::class, 'dotaciones'])->name('dotaciones');
            Route::get('/dotaciones/export', [ReporteLegacyController::class, 'dotacionesExport'])->name('dotaciones.export');
            Route::get('/dotaciones/print', [ReporteLegacyController::class, 'dotacionesPrint'])->name('dotaciones.print');
        
            Route::get('/ship-chandler', [ReporteShipChandlerController::class, 'index'])->middleware('admin.tipo')->name('ship-chandler.index');
        });

    Route::prefix('graficas')
        ->middleware('user.role:administrador,almacenista,gestor')
        ->name('graficas.')
        ->group(function (): void {
            Route::get('/', [GraficasController::class, 'index'])->name('index');
        });
    });
