<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\CategoryController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\TableController;
use App\Http\Controllers\PosController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\SaleController;
use App\Http\Controllers\KitchenController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\SettingController;
use App\Http\Controllers\ExpenseController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\ClientController;
use App\Http\Controllers\ReservationController;
use App\Http\Controllers\SystemController;
use App\Http\Controllers\RolePermissionController;

/*
|--------------------------------------------------------------------------
| WEB ROUTES
|--------------------------------------------------------------------------
| Sistema POS - Gestión de Restaurante
|
| Jerarquía de roles (6 niveles):
|   1. superadmin - Administrador del Sistema (Protegido, bypass total)
|   2. admin      - Administrador del Negocio
|   3. gerente    - Gerente
|   4. cashier    - Cajero
|   5. waiter     - Mozo
|   6. kitchen    - Cocina
|
| El middleware 'role' valida pertenencia a un rol.
| El middleware 'module' valida que el usuario tenga permiso al módulo
|   según la tabla role_permissions (configurable desde Roles y Permisos).
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| 1. AUTENTICACIÓN
|--------------------------------------------------------------------------
*/

Route::get('/login', [LoginController::class, 'show'])
    ->name('login');

Route::post('/login', [LoginController::class, 'login'])
    ->name('login.perform');

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


/*
|--------------------------------------------------------------------------
| 2. USUARIOS AUTENTICADOS
|--------------------------------------------------------------------------
*/

Route::middleware(['auth'])->group(function () {


    /*
    |--------------------------------------------------------------------------
    | 2.0 RUTAS EXCLUSIVAS: ADMINISTRADOR DEL SISTEMA
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin', 'module:roles_permissions,system'])->group(function () {

        Route::get('/roles-permissions', [RolePermissionController::class, 'index'])
            ->name('roles.permissions.index');

        Route::post('/roles-permissions', [RolePermissionController::class, 'update'])
            ->name('roles.permissions.update');

        Route::post('/roles-permissions/seed', [RolePermissionController::class, 'seedPermissions'])
            ->name('roles.permissions.seed');

        Route::get('/system', [SystemController::class, 'index'])
            ->name('system.index');

        Route::post('/system/reset', [SystemController::class, 'resetData'])
            ->name('system.reset');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.1 DASHBOARD
    |--------------------------------------------------------------------------
    | Permisos en roles: superadmin, admin, gerente, cashier
    | Permiso dinámico (module:dashboard) -> configurable
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente,cashier', 'module:dashboard'])->group(function () {
        Route::get('/', [DashboardController::class, 'index'])
            ->name('dashboard');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.2 REPORTES GERENCIALES
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente', 'module:reports'])->group(function () {
        Route::get('/reports', [ReportController::class, 'index'])
            ->name('reports.index');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.3 POS / PUNTO DE VENTA
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente,cashier,waiter', 'module:pos'])->group(function () {

        Route::get('/pos', [PosController::class, 'index'])
            ->name('pos.index');

        Route::get('/pos/table/{table}', [PosController::class, 'order'])
            ->name('pos.order');

        Route::post('/pos/order/{table}/add', [PosController::class, 'addToOrder'])
            ->name('pos.add');

        Route::get('/pos/order/{order}/precheck', [PosController::class, 'precheck'])
            ->name('pos.precheck');

        Route::get('/pos/order/{order}/kitchen-ticket', [PosController::class, 'kitchenTicket'])
            ->name('pos.kitchen');

        Route::post('/pos/order/{order}/discount', [PosController::class, 'applyDiscount'])
            ->name('pos.discount');

        Route::post('/pos/order/{order}/move', [PosController::class, 'moveTable'])
            ->name('pos.move');

        Route::get('/pos/order/{order}/split-content', [PosController::class, 'getSplitContent'])
            ->name('pos.split.content');

        Route::post('/pos/order/{order}/split', [PosController::class, 'processSplit'])
            ->name('pos.split');

        Route::post('/pos/detail/{detail}/update', [PosController::class, 'updateQuantity'])
            ->name('pos.update');

        Route::post('/pos/detail/{detail}/note', [PosController::class, 'updateNote'])
            ->name('pos.note');

        Route::delete('/pos/detail/{detail}', [PosController::class, 'removeItem'])
            ->name('pos.remove');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.4 COCINA
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente,kitchen', 'module:kitchen'])->group(function () {

        Route::get('/kitchen', [KitchenController::class, 'index'])
            ->name('kitchen.index');

        Route::post('/kitchen/{detail}/status', [KitchenController::class, 'updateStatus'])
            ->name('kitchen.update');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.5 RESERVAS
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente,cashier,waiter', 'module:reservations'])->group(function () {

        Route::get('/reservations', [ReservationController::class, 'index'])
            ->name('reservations.index');

        Route::post('/reservations', [ReservationController::class, 'store'])
            ->name('reservations.store');

        Route::put('/reservations/{reservation}/status', [ReservationController::class, 'updateStatus'])
            ->name('reservations.status');

        Route::delete('/reservations/{reservation}', [ReservationController::class, 'destroy'])
            ->name('reservations.destroy');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.6 ZONA FINANCIERA (CAJA)
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente,cashier', 'module:sales,expenses'])->group(function () {

        Route::post('/pos/order/{order}/checkout', [PosController::class, 'checkout'])
            ->name('pos.checkout');

        Route::get('/sales', [SaleController::class, 'index'])
            ->name('sales.index');

        Route::get('/sales/daily-report', [SaleController::class, 'dailyReport'])
            ->name('sales.daily.report');

        Route::get('/sales/{order}/ticket', [SaleController::class, 'ticket'])
            ->name('sales.ticket');

        Route::resource('expenses', ExpenseController::class)
            ->only(['store', 'destroy']);
    });


    /*
    |--------------------------------------------------------------------------
    | 2.7 CLIENTES
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente', 'module:clients'])->group(function () {
        Route::resource('clients', ClientController::class);
    });


    /*
    |--------------------------------------------------------------------------
    | 2.8 CATEGORÍAS - CRUD COMPLETO
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente', 'module:categories'])->group(function () {
        Route::resource('categories', CategoryController::class);
        Route::post('/categories/{category}/toggle', [CategoryController::class, 'toggle'])
            ->name('categories.toggle');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.9 PRODUCTOS / INVENTARIO / KARDEX
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente', 'module:products,inventory_logs'])->group(function () {

        Route::post('/products/{product}/adjust', [ProductController::class, 'adjustStock'])
            ->name('products.adjust');

        Route::post('/products/{product}/toggle', [ProductController::class, 'toggleStatus'])
            ->name('products.toggle');

        Route::resource('products', ProductController::class);

        Route::get('/inventory/logs', function () {
            $logs = \App\Models\InventoryLog::with(['product', 'user'])
                ->orderBy('created_at', 'desc')
                ->paginate(50);
            return view('products.kardex', compact('logs'));
        })->name('inventory.logs')
         ->middleware('module:inventory_logs');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.10 MAPA DE MESAS / SALÓN
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente', 'module:tables'])->group(function () {

        Route::get('/tables', [TableController::class, 'index'])
            ->name('tables.index');

        Route::post('/tables/area', [TableController::class, 'storeArea'])
            ->name('tables.storeArea');

        Route::delete('/tables/area/{area}', [TableController::class, 'destroyArea'])
            ->name('tables.destroyArea');

        Route::post('/tables/table', [TableController::class, 'storeTable'])
            ->name('tables.storeTable');

        Route::delete('/tables/table/{table}', [TableController::class, 'destroyTable'])
            ->name('tables.destroyTable');

        Route::post('/tables/update-positions', [TableController::class, 'updatePositions'])
            ->name('tables.updatePositions');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.11 CONFIGURACIÓN
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente', 'module:settings'])->group(function () {
        Route::get('/settings', [SettingController::class, 'index'])
            ->name('settings.index');

        Route::post('/settings', [SettingController::class, 'update'])
            ->name('settings.update');
    });


    /*
    |--------------------------------------------------------------------------
    | 2.12 USUARIOS / PERSONAL
    |--------------------------------------------------------------------------
    | Acceso: superadmin / admin / gerente
    | Restricciones finas dentro del UserController según jerarquía.
    |--------------------------------------------------------------------------
    */

    Route::middleware(['role:superadmin,admin,gerente', 'module:users'])->group(function () {
        Route::resource('users', UserController::class);
    });

});
