<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\DepartmentController;
use App\Http\Controllers\ConfigurationController;
use App\Http\Controllers\AgentGroupController;

Route::get('/', fn() => redirect('/login'));

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

    // Dashboard
    Route::view('dashboard', 'dashboard')->name('dashboard');

    // Perfil
    Route::get('profile', [\App\Http\Controllers\ProfileController::class, 'edit'])->name('profile');
    Route::patch('profile', [\App\Http\Controllers\ProfileController::class, 'update'])->name('profile.update');
    Route::delete('profile', [\App\Http\Controllers\ProfileController::class, 'destroy'])->name('profile.destroy');

    // Usuarios
    Route::resource('usuarios', UserController::class)->names([
        'index'   => 'usuarios.index',
        'create'  => 'usuarios.create',
        'store'   => 'usuarios.store',
        'show'    => 'usuarios.show',
        'edit'    => 'usuarios.edit',
        'update'  => 'usuarios.update',
        'destroy' => 'usuarios.destroy',
    ])->parameters(['usuarios' => 'user']);
    Route::post('usuarios/{user}/toggle-status', [UserController::class, 'toggleStatus'])->name('usuarios.toggle-status');

    // Departamentos
    Route::resource('departamentos', DepartmentController::class)->names([
        'index'   => 'departamentos.index',
        'create'  => 'departamentos.create',
        'store'   => 'departamentos.store',
        'show'    => 'departamentos.show',
        'edit'    => 'departamentos.edit',
        'update'  => 'departamentos.update',
        'destroy' => 'departamentos.destroy',
    ])->parameters(['departamentos' => 'department']);

    // Grupos de Agentes
    Route::resource('grupos-agentes', AgentGroupController::class)->names([
        'index'   => 'grupos-agentes.index',
        'create'  => 'grupos-agentes.create',
        'store'   => 'grupos-agentes.store',
        'show'    => 'grupos-agentes.show',
        'edit'    => 'grupos-agentes.edit',
        'update'  => 'grupos-agentes.update',
        'destroy' => 'grupos-agentes.destroy',
    ])->parameters(['grupos-agentes' => 'agentGroup']);

    // Configuración del sistema

    // Auditoría
    Route::get('auditoria', function () {
        if (!auth()->user()->hasRole(['admin', 'superadmin'])) abort(403);
        return view('admin.activity-log');
    })->name('auditoria.index');

});

require __DIR__.'/auth.php';

// Logout
Route::post('logout', function() {
    auth()->logout();
    request()->session()->invalidate();
    request()->session()->regenerateToken();
    return redirect('/');
})->middleware('auth')->name('logout');

// ── SPRINT 2: Tickets ─────────────────────────────────────────────────────────
Route::middleware(['auth','verified'])->group(function () {

    // Tickets CRUD
    Route::resource('tickets', \App\Http\Controllers\TicketController::class)->middleware('solo.portal');
    Route::patch('tickets/{ticket}/status',  [\App\Http\Controllers\TicketController::class, 'changeStatus'])->name('tickets.status');
    Route::patch('tickets/{ticket}/assign',  [\App\Http\Controllers\TicketController::class, 'assign'])->name('tickets.assign');
    Route::post('tickets/{ticket}/comment',  [\App\Http\Controllers\TicketController::class, 'addComment'])->name('tickets.comment');
    Route::get('tickets-kanban',             [\App\Http\Controllers\TicketController::class, 'kanban'])->name('tickets.kanban');

    // Parametrización de tickets (admin)
    Route::prefix('admin/tickets')->name('ticket-')->group(function () {
        Route::get('categories',                   [\App\Http\Controllers\TicketCategoryController::class, 'index'])->name('categories.index');
        Route::post('categories',                  [\App\Http\Controllers\TicketCategoryController::class, 'store'])->name('categories.store');
        Route::patch('categories/{ticketCategory}',[\App\Http\Controllers\TicketCategoryController::class, 'update'])->name('categories.update');
        Route::delete('categories/{ticketCategory}',[\App\Http\Controllers\TicketCategoryController::class, 'destroy'])->name('categories.destroy');

        Route::get('priorities',                   [\App\Http\Controllers\TicketPriorityController::class, 'index'])->name('priorities.index');
        Route::post('priorities',                  [\App\Http\Controllers\TicketPriorityController::class, 'store'])->name('priorities.store');
        Route::patch('priorities/{ticketPriority}',[\App\Http\Controllers\TicketPriorityController::class, 'update'])->name('priorities.update');

        Route::get('statuses',                     [\App\Http\Controllers\TicketStatusController::class, 'index'])->name('statuses.index');
        Route::post('statuses',                    [\App\Http\Controllers\TicketStatusController::class, 'store'])->name('statuses.store');
        Route::patch('statuses/{ticketStatus}',    [\App\Http\Controllers\TicketStatusController::class, 'update'])->name('statuses.update');
    });
});

// ── SPRINT 3: Inventario CMDB ─────────────────────────────────────────────────
Route::middleware(['auth','verified'])->group(function () {
    Route::resource('assets', \App\Http\Controllers\AssetController::class);
    Route::post('assets/{asset}/intervention', [\App\Http\Controllers\AssetController::class, 'addIntervention'])
         ->name('assets.intervention');

    // Configuración de activos (admin)
    Route::prefix('admin/assets')->name('asset-')->group(function () {
        Route::get('categories',                     [\App\Http\Controllers\AssetCategoryController::class, 'index'])->name('categories.index');
        Route::post('categories',                    [\App\Http\Controllers\AssetCategoryController::class, 'store'])->name('categories.store');
        Route::patch('categories/{assetCategory}',   [\App\Http\Controllers\AssetCategoryController::class, 'update'])->name('categories.update');
        Route::post('categories/{assetCategory}/fields', [\App\Http\Controllers\AssetCategoryController::class, 'storeField'])->name('categories.field');
    });
});

// ── SPRINT 4: Portal + Notificaciones ────────────────────────────────────────
Route::middleware(['auth','verified'])->group(function () {

    // Dashboard mejorado
    Route::get('/dashboard', [\App\Http\Controllers\DashboardController::class, 'index'])
         ->name('dashboard');

    // Portal self-service
    Route::get('/portal',                  [\App\Http\Controllers\PortalController::class, 'index'])->name('portal.index');
    Route::get('/portal/create',           [\App\Http\Controllers\PortalController::class, 'create'])->name('portal.create');
    Route::post('/portal',                 [\App\Http\Controllers\PortalController::class, 'store'])->name('portal.store');
    Route::get('/portal/{ticket}',         [\App\Http\Controllers\PortalController::class, 'show'])->name('portal.show');
    Route::post('/portal/{ticket}/comment',[\App\Http\Controllers\PortalController::class, 'addComment'])->name('portal.comment');
    Route::post('/portal/{ticket}/satisfaction', [\App\Http\Controllers\PortalController::class, 'satisfaction'])->name('portal.satisfaction');

    // Notificaciones
    Route::get('/notifications', [\App\Http\Controllers\PortalController::class, 'notifications'])->name('notifications.index');
});

// ── SPRINT 5: Reportes ────────────────────────────────────────────────────────
Route::middleware(['auth','verified'])->prefix('reports')->name('reports.')->group(function () {
    Route::get('/',         [\App\Http\Controllers\Reports\ReportController::class, 'index'])->name('index');
    Route::get('/tickets',  [\App\Http\Controllers\Reports\ReportController::class, 'tickets'])->name('tickets');
    Route::get('/sla',      [\App\Http\Controllers\Reports\ReportController::class, 'sla'])->name('sla');
    Route::get('/inventory',[\App\Http\Controllers\Reports\ReportController::class, 'inventory'])->name('inventory');

    // Exportaciones
    Route::get('/export/tickets/csv', [\App\Http\Controllers\Reports\ReportController::class, 'exportTicketsCsv'])->name('export.tickets.csv');
    Route::get('/export/tickets/pdf', [\App\Http\Controllers\Reports\ReportController::class, 'exportTicketsPdf'])->name('export.tickets.pdf');
    Route::get('/export/inventory/csv', [\App\Http\Controllers\Reports\ReportController::class, 'exportInventoryCsv'])->name('export.inventory.csv');
    Route::get('/export/inventory/pdf', [\App\Http\Controllers\Reports\ReportController::class, 'exportInventoryPdf'])->name('export.inventory.pdf');
});

// ── SPRINT 6: Base de Conocimiento ────────────────────────────────────────────
Route::middleware(['auth','verified'])->group(function () {

    // Portal de lectura (todos los usuarios)
    Route::get('/kb',                       [\App\Http\Controllers\KbController::class, 'index'])->name('kb.index');
    Route::get('/kb/suggest',               [\App\Http\Controllers\KbController::class, 'suggest'])->name('kb.suggest');
    Route::get('/kb/category/{slug}',       [\App\Http\Controllers\KbController::class, 'category'])->name('kb.category');
    Route::get('/kb/{slug}',                [\App\Http\Controllers\KbController::class, 'show'])->name('kb.show');
    Route::post('/kb/{article}/vote',       [\App\Http\Controllers\KbController::class, 'vote'])->name('kb.vote');

    // Gestión de artículos (agentes y admins)
    Route::get('/kb-admin',                 [\App\Http\Controllers\KbAdminController::class, 'index'])->name('kb.admin.index');
    Route::get('/kb-admin/create',          [\App\Http\Controllers\KbAdminController::class, 'create'])->name('kb.admin.create');
    Route::post('/kb-admin',                [\App\Http\Controllers\KbAdminController::class, 'store'])->name('kb.admin.store');
    Route::get('/kb-admin/{article}/edit',  [\App\Http\Controllers\KbAdminController::class, 'edit'])->name('kb.admin.edit');
    Route::patch('/kb-admin/{article}',     [\App\Http\Controllers\KbAdminController::class, 'update'])->name('kb.admin.update');
    Route::delete('/kb-admin/{article}',    [\App\Http\Controllers\KbAdminController::class, 'destroy'])->name('kb.admin.destroy');
});

// ── SPRINT 7: Configuración + Automatizaciones ────────────────────────────────
Route::middleware(['auth','verified'])->prefix('admin')->name('admin.')->group(function () {

    // Configuración del sistema
    Route::get('/settings',        [\App\Http\Controllers\Admin\SettingsController::class, 'index'])->name('settings.index');
    Route::patch('/settings',      [\App\Http\Controllers\Admin\SettingsController::class, 'update'])->name('settings.update');
    Route::post('/settings/hours', [\App\Http\Controllers\Admin\SettingsController::class, 'updateHours'])->name('settings.hours');

    // Automatizaciones
    Route::get('/automations',               [\App\Http\Controllers\Admin\AutomationController::class, 'index'])->name('automations.index');
    Route::get('/automations/create',        [\App\Http\Controllers\Admin\AutomationController::class, 'create'])->name('automations.create');
    Route::post('/automations',              [\App\Http\Controllers\Admin\AutomationController::class, 'store'])->name('automations.store');
    Route::get('/automations/{automation}',  [\App\Http\Controllers\Admin\AutomationController::class, 'edit'])->name('automations.edit');
    Route::patch('/automations/{automation}',[\App\Http\Controllers\Admin\AutomationController::class, 'update'])->name('automations.update');
    Route::delete('/automations/{automation}',[\App\Http\Controllers\Admin\AutomationController::class,'destroy'])->name('automations.destroy');
    Route::patch('/automations/{automation}/toggle',[\App\Http\Controllers\Admin\AutomationController::class,'toggle'])->name('automations.toggle');

    // Plantillas de respuesta
    Route::get('/reply-templates',                   [\App\Http\Controllers\Admin\ReplyTemplateController::class, 'index'])->name('reply-templates.index');
    Route::get('/reply-templates/api',               [\App\Http\Controllers\Admin\ReplyTemplateController::class, 'api'])->name('reply-templates.api');
    Route::post('/reply-templates',                  [\App\Http\Controllers\Admin\ReplyTemplateController::class, 'store'])->name('reply-templates.store');
    Route::patch('/reply-templates/{replyTemplate}', [\App\Http\Controllers\Admin\ReplyTemplateController::class, 'update'])->name('reply-templates.update');
    Route::delete('/reply-templates/{replyTemplate}',[\App\Http\Controllers\Admin\ReplyTemplateController::class, 'destroy'])->name('reply-templates.destroy');
});

// API Docs
Route::get('/api/docs', fn() => view('api.docs'))->middleware('auth')->name('api.docs');

// Sprint 9: IA Local
Route::middleware(['auth','verified'])->prefix('ai')->name('ai.')->group(function () {
    Route::get('suggest',               [\App\Http\Controllers\AiController::class, 'suggest'])->name('suggest');
    Route::post('classify/{ticket}',    [\App\Http\Controllers\AiController::class, 'classify'])->name('classify');
    Route::post('feedback/{classification}', [\App\Http\Controllers\AiController::class, 'feedback'])->name('feedback');
    Route::post('retrain',              [\App\Http\Controllers\AiController::class, 'retrain'])->name('retrain');
    Route::get('admin',                 [\App\Http\Controllers\AiController::class, 'admin'])->name('admin');
});

// Sprint 10: IA Fase 3 + 4
Route::middleware(['auth','verified'])->prefix('ai')->name('ai.')->group(function () {
    // Fase 3: Respuestas autónomas
    Route::get('response/{ticket}',            [\App\Http\Controllers\AiResponseController::class, 'generate'])->name('response.generate');
    Route::post('response/{template}/accept',  [\App\Http\Controllers\AiResponseController::class, 'accept'])->name('response.accept');
    // Fase 4: Borradores KB
    Route::get('kb-drafts',                    [\App\Http\Controllers\AiResponseController::class, 'kbDrafts'])->name('kb-drafts');
    Route::get('kb-drafts/{draft}/edit',       [\App\Http\Controllers\AiResponseController::class, 'editDraft'])->name('kb-drafts.edit');
    Route::post('kb-drafts/{draft}/publish',   [\App\Http\Controllers\AiResponseController::class, 'publishDraft'])->name('kb-drafts.publish');
    Route::post('kb-drafts/{draft}/reject',    [\App\Http\Controllers\AiResponseController::class, 'rejectDraft'])->name('kb-drafts.reject');
    // Plantillas
    Route::get('templates',                    [\App\Http\Controllers\AiResponseController::class, 'templates'])->name('templates');
    Route::post('templates',                   [\App\Http\Controllers\AiResponseController::class, 'storeTemplate'])->name('templates.store');
    Route::patch('templates/{template}',       [\App\Http\Controllers\AiResponseController::class, 'updateTemplate'])->name('templates.update');
    Route::delete('templates/{template}',      [\App\Http\Controllers\AiResponseController::class, 'destroyTemplate'])->name('templates.destroy');
});
