<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\CompromiseController;
use App\Http\Controllers\EvaluacionesController;
use App\Http\Controllers\InfoInstitucionController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\RegistroEvaluacionesController;
use App\Http\Controllers\ReportesController;
use App\Http\Controllers\Admin\AdminOrderController;

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

// Flujo Diagnóstico
Route::get('/flujo-diagnostika', function () {
    return view('flujo-diagnostika');
})->name('flujo-diagnostika');

// Authentication Routes
Route::get('/login', [LoginController::class, 'show'])->name('login');
Route::post('/login', [LoginController::class, 'store']);
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');

Route::get('/register', [RegisterController::class, 'show'])->name('register');
Route::post('/register', [RegisterController::class, 'store']);

// Rutas Públicas de Compromiso 1 (Flujo Libre - Sin Registro)
Route::get('/diagnostico-libre/compromiso1', [CompromiseController::class, 'compromise1Libre'])->name('compromiso1.libre');
Route::post('/diagnostico-libre/save-progress', [CompromiseController::class, 'saveProgressLibre'])->name('compromiso1.saveProgressLibre');
Route::get('/diagnostico-libre/resumen', [CompromiseController::class, 'resumenCompromiso1Libre'])->name('resumen-compromiso1.libre');

// Rutas Públicas de Compromiso 1 (Para diagnóstico sin registro anterior)
Route::get('/compromiso1', [CompromiseController::class, 'compromise1'])->name('compromiso1');
Route::post('/compromiso1/save-progress', [CompromiseController::class, 'saveProgress'])->name('compromiso1.saveProgress');
Route::get('/resumen-compromiso1', [CompromiseController::class, 'resumenCompromiso1'])->name('resumen-compromiso1');

// Compromise/Diagnosis Routes - Protected by auth middleware
Route::middleware('auth')->group(function () {
    Route::get('/evaluaciones-institucionales', [EvaluacionesController::class, 'evaluacionesInstitucionales'])->name('evaluaciones-institucionales');

    Route::get('/evaluaciones-institucionales2', function () {
        return view('evaluaciones-institucionales2');
    })->name('evaluaciones-institucionales2');

    Route::post('/evaluaciones-institucionales/guardar-progreso', [EvaluacionesController::class, 'guardarProgreso'])->name('evaluaciones.guardarProgreso');
    Route::post('/evaluaciones-institucionales/guardar-seleccion-niveles', [EvaluacionesController::class, 'guardarSeleccionNiveles'])->name('evaluaciones.guardarSeleccionNiveles');
    Route::get('/evaluaciones-institucionales/obtener-datos', [EvaluacionesController::class, 'obtenerDatos'])->name('evaluaciones.obtenerDatos');
    
    Route::post('/evaluaciones-institucionales2/guardar-progreso', [EvaluacionesController::class, 'guardarProgreso2'])->name('evaluaciones2.guardarProgreso');
    Route::get('/evaluaciones-institucionales2/obtener-datos', [EvaluacionesController::class, 'obtenerDatos2'])->name('evaluaciones2.obtenerDatos');
    
    // Resúmenes de Evaluaciones Institucionales
    Route::get('/resumen-evaluaciones-institucionales', [EvaluacionesController::class, 'resumenEvaluaciones1'])->name('resumen-evaluaciones-institucionales');
    Route::get('/resumen-evaluaciones-institucionales2', [EvaluacionesController::class, 'resumenEvaluaciones2'])->name('resumen-evaluaciones-institucionales2');

    // Rutas para Ver Resumen SIN header/footer (layout blank)
    Route::get('/ver-resumen/compromiso1', [CompromiseController::class, 'verResumenCompromiso1'])->name('ver-resumen-compromiso1');
    Route::get('/ver-resumen/compromiso2', [CompromiseController::class, 'verResumenCompromiso2'])->name('ver-resumen-compromiso2');
    Route::get('/ver-resumen/compromiso3', [CompromiseController::class, 'verResumenCompromiso3'])->name('ver-resumen-compromiso3');
    Route::get('/ver-resumen/evaluaciones1', [EvaluacionesController::class, 'verResumenEvaluaciones1'])->name('ver-resumen-evaluaciones1');
    Route::get('/ver-resumen/evaluaciones2', [EvaluacionesController::class, 'verResumenEvaluaciones2'])->name('ver-resumen-evaluaciones2');

    // Nueva Evaluación (limpiar cache y empezar de cero)
    Route::get('/nueva-evaluacion', [CompromiseController::class, 'nuevaEvaluacion'])->name('nueva-evaluacion');

    // Route::get('/compromiso1', [CompromiseController::class, 'compromiso1'])->name('compromiso1'); // Movida a rutas públicas
    Route::post('/compromiso1', [CompromiseController::class, 'store'])->name('compromiso1.store');
    Route::post('/compromiso1/save-progress', [CompromiseController::class, 'saveProgress'])->name('compromiso1.saveProgress');
    // Route::get('/resumen-compromiso1', [CompromiseController::class, 'resumenCompromiso1'])->name('resumen-compromiso1'); // Movida a rutas públicas

    Route::get('/compromiso2', [CompromiseController::class, 'compromiso2'])->name('compromiso2');
    Route::post('/compromiso2', [CompromiseController::class, 'store2'])->name('compromiso2.store');
    Route::post('/compromiso2/save-progress', [CompromiseController::class, 'saveProgress2'])->name('compromiso2.saveProgress');
    Route::get('/resumen-compromiso2', [CompromiseController::class, 'resumenCompromiso2'])->name('resumen-compromiso2');

    Route::get('/compromiso3', [CompromiseController::class, 'compromiso3'])->name('compromiso3');
    Route::post('/compromiso3', [CompromiseController::class, 'store3'])->name('compromiso3.store');
    Route::post('/compromiso3/save-progress', [CompromiseController::class, 'saveProgress3'])->name('compromiso3.saveProgress');
    Route::get('/resumen-compromiso3', [CompromiseController::class, 'resumenCompromiso3'])->name('resumen-compromiso3');

    // Info Institución Routes
    Route::get('/info-institucion', [InfoInstitucionController::class, 'show'])->name('info-institucion');
    Route::post('/info-institucion/procesar', [InfoInstitucionController::class, 'procesarPago'])->name('info-institucion.procesar');
    
    // Registro de Evaluaciones Completadas
    Route::get('/registro-evaluaciones', [RegistroEvaluacionesController::class, 'index'])->name('registro-evaluaciones');
    
    // Reportes (rutas específicas primero)
    Route::get('/reportes/{id}/descargar', [ReportesController::class, 'descargarPDF'])->name('reportes.descargar');
    Route::get('/reportes/{id}/ver', [ReportesController::class, 'verPDF'])->name('reportes.ver');
    Route::post('/reportes/{pago_id}/regenerar', [ReportesController::class, 'regenerar'])->name('reportes.regenerar');
    Route::get('/reportes-graficos/{pagoId}', [ReportesController::class, 'verGraficos'])->name('reportes.graficos');
    Route::get('/hojas-resumen/{userId?}', [ReportesController::class, 'hojasResumen'])->name('hojas-resumen');
    Route::get('/reportes/{userId?}', [ReportesController::class, 'index'])->name('reportes');
    
    // Rutas de Pago
    Route::get('/pago/seleccionar/{pago_id}', [InfoInstitucionController::class, 'seleccionarMetodoPago'])->name('pago.seleccionar');
    Route::post('/pago/guardar-metodo/{pago_id}', [InfoInstitucionController::class, 'guardarMetodoPago'])->name('pago.guardarMetodo');
    Route::get('/pago/{pago_id}', [InfoInstitucionController::class, 'procesarMetodoPago'])->name('pago.metodo');
    Route::post('/pago/{pago_id}/confirmar', [InfoInstitucionController::class, 'confirmarPago'])->name('pago.confirmar');
    
    // API para actualizar estado de orden automáticamente
    Route::get('/api/orden-status', function() {
        $orden = \App\Models\ServicioDiagnostico::where('user_id', \Illuminate\Support\Facades\Auth::id())->first();
        if ($orden) {
            return response()->json([
                'estado' => $orden->estado,
                'pei_generado' => $orden->pei_generado,
                'pat_generado' => $orden->pat_generado,
                'pci_generado' => $orden->pci_generado,
                'ri_generado' => $orden->ri_generado,
            ]);
        }
        return response()->json(['error' => 'No orden found'], 404);
    });
});

// Admin Routes (protected by auth and admin middleware)
Route::prefix('admin')->middleware(['auth', 'admin'])->group(function () {
    Route::get('/', [App\Http\Controllers\Admin\AdminDashboardController::class, 'index'])->name('admin.dashboard');
    Route::get('/dashboard', [App\Http\Controllers\Admin\AdminDashboardController::class, 'index']); // Alias para evitar confusiones
    Route::get('/usuarios', [App\Http\Controllers\Admin\AdminDashboardController::class, 'users'])->name('admin.users.index');
    Route::get('/usuarios/exportar-excel', [App\Http\Controllers\Admin\AdminDashboardController::class, 'exportUsersExcel'])->name('admin.users.export-excel');
    Route::get('/usuarios/{userId}/reportes', [App\Http\Controllers\Admin\AdminDashboardController::class, 'userReports'])->name('admin.users.reports');
    
    // Rutas de Gestión de Personal Administrativo
    Route::get('/personal/crear', [App\Http\Controllers\Admin\AdminDashboardController::class, 'createPersonal'])->name('admin.users.create-personal');
    Route::post('/personal/crear', [App\Http\Controllers\Admin\AdminDashboardController::class, 'storePersonal'])->name('admin.users.store-personal');
    Route::get('/personal/{userId}/editar', [App\Http\Controllers\Admin\AdminDashboardController::class, 'editPersonal'])->name('admin.users.edit-personal');
    Route::post('/personal/{userId}/editar', [App\Http\Controllers\Admin\AdminDashboardController::class, 'updatePersonal'])->name('admin.users.update-personal');
    Route::delete('/personal/{userId}', [App\Http\Controllers\Admin\AdminDashboardController::class, 'deletePersonal'])->name('admin.users.delete-personal');
    
    // Rutas de Órdenes de Servicio
    Route::get('/ordenes', [AdminOrderController::class, 'index'])->name('admin.orders.dashboard');
    Route::get('/ordenes/lista', [AdminOrderController::class, 'listOrders'])->name('admin.orders.list');
    Route::get('/ordenes/{ordenId}', [AdminOrderController::class, 'show'])->name('admin.orders.show');
    Route::post('/ordenes/{ordenId}/estado', [AdminOrderController::class, 'changeStatus'])->name('admin.orders.changeStatus');
    Route::post('/ordenes/{ordenId}/documento', [AdminOrderController::class, 'markDocument'])->name('admin.orders.markDocument');
    Route::post('/ordenes/{ordenId}/nota', [AdminOrderController::class, 'addNote'])->name('admin.orders.addNote');
    // Asignar usuario responsable a la orden
    Route::post('/ordenes/{ordenId}/asignar-trabajador', [AdminOrderController::class, 'assignTrabajador'])->name('admin.orders.assignTrabajador');
});

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