<?php
require_once __DIR__ . '/../src/bootstrap.php';

use App\Controllers\AuthController;
use App\Controllers\DashboardController;
use App\Controllers\AdminController;
use App\Controllers\SettingsController;
use App\Controllers\ApiController;
use App\Controllers\RequirementsController;
use App\Controllers\ProjectsController;
use App\Controllers\BacklogController;
use App\Controllers\TasksController;
use App\Controllers\ReportsController;
use App\Controllers\DocumentsController;
use App\Middleware\AuthMiddleware;

// Inicializar middleware
$auth = new AuthMiddleware();

// Obtener la ruta actual y método HTTP
$request_uri = $_SERVER['REQUEST_URI'];
$path = parse_url($request_uri, PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];

// Remover el slash final si existe
$path = rtrim($path, '/');
if (empty($path)) {
    $path = '/';
}

// Router simple con soporte para métodos HTTP
try {
    $route = $method . ' ' . $path;
    
    // Rutas con parámetros dinámicos
    if (preg_match('#^GET /requirements/view/(\d+)$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new RequirementsController();
        $controller->view($matches[1]);
        exit;
    }
    
    if (preg_match('#^GET /requirements/download/(\d+)$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new RequirementsController();
        $controller->download($matches[1]);
        exit;
    }

    if (preg_match('#^GET /requirements/(\d+)$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new RequirementsController();
        $controller->view($matches[1]);
        exit;
    }

    if (preg_match('#^GET /projects/(\d+)$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new ProjectsController();
        $controller->view($matches[1]);
        exit;
    }

    if (preg_match('#^GET /backlog/(\d+)$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new BacklogController();
        $controller->index($matches[1]);
        exit;
    }

    if (preg_match('#^GET /sprints/(\d+)$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new BacklogController();
        $controller->viewSprint($matches[1]);
        exit;
    }

    if (preg_match('#^POST /backlog/items/(\d+)/update$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new BacklogController();
        $controller->updateItem($matches[1]);
        exit;
    }

    if (preg_match('#^POST /backlog/items/(\d+)/delete$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new BacklogController();
        $controller->deleteItem($matches[1]);
        exit;
    }

    if (preg_match('#^POST /sprints/(\d+)/update$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new BacklogController();
        $controller->updateSprint($matches[1]);
        exit;
    }

    if (preg_match('#^POST /projects/(\d+)/update$#', $route, $matches)) {
        $auth->requireRole();
        $controller = new ProjectsController();
        $controller->update($matches[1]);
        exit;
    }

    if (preg_match('#^POST /projects/(\d+)/delete$#', $route, $matches)) {
        $auth->requireAdmin();
        $controller = new ProjectsController();
        $controller->delete($matches[1]);
        exit;
    }
    
    switch ($route) {
        // === RUTAS PÚBLICAS ===
        case 'GET /':
        case 'GET /login':
            $controller = new AuthController();
            $controller->showLogin();
            break;

        case 'POST /auth/login':
            $controller = new AuthController();
            $controller->login();
            break;

        case 'GET /auth/keycloak':
            $controller = new AuthController();
            $controller->redirectToKeycloak();
            break;

        case 'GET /auth/callback':
            $controller = new AuthController();
            $controller->handleCallback();
            break;

        case 'GET /logout':
        case 'GET /auth/logout':
        case 'POST /auth/logout':
            $controller = new AuthController();
            $controller->logout();
            break;

        // === APIS ===
        case 'POST /api/extend-session':
            $controller = new ApiController();
            $controller->extendSession();
            break;

        case 'GET /api/session-status':
            $controller = new ApiController();
            $controller->sessionStatus();
            break;

        case 'GET /api/dashboard-stats':
            $controller = new ApiController();
            $controller->dashboardStats();
            break;

        case 'GET /api/search-users':
            $controller = new ApiController();
            $controller->searchUsers();
            break;

        case 'GET /api/notifications':
            $controller = new ApiController();
            $controller->getNotifications();
            break;

        case 'POST /api/notifications/read':
            $controller = new ApiController();
            $controller->markNotificationRead();
            break;

        case 'GET /api/user/current':
            $auth->requireRole();
            $controller = new AuthController();
            $controller->getCurrentUserInfo();
            break;

        // === RUTAS CON AUTENTICACIÓN PERO SIN ROL ===
        case 'GET /pending':
            $controller = new AuthController();
            $controller->showPending();
            break;

        case 'GET /auth/check-role-status':
            header('Content-Type: application/json');
            $auth->requireAuth();
            $controller = new AuthController();
            $controller->checkRoleStatus();
            break;

        // === RUTAS AUXILIARES ===
        case 'GET /redirect-dashboard':
            if (!$auth->isAuthenticated()) {
                header('Location: /login');
                exit;
            }
            if (!$auth->hasRole()) {
                header('Location: /pending');
                exit;
            }
            header('Location: /dashboard');
            exit;

        case 'GET /debug-auth-state':
            if (!($_ENV['APP_DEBUG'] ?? false)) {
                http_response_code(404);
                exit;
            }
            
            header('Content-Type: application/json');
            echo json_encode([
                'is_authenticated' => $auth->isAuthenticated(),
                'has_role' => $auth->hasRole(),
                'is_admin' => $auth->isAdmin(),
                'session_user' => $_SESSION['user'] ?? null,
                'session_id' => session_id(),
                'timestamp' => time()
            ]);
            exit;

        // === RUTAS QUE REQUIEREN ROL ASIGNADO ===
        case 'GET /dashboard':
            $auth->requireRole();
            $controller = new DashboardController();
            $controller->index();
            break;

        case 'GET /profile':
            $auth->requireRole();
            $controller = new DashboardController();
            $controller->profile();
            break;

        case 'POST /profile/update':
            $auth->requireRole();
            $controller = new DashboardController();
            $controller->updateProfile();
            break;

        // === RUTAS DE ADMINISTRACIÓN ===
        case 'GET /admin':
        case 'GET /admin/dashboard':
            $auth->requireAdmin();
            $controller = new AdminController();
            $controller->dashboard();
            break;

        case 'GET /admin/users':
            $auth->requireAdmin();
            $controller = new AdminController();
            $controller->users();
            break;

        case 'POST /admin/users':
            $auth->requireAdmin();
            $controller = new AdminController();
            $controller->users();
            break;

        case 'GET /admin/roles':
            $auth->requireAdmin();
            $controller = new AdminController();
            $controller->roles();
            break;

        case 'POST /admin/roles':
            $auth->requireAdmin();
            $controller = new AdminController();
            $controller->roles();
            break;

        case 'GET /admin/teams':
            $auth->requireAdmin();
            $controller = new AdminController();
            $controller->teams();
            break;

        case 'POST /admin/teams':
            $auth->requireAdmin();
            $controller = new AdminController();
            $controller->teams();
            break;

        case 'GET /settings':
        case 'GET /admin/settings':
            $auth->requireAdmin();
            $controller = new SettingsController();
            $controller->index();
            break;

        case 'POST /settings':
        case 'POST /admin/settings':
            $auth->requireAdmin();
            $controller = new SettingsController();
            $controller->index();
            break;

        // === RUTAS DE REQUERIMIENTOS ===
        case 'GET /requirements':
            $auth->requireRole();
            $controller = new RequirementsController();
            $controller->index();
            break;

        case 'GET /requirements/create':
            $auth->requireRole();
            $controller = new RequirementsController();
            $controller->create();
            break;

        case 'POST /requirements/create':
            $auth->requireRole();
            $controller = new RequirementsController();
            $controller->create();
            break;

        case 'POST /requirements':
            $auth->requireRole();
            $controller = new RequirementsController();
            $controller->handleAction();
            break;

        // === RUTAS DE PROYECTOS ===
        case 'GET /projects':
            $auth->requireRole();
            $controller = new ProjectsController();
            $controller->index();
            break;

        case 'GET /projects/create':
            $auth->requireRole();
            $controller = new ProjectsController();
            $controller->create();
            break;

        case 'POST /projects/store':
            $auth->requireRole();
            $controller = new ProjectsController();
            $controller->store();
            break;

        // === RUTAS DE BACKLOG / SPRINTS ===
        case 'POST /backlog/items/create':
            $auth->requireRole();
            $controller = new BacklogController();
            $controller->createItem();
            break;

        case 'POST /backlog/sprints/create':
            $auth->requireRole();
            $controller = new BacklogController();
            $controller->createSprint();
            break;

        case 'GET /backlog/stats':
            $auth->requireRole();
            if (!empty($_GET['project_id'])) {
                $controller = new BacklogController();
                $controller->getStats($_GET['project_id']);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'project_id required']);
            }
            break;

        case 'GET /sprints/burndown':
            $auth->requireRole();
            if (!empty($_GET['sprint_id'])) {
                $controller = new BacklogController();
                $controller->getBurndownData($_GET['sprint_id']);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'sprint_id required']);
            }
            break;

        // === RUTAS DE TAREAS ===
        case 'POST /tasks/create':
            $auth->requireRole();
            $controller = new TasksController();
            $controller->create();
            break;

        case 'POST /tasks/update':
            $auth->requireRole();
            if (!empty($_POST['task_id'])) {
                $controller = new TasksController();
                $controller->update($_POST['task_id']);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'task_id required']);
            }
            break;

        case 'POST /tasks/delete':
            $auth->requireRole();
            if (!empty($_POST['task_id'])) {
                $controller = new TasksController();
                $controller->delete($_POST['task_id']);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'task_id required']);
            }
            break;

        case 'GET /tasks/list':
            $auth->requireRole();
            if (!empty($_GET['backlog_item_id'])) {
                $controller = new TasksController();
                $controller->getTasks($_GET['backlog_item_id']);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'backlog_item_id required']);
            }
            break;

        // === RUTAS DE REPORTES ===
        case 'GET /reports':
            $auth->requireRole();
            $controller = new ReportsController();
            $controller->index();
            break;

        case 'GET /reports/metrics':
            $auth->requireRole();
            $controller = new ReportsController();
            $controller->getMetrics();
            break;

        case 'GET /reports/charts':
            $auth->requireRole();
            $controller = new ReportsController();
            $controller->getChartData();
            break;

        // === RUTAS DE DOCUMENTOS ===
        case 'POST /documents/upload':
            $auth->requireRole();
            $controller = new DocumentsController();
            $controller->upload();
            break;

        case 'POST /documents/review':
            $auth->requireRole(['admin', 'quality']);
            $controller = new DocumentsController();
            $controller->review();
            break;

        case 'POST /documents/delete':
            $auth->requireRole(['admin']);
            if (!empty($_POST['document_id'])) {
                $controller = new DocumentsController();
                $controller->delete($_POST['document_id']);
            }
            break;

        case 'GET /documents/list':
            $auth->requireRole();
            $controller = new DocumentsController();
            $controller->list();
            break;

        // === 404 - PÁGINA NO ENCONTRADA ===
        default:
            // Ruta dinámica para descargar documentos: GET /documents/download/{id}
            if (preg_match('#^GET /documents/download/(\d+)$#', $route, $matches)) {
                $auth->requireRole();
                $controller = new DocumentsController();
                $controller->download($matches[1]);
                exit;
            }

            http_response_code(404);
            include __DIR__ . '/../views/errors/404.php';
            break;
    }

} catch (Exception $e) {
    error_log('Router Error: ' . $e->getMessage());
    
    if ($_ENV['APP_DEBUG'] ?? false) {
        echo "<h1>Error del Sistema</h1>";
        echo "<pre>" . $e->getMessage() . "</pre>";
        echo "<pre>" . $e->getTraceAsString() . "</pre>";
    } else {
        http_response_code(500);
        include __DIR__ . '/../views/errors/500.php';
    }
}