<?php
$title = 'Requerimientos - Sistema de Gestión de Proyectos';
$page_title = 'Gestión de Requerimientos';
$current_page = 'requirements';
$showSidebar = true;
$csrf_token = csrf_token();

ob_start();
?>

<div class="mb-6">
    <!-- Header con estadísticas -->
    <div class="bg-gradient-to-r from-blue-600 to-indigo-600 rounded-lg shadow-lg p-6 mb-6 text-white">
        <div class="flex items-center justify-between mb-4">
            <div>
                <h2 class="text-2xl font-bold">Requerimientos</h2>
                <p class="text-blue-100 mt-1">Gestión de tickets y solicitudes del área</p>
            </div>
            <a href="/requirements/create" class="inline-flex items-center px-4 py-2 bg-white text-blue-600 text-sm font-medium rounded-md hover:bg-blue-50">
                <i class="fas fa-plus mr-2"></i>
                Nuevo Requerimiento
            </a>
        </div>

        <!-- Estadísticas -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mt-4">
            <div class="bg-white bg-opacity-20 rounded-lg p-4">
                <div class="flex items-center">
                    <i class="fas fa-clipboard-list text-2xl mr-3"></i>
                    <div>
                        <p class="text-sm opacity-90">Total</p>
                        <p class="text-2xl font-bold"><?= $stats['total'] ?></p>
                    </div>
                </div>
            </div>
            <div class="bg-white bg-opacity-20 rounded-lg p-4">
                <div class="flex items-center">
                    <i class="fas fa-inbox text-2xl mr-3"></i>
                    <div>
                        <p class="text-sm opacity-90">Nuevos</p>
                        <p class="text-2xl font-bold"><?= $stats['new'] ?></p>
                    </div>
                </div>
            </div>
            <div class="bg-white bg-opacity-20 rounded-lg p-4">
                <div class="flex items-center">
                    <i class="fas fa-spinner text-2xl mr-3"></i>
                    <div>
                        <p class="text-sm opacity-90">En Proceso</p>
                        <p class="text-2xl font-bold"><?= $stats['in_progress'] ?></p>
                    </div>
                </div>
            </div>
            <div class="bg-white bg-opacity-20 rounded-lg p-4">
                <div class="flex items-center">
                    <i class="fas fa-check-circle text-2xl mr-3"></i>
                    <div>
                        <p class="text-sm opacity-90">Completados</p>
                        <p class="text-2xl font-bold"><?= $stats['completed'] ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros y búsqueda -->
    <div class="bg-white shadow rounded-lg p-4 mb-6">
        <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Buscar</label>
                <input type="text" name="search" value="<?= htmlspecialchars($filters['search']) ?>" 
                       placeholder="Código, título o descripción..."
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Estado</label>
                <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Todos los estados</option>
                    <option value="new" <?= $filters['status'] == 'new' ? 'selected' : '' ?>>Nuevo</option>
                    <option value="classified" <?= $filters['status'] == 'classified' ? 'selected' : '' ?>>Clasificado</option>
                    <option value="in_analysis" <?= $filters['status'] == 'in_analysis' ? 'selected' : '' ?>>En Análisis</option>
                    <option value="approved" <?= $filters['status'] == 'approved' ? 'selected' : '' ?>>Aprobado</option>
                    <option value="in_development" <?= $filters['status'] == 'in_development' ? 'selected' : '' ?>>En Desarrollo</option>
                    <option value="completed" <?= $filters['status'] == 'completed' ? 'selected' : '' ?>>Completado</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
                <select name="type" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Todos los tipos</option>
                    <option value="incident" <?= $filters['type'] == 'incident' ? 'selected' : '' ?>>Incidente</option>
                    <option value="support" <?= $filters['type'] == 'support' ? 'selected' : '' ?>>Soporte</option>
                    <option value="improvement" <?= $filters['type'] == 'improvement' ? 'selected' : '' ?>>Mejora</option>
                    <option value="project_minor" <?= $filters['type'] == 'project_minor' ? 'selected' : '' ?>>Proyecto Menor</option>
                    <option value="project_major" <?= $filters['type'] == 'project_major' ? 'selected' : '' ?>>Proyecto Mayor</option>
                </select>
            </div>
            <div class="flex items-end">
                <button type="submit" class="w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                    <i class="fas fa-search mr-2"></i>Filtrar
                </button>
            </div>
        </form>
    </div>

    <!-- Tabla de requerimientos -->
    <div class="bg-white shadow rounded-lg overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Código</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Título</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tipo</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Estado</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Prioridad</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Solicitante</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Fecha</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Acciones</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($requirements as $req): ?>
                    <tr class="hover:bg-gray-50 cursor-pointer" onclick="viewRequirementDetails(<?= $req['id'] ?>)">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm font-mono font-medium text-blue-600"><?= htmlspecialchars($req['code']) ?></span>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm font-medium text-gray-900"><?= htmlspecialchars($req['title']) ?></div>
                            <div class="text-sm text-gray-500"><?= htmlspecialchars(substr($req['description'], 0, 60)) ?>...</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php
                            $typeLabels = [
                                'incident' => ['text' => 'Incidente', 'class' => 'bg-red-100 text-red-800'],
                                'support' => ['text' => 'Soporte', 'class' => 'bg-blue-100 text-blue-800'],
                                'improvement' => ['text' => 'Mejora', 'class' => 'bg-green-100 text-green-800'],
                                'project_minor' => ['text' => 'Proyecto Menor', 'class' => 'bg-purple-100 text-purple-800'],
                                'project_major' => ['text' => 'Proyecto Mayor', 'class' => 'bg-indigo-100 text-indigo-800'],
                            ];
                            $type = $typeLabels[$req['type']] ?? ['text' => $req['type'], 'class' => 'bg-gray-100 text-gray-800'];
                            ?>
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?= $type['class'] ?>">
                                <?= $type['text'] ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php
                            $statusLabels = [
                                'new' => ['text' => 'Nuevo', 'class' => 'bg-yellow-100 text-yellow-800'],
                                'classified' => ['text' => 'Clasificado', 'class' => 'bg-blue-100 text-blue-800'],
                                'in_analysis' => ['text' => 'En Análisis', 'class' => 'bg-orange-100 text-orange-800'],
                                'approved' => ['text' => 'Aprobado', 'class' => 'bg-green-100 text-green-800'],
                                'in_development' => ['text' => 'En Desarrollo', 'class' => 'bg-purple-100 text-purple-800'],
                                'completed' => ['text' => 'Completado', 'class' => 'bg-gray-100 text-gray-800'],
                            ];
                            $status = $statusLabels[$req['status']] ?? ['text' => $req['status'], 'class' => 'bg-gray-100 text-gray-800'];
                            ?>
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?= $status['class'] ?>">
                                <?= $status['text'] ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php
                            $priorityLabels = [
                                'low' => ['text' => 'Baja', 'icon' => 'fa-arrow-down', 'class' => 'text-gray-600'],
                                'medium' => ['text' => 'Media', 'icon' => 'fa-minus', 'class' => 'text-blue-600'],
                                'high' => ['text' => 'Alta', 'icon' => 'fa-arrow-up', 'class' => 'text-orange-600'],
                                'critical' => ['text' => 'Crítica', 'icon' => 'fa-exclamation-triangle', 'class' => 'text-red-600'],
                            ];
                            $priority = $priorityLabels[$req['priority']] ?? ['text' => $req['priority'], 'icon' => 'fa-circle', 'class' => 'text-gray-600'];
                            ?>
                            <span class="text-sm <?= $priority['class'] ?>">
                                <i class="fas <?= $priority['icon'] ?> mr-1"></i><?= $priority['text'] ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <?= htmlspecialchars($req['requester_name']) ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <?= date('d/m/Y', strtotime($req['created_at'])) ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <a href="/requirements/view/<?= $req['id'] ?>" class="text-blue-600 hover:text-blue-900" onclick="event.stopPropagation()">
                                <i class="fas fa-eye"></i> Ver
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>

                    <?php if (empty($requirements)): ?>
                    <tr>
                        <td colspan="8" class="px-6 py-12 text-center text-gray-500">
                            <i class="fas fa-inbox text-4xl mb-4 text-gray-300"></i>
                            <p class="text-lg">No hay requerimientos que mostrar</p>
                            <p class="text-sm mt-2">Ajusta los filtros o crea un nuevo requerimiento</p>
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Paginación -->
        <?php if ($totalPages > 1): ?>
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
            <div class="flex-1 flex justify-between sm:hidden">
                <?php if ($page > 1): ?>
                <a href="?page=<?= $page - 1 ?>&<?= http_build_query($filters) ?>" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">Anterior</a>
                <?php endif; ?>
                <?php if ($page < $totalPages): ?>
                <a href="?page=<?= $page + 1 ?>&<?= http_build_query($filters) ?>" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">Siguiente</a>
                <?php endif; ?>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        Mostrando página <span class="font-medium"><?= $page ?></span> de <span class="font-medium"><?= $totalPages ?></span>
                        <span class="text-gray-500">(<?= $total ?> total)</span>
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                        <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <a href="?page=<?= $i ?>&<?= http_build_query($filters) ?>" 
                           class="relative inline-flex items-center px-4 py-2 border text-sm font-medium <?= $i == $page ? 'z-10 bg-blue-50 border-blue-500 text-blue-600' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50' ?>">
                            <?= $i ?>
                        </a>
                        <?php endfor; ?>
                    </nav>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modal: Ver Detalles del Requerimiento -->
<div id="requirementDetailsModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
    <div class="relative top-10 mx-auto p-6 border w-full max-w-4xl shadow-lg rounded-md bg-white">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-semibold text-gray-900" id="modalReqTitle">Detalles del Requerimiento</h3>
            <button onclick="closeRequirementDetailsModal()" class="text-gray-400 hover:text-gray-500">
                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>

        <div id="requirementDetailsContent" class="space-y-4">
            <!-- Se llenará dinámicamente -->
        </div>

        <div class="flex justify-between gap-3 pt-4 mt-4 border-t">
            <button type="button" onclick="closeRequirementDetailsModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                Cerrar
            </button>
            <a id="modalViewFullBtn" href="#" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700">
                Ver Completo
            </a>
        </div>
    </div>
</div>

<script>
const allRequirements = <?= json_encode($requirements) ?>;

function viewRequirementDetails(reqId) {
    const req = allRequirements.find(r => r.id == reqId);
    if (!req) return;
    
    const typeLabels = {
        'incident': 'Incidente',
        'support': 'Soporte',
        'improvement': 'Mejora',
        'project_minor': 'Proyecto Menor',
        'project_major': 'Proyecto Mayor'
    };
    
    const statusLabels = {
        'new': 'Nuevo',
        'in_analysis': 'En Análisis',
        'approved': 'Aprobado',
        'in_progress': 'En Progreso',
        'on_hold': 'En Espera',
        'completed': 'Completado',
        'rejected': 'Rechazado'
    };
    
    const priorityLabels = {
        'low': 'Baja',
        'medium': 'Media',
        'high': 'Alta',
        'critical': 'Crítica'
    };
    
    document.getElementById('modalReqTitle').textContent = req.code + ' - ' + req.title;
    document.getElementById('modalViewFullBtn').href = '/requirements/view/' + req.id;
    
    const content = `
        <div class="grid grid-cols-3 gap-4 mb-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
                <span class="text-sm text-gray-900">${typeLabels[req.type] || req.type}</span>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Estado</label>
                <span class="text-sm text-gray-900">${statusLabels[req.status]}</span>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Prioridad</label>
                <span class="text-sm text-gray-900">${priorityLabels[req.priority]}</span>
            </div>
        </div>
        
        <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">Descripción</label>
            <p class="text-sm text-gray-900 whitespace-pre-wrap">${req.description}</p>
        </div>
        
        <div class="grid grid-cols-2 gap-4 mb-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Solicitante</label>
                <span class="text-sm text-gray-900">${req.requester_name}</span>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Área</label>
                <span class="text-sm text-gray-900">${req.department || 'No especificado'}</span>
            </div>
            ${req.assigned_team_name ? `
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Equipo Asignado</label>
                <span class="text-sm text-gray-900">${req.assigned_team_name}</span>
            </div>
            ` : ''}
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Fecha Creación</label>
                <span class="text-sm text-gray-900">${new Date(req.created_at).toLocaleDateString('es-PE')}</span>
            </div>
        </div>
        
        ${req.business_justification ? `
        <div class="mb-4 bg-blue-50 p-4 rounded">
            <label class="block text-sm font-medium text-blue-900 mb-2">💼 Justificación de Negocio</label>
            <p class="text-sm text-blue-800 whitespace-pre-wrap">${req.business_justification}</p>
        </div>
        ` : ''}
        
        ${req.expected_benefit ? `
        <div class="mb-4 bg-green-50 p-4 rounded">
            <label class="block text-sm font-medium text-green-900 mb-2">✓ Beneficio Esperado</label>
            <p class="text-sm text-green-800 whitespace-pre-wrap">${req.expected_benefit}</p>
        </div>
        ` : ''}
    `;
    
    document.getElementById('requirementDetailsContent').innerHTML = content;
    document.getElementById('requirementDetailsModal').classList.remove('hidden');
}

function closeRequirementDetailsModal() {
    document.getElementById('requirementDetailsModal').classList.add('hidden');
}
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/../layouts/app.php';
?>
