<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Artisan;
use App\Http\Controllers\ConfiguracionEmpresaController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\TokenController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\OrdenLavanderiaController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

Route::post('/registro', [UserController::class, 'registro']);

// Ruta pública para configuración básica (logo, favicon, etc.) - no requiere autenticación
Route::get('/configuracion-empresa/public', [ConfiguracionEmpresaController::class, 'publicConfig']);

// Ruta pública para ejecutar storage:link
Route::get('/storage-link', function () {
    try {
        Artisan::call('storage:link');
        $output = Artisan::output();
        return response()->json([
            'success' => true,
            'message' => 'Enlace simbólico de storage creado correctamente',
            'output' => $output
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error ejecutando storage:link: ' . $e->getMessage()
        ], 500);
    }
});

// Ruta pública para generar la clave de aplicación
Route::get('/generate-key', function () {
    try {
        Artisan::call('key:generate');
        $output = Artisan::output();
        return response()->json([
            'success' => true,
            'message' => 'Clave de aplicación generada correctamente',
            'output' => $output
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error generando clave de aplicación: ' . $e->getMessage()
        ], 500);
    }
});

Route::prefix('/tokens')->group(function (): void {
    Route::post('/create', [TokenController::class, 'createToken']);
    Route::post('/pw', [TokenController::class, 'createResetPW']);
    Route::post('/savepw', [TokenController::class, 'saveResetPW']);
    Route::post('/getpwuuid', [TokenController::class, 'getUserUuid']);
});

Route::prefix('/configuracion-empresa')->group(function (): void {
    Route::get('/', [ConfiguracionEmpresaController::class, 'index']);
});

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

    Route::prefix('/tokens')->group(function (): void {
        Route::delete('/{token}', [TokenController::class, 'expire']);
        Route::get('/permissions', function () {
            if (!auth()->check()) {
                return response()->json(['all' => false, 'permissions' => []], 401);
            }
            
            $user = auth()->user();
            $permissions = $user->getAllPermissions()->pluck('name')->toArray();
            $roles = $user->getRoleNames()->toArray();
            
            // Si es Administrador, tiene todos los permisos
            $isAdmin = in_array('Administrador', $roles);
            
            return response()->json([
                'all' => $isAdmin,
                'permissions' => $permissions,
                'roles' => $roles
            ]);
        });
    });

    Route::prefix('/users')->group(function (): void {
        Route::get('/', fn (Request $request) => $request->user()->load('roles'));
        Route::get('/all', [UserController::class, 'getUsers']);
        Route::get('/{user}', [UserController::class, 'getUser']);
        Route::post('/create', [UserController::class, 'store']);
        Route::put('/{user}/edit', [UserController::class, 'update']);
        Route::put('/{user}/password', [UserController::class, 'updatePassword']);
        Route::get('/{user}/mediciones', [UserController::class, 'getMediciones']);
        Route::get('/{user}/sucursales', [UserController::class, 'getSucursales']);
        Route::put('/perfil', [UserController::class, 'updatePerfil']);
        Route::get('/config/setconfig', [UserController::class, 'setConfigSucursal']);
        Route::get('/config/sucursal', [UserController::class, 'getConfigSucursal']);
        Route::get('/get/terapista', [UserController::class, 'getTerapistas']);
        Route::get('/get/revision', [UserController::class, 'getRevision']);
        Route::delete('/{user}', [UserController::class, 'destroy']);
    });

    Route::prefix('/roles')->group(function (): void {
        Route::get('/all', [RoleController::class, 'getRoles']);
        Route::get('/permissions', [RoleController::class, 'getPermissions']);
        Route::put('/{role}/permissions', [RoleController::class, 'updateRolePermissions']);
    });

    Route::prefix('/configuracion-empresa')->group(function (): void {
        Route::put('/update', [ConfiguracionEmpresaController::class, 'update']);
        Route::post('/upload-logo', [ConfiguracionEmpresaController::class, 'uploadLogo']);
        Route::post('/upload-favicon', [ConfiguracionEmpresaController::class, 'uploadFavicon']);
        Route::post('/upload-icono-mensaje', [ConfiguracionEmpresaController::class, 'uploadIconoMensaje']);
        Route::delete('/delete-logo', [ConfiguracionEmpresaController::class, 'deleteLogo']);
        Route::delete('/delete-favicon', [ConfiguracionEmpresaController::class, 'deleteFavicon']);
        Route::delete('/delete-icono-mensaje', [ConfiguracionEmpresaController::class, 'deleteIconoMensaje']);
    });

    // Módulo de Lavandería - Órdenes
    Route::prefix('/lavanderia/ordenes')->group(function (): void {
        // Recepción / Registro inicial
        Route::get('/', [OrdenLavanderiaController::class, 'index'])->middleware('role:Administrador,Recepcionista');
        Route::post('/', [OrdenLavanderiaController::class, 'store'])->middleware('role:Administrador,Recepcionista');

        // Escaneo QR para operadores
        Route::post('/escanear-qr', [OrdenLavanderiaController::class, 'escanearQR'])->middleware('role:Administrador,Operador');

        // Flujo operativo por etapas (Lavado, Secado, Planchado, Liberación)
        Route::post('/{orden}/avanzar', [OrdenLavanderiaController::class, 'avanzar'])->middleware('role:Administrador,Operador');
        Route::post('/{orden}/entregar', [OrdenLavanderiaController::class, 'marcarEntregada'])->middleware('role:Administrador,Recepcionista');

        // Dashboard tipo semáforo
        Route::get('/dashboard/resumen', [OrdenLavanderiaController::class, 'dashboard'])
            ->middleware('role:Administrador,Recepcionista,Operador');

        Route::get('/{orden}', [OrdenLavanderiaController::class, 'show'])
            ->middleware('role:Administrador,Recepcionista,Operador');
    });


}); 