<?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\MarcaController;
use App\Http\Controllers\BoletoController;
use App\Http\Controllers\ConfiguracionHardwareController;
use App\Http\Controllers\TipoCargaController;
use App\Http\Controllers\DestinoController;
use App\Http\Controllers\PlacaFrecuenteController;
use App\Http\Controllers\ReporteController;

/*
|--------------------------------------------------------------------------
| 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 () {
    // Dashboard: estadísticas (usa el mismo endpoint que reportes/estadisticas)
    Route::get('/dashboard/estadisticas', [ReporteController::class, 'estadisticas']);

    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']);
    });

    Route::prefix('/marcas')->group(function (): void {
        Route::get('/', [MarcaController::class, 'index']);
        Route::post('/', [MarcaController::class, 'store']);
        Route::get('/{marca}', [MarcaController::class, 'show']);
        Route::put('/{marca}', [MarcaController::class, 'update']);
        Route::delete('/{marca}', [MarcaController::class, 'destroy']);
        Route::post('/{marca}/upload-logo', [MarcaController::class, 'uploadLogo']);
        Route::delete('/{marca}/delete-logo', [MarcaController::class, 'deleteLogo']);
    });

    // Módulo de Operaciones - Boletos
    Route::prefix('/boletos')->group(function (): void {
        Route::get('/', [BoletoController::class, 'index']);
        Route::post('/', [BoletoController::class, 'store']);
        Route::get('/{boleto}', [BoletoController::class, 'show']);
        Route::post('/capturar-foto', [BoletoController::class, 'capturarFoto']);
        Route::post('/validar', [BoletoController::class, 'validar']);
    });

    // Módulo de Administración - Configuración Hardware
    Route::prefix('/configuracion-hardware')->group(function (): void {
        Route::get('/', [ConfiguracionHardwareController::class, 'index']);
        Route::post('/', [ConfiguracionHardwareController::class, 'store']);
        Route::get('/{configuracionHardware}', [ConfiguracionHardwareController::class, 'show']);
        Route::put('/{configuracionHardware}', [ConfiguracionHardwareController::class, 'update']);
        Route::delete('/{configuracionHardware}', [ConfiguracionHardwareController::class, 'destroy']);
    });

    // Catálogos - Tipos de Carga
    Route::prefix('/tipos-carga')->group(function (): void {
        Route::get('/', [TipoCargaController::class, 'index']);
        Route::post('/', [TipoCargaController::class, 'store']);
        Route::get('/{tipoCarga}', [TipoCargaController::class, 'show']);
        Route::put('/{tipoCarga}', [TipoCargaController::class, 'update']);
        Route::delete('/{tipoCarga}', [TipoCargaController::class, 'destroy']);
    });

    // Catálogos - Destinos
    Route::prefix('/destinos')->group(function (): void {
        Route::get('/', [DestinoController::class, 'index']);
        Route::post('/', [DestinoController::class, 'store']);
        Route::get('/{destino}', [DestinoController::class, 'show']);
        Route::put('/{destino}', [DestinoController::class, 'update']);
        Route::delete('/{destino}', [DestinoController::class, 'destroy']);
    });

    // Catálogos - Placas Frecuentes
    Route::prefix('/placas-frecuentes')->group(function (): void {
        Route::get('/', [PlacaFrecuenteController::class, 'index']);
        Route::post('/', [PlacaFrecuenteController::class, 'store']);
        Route::get('/{placaFrecuente}', [PlacaFrecuenteController::class, 'show']);
        Route::put('/{placaFrecuente}', [PlacaFrecuenteController::class, 'update']);
        Route::delete('/{placaFrecuente}', [PlacaFrecuenteController::class, 'destroy']);
    });

    // Módulo de Reportes
    Route::prefix('/reportes')->group(function (): void {
        Route::get('/salidas', [ReporteController::class, 'salidas']);
        Route::get('/estadisticas', [ReporteController::class, 'estadisticas']);
        Route::get('/exportar-csv', [ReporteController::class, 'exportarCsv']);
    });

}); 