<?php
/**
 * URL Router - Maneja URLs amigables no cubiertas por las reglas específicas de .htaccess
 */

// Iniciar sesión si no está iniciada
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once 'includes/db.php';
require_once 'includes/helpers.php';

// Verificar autenticación
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Obtener la URL solicitada
$url = isset($_GET['url']) ? trim($_GET['url'], '/') : '';
$url_parts = explode('/', $url);
$section = $url_parts[0] ?? '';
$action = $url_parts[1] ?? '';
$id = $url_parts[2] ?? '';

// Handle special case for job-applications with ID
if ($section === 'admin' && $action === 'job-applications' && is_numeric($id)) {
    $_GET['id'] = $id;
    $file_url = 'admin/job-applications';
} elseif ($section === 'admin' && $action === 'students' && is_numeric($id)) {
    // Handle admin/students/{id} routes
    $_GET['id'] = $id;
    $file_url = 'admin/students';
} elseif ($section === 'admin' && $action === 'students' && $id === 'edit' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/students/edit/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/edit-student';
} elseif ($section === 'admin' && $action === 'delete' && is_numeric($id)) {
    // Handle admin/delete/{id} routes
    $_GET['id'] = $id;
    $file_url = 'admin/delete-student';
} elseif ($section === 'admin' && $action === 'students' && $id === 'delete' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/students/delete/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/delete-student';
} elseif ($section === 'admin' && $action === 'students' && $id === 'delete' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/students/delete/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/delete-student';
} elseif ($section === 'admin' && $action === 'students' && $id === 'view' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/students/view/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/view-student';
} elseif ($section === 'admin' && $action === 'graduates' && $id === 'view' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/graduates/view/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/view-graduate';
} elseif ($section === 'admin' && $action === 'graduates' && $id === 'edit' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/graduates/edit/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/edit-graduate';
} elseif ($section === 'admin' && $action === 'graduates' && $id === 'delete' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/graduates/delete/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/delete-graduate';
} elseif ($section === 'admin' && $action === 'teachers' && $id === 'edit' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/teachers/edit/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/edit-teacher';
} elseif ($section === 'admin' && $action === 'teachers' && $id === 'view' && is_numeric($url_parts[3] ?? '')) {
    // Handle admin/teachers/view/{id} routes
    $_GET['id'] = $url_parts[3];
    $file_url = 'admin/view-teacher';
} elseif ($section === 'admin' && $action === 'teachers' && $id === 'delete' && is_numeric($url_parts[3] ?? '')) {
     // Handle admin/teachers/delete/{id} routes
     $_GET['id'] = $url_parts[3];
     $file_url = 'admin/delete-teacher';
 } elseif ($section === 'admin' && $action === 'companies' && $id === 'view' && is_numeric($url_parts[3] ?? '')) {
     // Handle admin/companies/view/{id} routes
     $_GET['id'] = $url_parts[3];
     $file_url = 'admin/view-company';
 } elseif ($section === 'admin' && $action === 'companies' && $id === 'edit' && is_numeric($url_parts[3] ?? '')) {
     // Handle admin/companies/edit/{id} routes
     $_GET['id'] = $url_parts[3];
     $file_url = 'admin/edit-company';
 } elseif ($section === 'admin' && $action === 'companies' && $id === 'edit') {
     // Invalid edit ID, redirect to login
     header('Location: login.php');
     exit;
 } elseif ($section === 'admin' && $action === 'companies' && $id === 'delete' && is_numeric($url_parts[3] ?? '')) {
     // Handle admin/companies/delete/{id} routes
     $_GET['id'] = $url_parts[3];
     $file_url = 'admin/delete-company';
 } elseif ($section === 'admin' && $action === 'companies' && $id === 'delete') {
     // Invalid delete ID, redirect to login
     header('Location: login.php');
     exit;
 } elseif ($section === 'teacher' && $action === 'job-detail' && is_numeric($id)) {
     $_GET['id'] = $id;
     $file_url = 'teacher/job-detail';
 } elseif ($section === 'teacher' && $action === 'job-applications' && is_numeric($id)) {
     $_GET['id'] = $id;
     $file_url = 'teacher/job-applications';
 } elseif ($section === 'teacher' && $action === 'resume' && is_numeric($id)) {
     $_GET['id'] = $id;
     $file_url = 'teacher/resume';
 } elseif ($section === 'teacher' && $action === 'resume' && is_numeric($id)) {
     $_GET['id'] = $id;
     // Preserve additional query parameters like 'download'
     $query_string = $_SERVER['QUERY_STRING'] ?? '';
     if ($query_string) {
         parse_str($query_string, $query_params);
         foreach ($query_params as $key => $value) {
             if ($key !== 'url' && $key !== 'id') { // Skip the 'url' parameter used by the router and 'id' which is already set
                 $_GET[$key] = $value;
             }
         }
     }
     $file_url = 'teacher/resume';
 } elseif ($section === 'admin' && $action === 'students' && $id === 'edit' && is_numeric($url_parts[3] ?? '')) {
     // Handle admin/students/edit/{id} routes
     $_GET['id'] = $url_parts[3];
     $file_url = 'admin/edit-student';
} else {
    // Si la última parte de la URL es numérica, asumimos que es un ID
    // y la URL base para encontrar el archivo no la incluye.
    $file_url = $url;
    if (is_numeric($action) || is_numeric($id)) {
        $file_url = $section . (is_numeric($action) ? '' : '/' . $action);
        // Set the ID parameter if it's numeric
        if (is_numeric($action)) {
            $_GET['id'] = $action;
        } elseif (is_numeric($id)) {
            $_GET['id'] = $id;
        }
    }
}

// Mapeo de rutas especiales que no siguen el patrón {seccion}/{accion}.php
$special_routes = [
    'login' => 'login.php',
    'logout' => 'logout.php',
    'register' => 'register.php',
    'admin/jobs/new' => 'admin/post-job.php',
    'admin/users/new' => 'admin/add-user.php',
    'admin/students/new' => 'admin/add-student.php',
    'admin/graduates/new' => 'admin/add-graduate.php',
    'admin/teachers/new' => 'admin/add-teacher.php',
    'admin/companies/new' => 'admin/add-company.php',
    'admin/notifications/send' => 'admin/send-notification.php',
    'admin/reports' => 'admin/custom-reports.php',
    'admin/settings' => 'admin/institution-settings.php',
    'admin/auto-update-job-status' => 'admin/auto_update_job_status.php',
    'admin/export-jobs' => 'admin/export-jobs.php',
    'admin/upload-students' => 'admin/upload-students.php',
    'admin/toggle-graduate-status' => 'admin/toggle-graduate-status.php',
    'company/jobs/new' => 'company/post-job.php',
    'admin/job-applications' => 'admin/job-applications.php',
    'student/languages' => 'student/languages.php',
    'student/experience' => 'student/work-experience.php',
    'student/view-job' => 'student/view-job.php'
];

// Construir la ruta al archivo PHP.
$file_path = __DIR__ . '/' . $file_url . '.php';

// Verificar si el archivo existe
if (file_exists($file_path)) {
    // Verificar permisos de rol
    $role_map = [
        'admin'     => 'administrador',
        'company'   => 'empresa',
        'student'   => 'alumno',
        'graduate'  => 'egresado',
        'teacher'   => 'profesor'
    ];
    $required_role = $role_map[$section] ?? null;

    if ($required_role && $_SESSION['role'] !== $required_role) {
        // Si el rol no coincide, redirigir al index (que a su vez redirige al dashboard correcto)
        header('Location: ' . url('/'));
        exit;
    }
    
    include $file_path;
} elseif (isset($special_routes[$url]) && file_exists(__DIR__ . '/' . $special_routes[$url])) {
    // Incluir archivo de ruta especial
    include __DIR__ . '/' . $special_routes[$url];
} else {
    // Si el archivo no existe, mostrar un 404 o redirigir
    http_response_code(404);
    echo "<h1>404 No Encontrado</h1>";
    echo "La página que solicitaste en '$url' no fue encontrada.";
    // Opcionalmente, redirigir a una página de error
    // header('Location: /error404.php');
}

exit;
?>