<?php

use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\SucursalSelectorController;
use App\Http\Controllers\InsumoController;
use App\Http\Controllers\RecetaController;
use App\Http\Controllers\ProgramacionController;
use App\Http\Controllers\PickingController;
use App\Http\Controllers\OrdenCompraController;
use App\Http\Controllers\AlmacenController;
use App\Http\Controllers\CajaController;
use App\Http\Controllers\ProveedorController;
use App\Http\Controllers\ReporteController;
use App\Http\Controllers\Admin\UsuarioController;
use App\Http\Controllers\Admin\ConfiguracionController;
use App\Http\Controllers\Admin\AuditoriaController;
use App\Http\Controllers\Admin\SucursalController;


Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

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::get('/sucursal/seleccionar', [SucursalSelectorController::class , 'index'])
        ->name('sucursal.seleccionar');
    Route::post('/sucursal/seleccionar', [SucursalSelectorController::class , 'store'])
        ->name('sucursal.guardar');
    Route::post('/sucursal/cambiar', [SucursalSelectorController::class , 'cambiar'])
        ->name('sucursal.cambiar');
});

// ── Rutas protegidas (auth + sucursal activa) ──────────────────────────
Route::middleware(['auth', 'sucursal'])->group(function () {

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

    // ── INSUMOS ───────────────────────────────────────────────────────
    Route::middleware('permission:ver.insumos')->prefix('insumos')->name('insumos.')->group(function () {
            // 1️⃣ ÍNDICE (sin parámetros)
            Route::get('/', [InsumoController::class , 'index'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS (con palabras clave fijas: create, verificar, etc.)
            Route::middleware('permission:crear.insumos')
                ->get('/create', [InsumoController::class , 'create'])->name('create');
            Route::middleware('permission:crear.insumos')
                ->post('/', [InsumoController::class , 'store'])->name('store');

            Route::middleware('permission:editar.insumos')
                ->get('/{insumo}/edit', [InsumoController::class , 'edit'])->name('edit');
            Route::middleware('permission:editar.insumos')
                ->put('/{insumo}', [InsumoController::class , 'update'])->name('update');

            Route::middleware('permission:eliminar.insumos')
                ->delete('/{insumo}', [InsumoController::class , 'destroy'])->name('destroy');

            Route::get('/verificar/nombre', [InsumoController::class , 'verificarNombre'])
                ->name('verificar');
            
            // 3️⃣ RUTAS CON PARÁMETROS COMODÍN (SIEMPRE AL FINAL)
            Route::get('/{insumo}', [InsumoController::class , 'show'])->name('show');
        });

        // ── RECETAS ───────────────────────────────────────────────────────
        Route::middleware('permission:ver.recetas')->prefix('recetas')->name('recetas.')->group(function () {
            
            // 1️⃣ ÍNDICE
            Route::get('/', [RecetaController::class, 'index'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS (ANTES de rutas con parámetros)
            Route::middleware('permission:crear.recetas')->group(function () {
                Route::post('/', [RecetaController::class, 'store'])->name('store');
            });
            
            // Endpoint AJAX para verificar nombre duplicado
            Route::get('/verificar/nombre', [RecetaController::class, 'verificarNombre'])
                ->name('verificar');
            
            // 3️⃣ RUTAS CON PARÁMETROS (SIEMPRE AL FINAL)
            Route::get('/{receta}', [RecetaController::class, 'show'])->name('show');
            
            Route::middleware('permission:editar.recetas')->group(function () {
                Route::get('/{receta}/edit', [RecetaController::class, 'edit'])->name('edit');
                Route::put('/{receta}', [RecetaController::class, 'update'])->name('update');
            });
            
            Route::middleware('permission:eliminar.recetas')
                ->delete('/{receta}', [RecetaController::class, 'destroy'])->name('destroy');
        });
 

            // ── CALENDARIO / PROGRAMACIÓN ─────────────────────────────────────
        Route::middleware('permission:ver.programacion')->prefix('programaciones')->name('programaciones.')->group(function () {
            
            // 1️⃣ ÍNDICE
            Route::get('/', [ProgramacionController::class, 'index'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS (ANTES de rutas con parámetros)
            Route::middleware('permission:crear.programacion')->group(function () {
                Route::get('/create', [ProgramacionController::class, 'create'])->name('create');
                Route::post('/', [ProgramacionController::class, 'store'])->name('store');
            });
            
            // 3️⃣ RUTAS CON PARÁMETROS (SIEMPRE AL FINAL)
            Route::get('/{programacion}', [ProgramacionController::class, 'show'])->name('show');
            
            Route::middleware('permission:crear.programacion')->group(function () {
                Route::get('/{programacion}/edit', [ProgramacionController::class, 'edit'])->name('edit');
                Route::put('/{programacion}', [ProgramacionController::class, 'update'])->name('update');
                Route::delete('/{programacion}', [ProgramacionController::class, 'destroy'])->name('destroy');
            });
            
            Route::middleware('permission:confirmar.programacion')
                ->post('/{programacion}/confirmar', [ProgramacionController::class, 'confirmar'])->name('confirmar');
        });

            // ── PICKING ───────────────────────────────────────────────────────
        Route::middleware('permission:ver.picking')->prefix('picking')->name('picking.')->group(function () {
            
            // 1️⃣ ÍNDICE
            Route::get('/', [PickingController::class, 'index'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS (ANTES de rutas con parámetros)
            Route::middleware('permission:completar.picking')->group(function () {
                Route::post('/{picking}/completar-bloque', [PickingController::class, 'completarBloque'])->name('completarBloque');
                Route::patch('/items/{item}/completar', [PickingController::class, 'completarItem'])->name('completar');
                Route::patch('/items/{item}/deshacer', [PickingController::class, 'deshacerItem'])->name('deshacer');
            });
            
            // 3️⃣ RUTAS CON PARÁMETROS (SIEMPRE AL FINAL)
            Route::get('/{picking}', [PickingController::class, 'show'])->name('show');
            Route::get('/{picking}/progreso', [PickingController::class, 'progreso'])->name('progreso'); // AJAX polling
            
            Route::middleware('permission:crear.compras')
                ->post('/{picking}/pre-compra', [PickingController::class, 'generarPreCompraFaltantes'])->name('precompra');
        });
 

        // ── COMPRAS ───────────────────────────────────────────────────────
        Route::middleware('permission:ver.compras')->prefix('compras')->name('compras.')->group(function () {
            
            // 1️⃣ ÍNDICE
            Route::get('/', [OrdenCompraController::class, 'index'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS (ANTES de rutas con parámetros)
            Route::middleware('permission:crear.compras')->group(function () {
                Route::post('/', [OrdenCompraController::class, 'store'])->name('store');
                Route::post('/auto', [OrdenCompraController::class, 'generarAuto'])->name('auto'); // pre-compra automática
            });
            
            // 3️⃣ RUTAS CON PARÁMETROS (SIEMPRE AL FINAL)
            Route::get('/{orden}', [OrdenCompraController::class, 'show'])->name('show');
            
            Route::middleware('permission:editar.compras')->group(function () {
                Route::get('/{orden}/edit', [OrdenCompraController::class, 'edit'])->name('edit');
                Route::put('/{orden}', [OrdenCompraController::class, 'update'])->name('update');
                Route::patch('/{orden}/cancelar', [OrdenCompraController::class, 'cancelar'])->name('cancelar');
            });
            
            Route::middleware('permission:aprobar.compras')->group(function () {
                Route::patch('/{orden}/aprobar', [OrdenCompraController::class, 'aprobar'])->name('aprobar');
                Route::patch('/{orden}/en-camino', [OrdenCompraController::class, 'marcarEnCamino'])->name('enCamino');
            });
            
            Route::middleware('permission:confirmar.llegada.compras')
                ->patch('/{orden}/confirmar-llegada', [OrdenCompraController::class, 'confirmarLlegada'])->name('confirmarLlegada');
        });

        // ── ALMACÉN / KARDEX ──────────────────────────────────────────────
        Route::middleware('permission:ver.almacen')->prefix('almacen')->name('almacen.')->group(function () {
            
            // 1️⃣ ÍNDICE
            Route::get('/', [AlmacenController::class, 'index'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS (ANTES de rutas con parámetros)
            Route::get('/kardex', [AlmacenController::class, 'kardex'])->name('kardex');
            Route::get('/kardex/export', [AlmacenController::class, 'exportar'])->name('exportar');
            
            Route::post('/auto-requerimiento', [AlmacenController::class, 'autoRequerimiento'])->name('auto_req');
            
            Route::middleware('permission:ajustar.almacen')
                ->post('/ajuste', [AlmacenController::class, 'ajuste'])->name('ajuste');
        });

        // ── CAJA ──────────────────────────────────────────────────────────
        Route::middleware('permission:ver.caja')->prefix('caja')->name('caja.')->group(function () {
            
            // 1️⃣ ÍNDICE
            Route::get('/', [CajaController::class, 'index'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS (ANTES de rutas con parámetros)
            Route::get('/historial', [CajaController::class, 'historial'])->name('historial');
            
            Route::middleware('permission:registrar.caja')->group(function () {
                Route::post('/abrir', [CajaController::class, 'abrir'])->name('abrir');
                Route::post('/movimiento', [CajaController::class, 'movimiento'])->name('movimiento');
            });
            
            Route::middleware('permission:cerrar.caja')
                ->post('/cerrar', [CajaController::class, 'cerrar'])->name('cerrar');
            
            Route::middleware('permission:anular.caja')
                ->patch('/movimiento/{mov}/anular', [CajaController::class, 'anular'])->name('anular');
            
            // 3️⃣ RUTAS CON PARÁMETROS (SIEMPRE AL FINAL)
            Route::get('/sesion/{sesion}', [CajaController::class, 'sesion'])->name('sesion');
            
            Route::middleware('permission:exportar.caja')
                ->get('/sesion/{sesion}/export', [CajaController::class, 'exportar'])->name('exportar');
        });

        // ── PROVEEDORES ───────────────────────────────────────────────────
        Route::middleware('permission:ver.proveedores')->prefix('proveedores')->name('proveedores.')->group(function () {
            
            // 1️⃣ ÍNDICE
            Route::get('/', [ProveedorController::class, 'index'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS (ANTES de rutas con parámetros)
            Route::middleware('permission:crear.proveedores')->group(function () {
                Route::get('/create', [ProveedorController::class, 'create'])->name('create');
                Route::post('/', [ProveedorController::class, 'store'])->name('store');
            });
            
            // 3️⃣ RUTAS CON PARÁMETROS (SIEMPRE AL FINAL)
            Route::get('/{proveedor}', [ProveedorController::class, 'show'])->name('show');
            
            Route::middleware('permission:editar.proveedores')->group(function () {
                Route::get('/{proveedor}/edit', [ProveedorController::class, 'edit'])->name('edit');
                Route::put('/{proveedor}', [ProveedorController::class, 'update'])->name('update');
            });
        });

        // ── COSTOS / REPORTES ─────────────────────────────────────────────
        Route::middleware('permission:ver.costos')->prefix('costos')->name('costos.')->group(function () {
            
            // 1️⃣ ÍNDICE
            Route::get('/', [ReporteController::class, 'costos'])->name('index');
            
            // 2️⃣ RUTAS ESPECÍFICAS
            Route::get('/recetas', [ReporteController::class, 'recetas'])->name('recetas');
            
            Route::get('/compras', [ReporteController::class, 'compras'])
                ->middleware('permission:ver.reportes')
                ->name('compras');
            
            Route::get('/consolidado', [ReporteController::class, 'consolidado'])
                ->middleware('permission:ver.consolidado')
                ->name('consolidado');
        });

        // ── ADMINISTRACIÓN (solo admin) ────────────────────────────────────
        Route::middleware('role:admin')->prefix('admin')->name('admin.')->group(function () {

            // ── USUARIOS ───────────────────────────────────────────────────
            Route::prefix('usuarios')->name('usuarios.')->group(function () {
                
                // 1️⃣ ÍNDICE
                Route::get('/', [UsuarioController::class, 'index'])->name('index');
                
                // 2️⃣ RUTAS ESPECÍFICAS
                Route::get('/create', [UsuarioController::class, 'create'])->name('create');
                Route::post('/', [UsuarioController::class, 'store'])->name('store');
                Route::get('/verificar/email', [UsuarioController::class, 'verificarEmail'])->name('verificarEmail');
                
                // 3️⃣ RUTAS CON PARÁMETROS
                Route::get('/{usuario}/edit', [UsuarioController::class, 'edit'])->name('edit');
                Route::put('/{usuario}', [UsuarioController::class, 'update'])->name('update');
                Route::patch('/{usuario}/toggle', [UsuarioController::class, 'toggle'])->name('toggle');
            });

            // ── CONFIGURACIÓN GLOBAL ───────────────────────────────────────
            Route::get('configuracion', [ConfiguracionController::class, 'index'])->name('configuracion.index');
            Route::put('configuracion', [ConfiguracionController::class, 'update'])->name('configuracion.update');

            // ── AUDITORÍA ──────────────────────────────────────────────────
            Route::get('auditoria', [AuditoriaController::class, 'index'])->name('auditoria.index');
            Route::get('auditoria/{auditoria}', [AuditoriaController::class, 'show'])->name('auditoria.show');

            // ── SUCURSALES ──────────────────────────────────────────────────
            Route::resource('sucursales', \App\Http\Controllers\Admin\SucursalController::class)->except(['create', 'show', 'edit']);
        });
            
    });

require __DIR__ . '/auth.php';
