<?php

use App\Http\Controllers\AjusteInventarioController;
use App\Http\Controllers\AuditoriaController;
use App\Http\Controllers\BackupController;
use App\Http\Controllers\CategoriaController;
use App\Http\Controllers\ClienteController;
use App\Http\Controllers\ConsultaController;
use App\Http\Controllers\ConfiguracionNegocioController;
use App\Http\Controllers\CorteCajaController;
use App\Http\Controllers\CuponController;
use App\Http\Controllers\DepartamentoController;
use App\Http\Controllers\EntradaInventarioController;
use App\Http\Controllers\EstadisticaController;
use App\Http\Controllers\FacturacionController;
use App\Http\Controllers\FacturaController;
use App\Http\Controllers\InstalacionController;
use App\Http\Controllers\InventarioController;
use App\Http\Controllers\NotaCreditoController;
use App\Http\Controllers\OperadorController;
use App\Http\Controllers\PerfilController;
use App\Http\Controllers\ProveedorController;
use App\Http\Controllers\ReporteController;
use App\Http\Controllers\ReposicionInventarioController;
use App\Http\Controllers\RoleController;
use App\Http\Middleware\EnsureNoInstalado;
use App\Http\Controllers\TipoImpuestoController;
use App\Http\Controllers\UnidadController;
use Illuminate\Support\Facades\Route;

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

Route::prefix('instalar')->middleware(EnsureNoInstalado::class)->name('instalador.')->group(function () {
    Route::get('/', [InstalacionController::class, 'requisitos'])->name('requisitos');
    Route::get('/base-de-datos', [InstalacionController::class, 'baseDeDatos'])->name('baseDeDatos');
    Route::post('/base-de-datos', [InstalacionController::class, 'procesarBaseDeDatos'])->name('baseDeDatos.procesar');
    Route::get('/migrando', [InstalacionController::class, 'migrando'])->name('migrando');
    Route::post('/migrando', [InstalacionController::class, 'procesarMigracion'])->name('migrando.procesar');
    Route::get('/administrador', [InstalacionController::class, 'administrador'])->name('administrador');
    Route::post('/administrador', [InstalacionController::class, 'procesarAdministrador'])->name('administrador.procesar');
    Route::get('/finalizar', [InstalacionController::class, 'finalizar'])->name('finalizar');
});

Auth::routes(['register' => false]);

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::middleware('auth')->group(function () {
    Route::middleware('permiso:catalogos.gestionar')->group(function () {
        $catalogos = [
            'clientes' => ['controller' => ClienteController::class, 'param' => 'cliente'],
            'proveedores' => ['controller' => ProveedorController::class, 'param' => 'proveedor'],
            'categorias' => ['controller' => CategoriaController::class, 'param' => 'categoria'],
            'departamentos' => ['controller' => DepartamentoController::class, 'param' => 'departamento'],
            'unidades' => ['controller' => UnidadController::class, 'param' => 'unidad'],
        ];

        foreach ($catalogos as $uri => $config) {
            Route::resource($uri, $config['controller'])->except('show', 'destroy');
            Route::patch("{$uri}/{{$config['param']}}/toggle", [$config['controller'], 'toggle'])->name("{$uri}.toggle");
        }

        Route::resource('tipos-impuesto', TipoImpuestoController::class)
            ->except('show', 'destroy')
            ->parameters(['tipos-impuesto' => 'tipo_impuesto']);
        Route::patch('tipos-impuesto/{tipo_impuesto}/toggle', [TipoImpuestoController::class, 'toggle'])->name('tipos-impuesto.toggle');
        Route::post('tipos-impuesto/{tipo_impuesto}/predeterminado', [TipoImpuestoController::class, 'marcarPredeterminado'])->name('tipos-impuesto.predeterminado');

        Route::get('/negocio', [ConfiguracionNegocioController::class, 'edit'])->name('configuracion.edit');
        Route::put('/negocio', [ConfiguracionNegocioController::class, 'update'])->name('configuracion.update');
    });

    Route::middleware('permiso:inventario.gestionar')->group(function () {
        Route::resource('inventario', InventarioController::class)->except('show', 'destroy');
        Route::patch('inventario/{inventario}/toggle', [InventarioController::class, 'toggle'])->name('inventario.toggle');

        Route::get('/ajustes-inventario', [AjusteInventarioController::class, 'create'])->name('ajustes.create');
        Route::post('/ajustes-inventario', [AjusteInventarioController::class, 'store'])->name('ajustes.store');

        Route::get('/entradas-inventario', [EntradaInventarioController::class, 'create'])->name('entradas.create');
        Route::post('/entradas-inventario', [EntradaInventarioController::class, 'store'])->name('entradas.store');

        Route::get('/reposicion-inventario', [ReposicionInventarioController::class, 'index'])->name('reposicion.index');
    });

    Route::middleware('permiso:pos.acceso')->group(function () {
        Route::get('/facturacion', [FacturacionController::class, 'index'])->name('facturacion.index');
        Route::post('/facturacion', [FacturacionController::class, 'store'])->name('facturacion.store');
        Route::post('/facturacion/carrito', [FacturacionController::class, 'addItem'])->name('facturacion.carrito.store');
        Route::patch('/facturacion/carrito/{item}', [FacturacionController::class, 'updateItem'])->name('facturacion.carrito.update');
        Route::delete('/facturacion/carrito/{item}', [FacturacionController::class, 'removeItem'])->name('facturacion.carrito.destroy');
    });

    Route::middleware('permiso:facturas.consultar')->group(function () {
        Route::get('/facturas', [FacturaController::class, 'index'])->name('facturas.index');
        Route::post('/facturas/filtro', [FacturaController::class, 'filtrar'])->name('facturas.filtrar');
    });

    // Ver/imprimir una factura puntual: alcanza con acceso a caja (para
    // reimprimir) O con el permiso de consulta completa.
    Route::middleware('permiso:facturas.consultar,pos.acceso')->group(function () {
        Route::get('/facturas/buscar-numero', [FacturaController::class, 'buscarPorNumero'])->name('facturas.buscarPorNumero');
        Route::get('/facturas/{factura}', [FacturaController::class, 'show'])->name('facturas.show');
        Route::get('/facturas/{factura}/pdf', [FacturaController::class, 'pdf'])->name('facturas.pdf');
    });

    Route::middleware('permiso:reportes.ver')->group(function () {
        Route::get('/consultas/inventario-familia', [ConsultaController::class, 'inventarioPorFamilia'])->name('consultas.inventarioFamilia');
        Route::post('/consultas/inventario-familia/filtro', [ConsultaController::class, 'inventarioPorFamiliaFiltrar'])->name('consultas.inventarioFamilia.filtrar');
        Route::get('/consultas/facturas-familia', [ConsultaController::class, 'facturasPorFamilia'])->name('consultas.facturasFamilia');
        Route::post('/consultas/facturas-familia/filtro', [ConsultaController::class, 'facturasPorFamiliaFiltrar'])->name('consultas.facturasFamilia.filtrar');
        Route::get('/entradas-inventario/historial', [EntradaInventarioController::class, 'index'])->name('consultas.entradas');
        Route::post('/entradas-inventario/historial/filtro', [EntradaInventarioController::class, 'filtrar'])->name('consultas.entradas.filtrar');

        Route::get('/reportes', [ReporteController::class, 'index'])->name('reportes.index');
        Route::post('/reportes/ventas', [ReporteController::class, 'ventas'])->name('reportes.ventas');
        Route::get('/reportes/inventario', [ReporteController::class, 'inventario'])->name('reportes.inventario');
        Route::post('/reportes/compras', [ReporteController::class, 'compras'])->name('reportes.compras');
        Route::get('/reportes/estadisticas', [EstadisticaController::class, 'index'])->name('reportes.estadisticas');
        Route::post('/reportes/estadisticas/filtro', [EstadisticaController::class, 'filtrar'])->name('reportes.estadisticas.filtrar');
    });

    Route::middleware('permiso:caja.gestionar')->group(function () {
        Route::get('/notas-credito', [NotaCreditoController::class, 'index'])->name('notascredito.index');
        Route::post('/notas-credito/{factura}/pagar', [NotaCreditoController::class, 'pagar'])->name('notascredito.pagar');

        Route::get('/corte-caja', [CorteCajaController::class, 'index'])->name('cortecaja.index');
    });

    Route::get('/perfil', [PerfilController::class, 'edit'])->name('perfil.edit');
    Route::put('/perfil', [PerfilController::class, 'update'])->name('perfil.update');

    Route::middleware('admin')->group(function () {
        Route::resource('operadores', OperadorController::class)->except('show', 'destroy')->parameters(['operadores' => 'operador']);
        Route::patch('operadores/{operador}/toggle', [OperadorController::class, 'toggle'])->name('operadores.toggle');
        Route::post('operadores/{operador}/reset-password', [OperadorController::class, 'resetPassword'])->name('operadores.reset-password');

        Route::resource('roles', RoleController::class)->except('show', 'destroy');
        Route::delete('roles/{role}', [RoleController::class, 'destroy'])->name('roles.destroy');

        Route::patch('/facturas/{factura}/estado', [FacturaController::class, 'actualizarEstado'])->name('facturas.estado.update');
    });

    Route::middleware('permiso:auditoria.ver')->group(function () {
        Route::get('/auditoria', [AuditoriaController::class, 'index'])->name('auditoria.index');
    });

    Route::middleware('permiso:cupones.gestionar')->group(function () {
        Route::resource('cupones', CuponController::class)->except('show', 'destroy')->parameters(['cupones' => 'cupon']);
        Route::patch('cupones/{cupon}/toggle', [CuponController::class, 'toggle'])->name('cupones.toggle');
    });

    Route::middleware('permiso:backup.gestionar')->group(function () {
        Route::get('/backup', [BackupController::class, 'index'])->name('backup.index');
        Route::post('/backup', [BackupController::class, 'generar'])->name('backup.generar');
        Route::get('/backup/{archivo}/descargar', [BackupController::class, 'descargar'])->name('backup.descargar');
    });
});
