<?php
$title = 'Requerimiento ' . htmlspecialchars($requirement['code']) . ' - Sistema de Gestión de Proyectos';
$page_title = 'Detalle de Requerimiento';
$current_page = 'requirements';
$showSidebar = true;
$csrf_token = csrf_token();

ob_start();
?>

<div class="max-w-7xl mx-auto">
    <!-- Mensajes de éxito/error -->
    <?php if (isset($_GET['success'])): ?>
    <div class="mb-4 p-4 bg-green-50 border border-green-200 text-green-800 rounded-lg">
        <i class="fas fa-check-circle mr-2"></i><?= htmlspecialchars($_GET['success']) ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['error'])): ?>
    <div class="mb-4 p-4 bg-red-50 border border-red-200 text-red-800 rounded-lg">
        <i class="fas fa-exclamation-circle mr-2"></i><?= htmlspecialchars($_GET['error']) ?>
    </div>
    <?php endif; ?>

    <!-- Header -->
    <div class="mb-6">
        <a href="/requirements" class="text-blue-600 hover:text-blue-800 text-sm mb-2 inline-flex items-center">
            <i class="fas fa-arrow-left mr-2"></i>Volver a Requerimientos
        </a>
        <div class="flex items-center justify-between mt-2">
            <div>
                <h2 class="text-2xl font-bold text-gray-900"><?= htmlspecialchars($requirement['title']) ?></h2>
                <p class="text-gray-600 mt-1">Código: <span class="font-mono font-medium"><?= htmlspecialchars($requirement['code']) ?></span></p>
            </div>
            <div class="flex space-x-2">
                <?php if ($canEdit): ?>
                <button onclick="showChangeStatusModal()" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                    <i class="fas fa-exchange-alt mr-2"></i>Cambiar Estado
                </button>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Columna Principal -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Información Principal -->
            <div class="bg-white shadow rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Descripción</h3>
                <div class="prose max-w-none text-gray-700">
                    <?= nl2br(htmlspecialchars($requirement['description'])) ?>
                </div>

                <?php if (!empty($requirement['expected_impact'])): ?>
                <div class="mt-6">
                    <h4 class="font-medium text-gray-900 mb-2">Impacto Esperado</h4>
                    <p class="text-gray-700"><?= nl2br(htmlspecialchars($requirement['expected_impact'])) ?></p>
                </div>
                <?php endif; ?>
            </div>

            <!-- Archivos Adjuntos -->
            <?php if (!empty($attachments)): ?>
            <div class="bg-white shadow rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Archivos Adjuntos</h3>
                <div class="space-y-2">
                    <?php foreach ($attachments as $file): ?>
                    <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100">
                        <div class="flex items-center">
                            <i class="fas fa-file text-blue-600 text-xl mr-3"></i>
                            <div>
                                <p class="text-sm font-medium text-gray-900"><?= htmlspecialchars($file['file_original_name']) ?></p>
                                <p class="text-xs text-gray-500">
                                    <?= number_format($file['file_size'] / 1024, 2) ?> KB • 
                                    <?= date('d/m/Y H:i', strtotime($file['created_at'])) ?>
                                </p>
                            </div>
                        </div>
                        <a href="/requirements/download/<?= $file['id'] ?>" class="text-blue-600 hover:text-blue-800">
                            <i class="fas fa-download"></i>
                        </a>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Documentos de Proceso (AS-IS/TO-BE) -->
            <div class="bg-white shadow rounded-lg p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">
                        <i class="fas fa-file-alt text-blue-600 mr-2"></i>
                        Documentos de Proceso
                    </h3>
                    <?php if ($canEdit && in_array($requirement['status'], ['classified', 'in_analysis', 'approved'])): ?>
                    <button onclick="showUploadDocumentModal()" class="px-3 py-2 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700">
                        <i class="fas fa-upload mr-1"></i>Subir Documento
                    </button>
                    <?php endif; ?>
                </div>

                <div id="documentsList" class="space-y-3">
                    <div class="text-center text-gray-500 py-8">
                        <i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
                        <p>Cargando documentos...</p>
                    </div>
                </div>
            </div>

            <!-- Comentarios -->
            <div class="bg-white shadow rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Comentarios</h3>

                <!-- Lista de comentarios -->
                <div class="space-y-4 mb-6">
                    <?php foreach ($comments as $comment): ?>
                    <div class="border-l-4 <?= $comment['is_internal'] ? 'border-yellow-400 bg-yellow-50' : 'border-blue-400 bg-gray-50' ?> p-4 rounded">
                        <div class="flex items-start justify-between mb-2">
                            <div class="flex items-center">
                                <div class="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold mr-3">
                                    <?= strtoupper(substr($comment['user_name'], 0, 1)) ?>
                                </div>
                                <div>
                                    <p class="font-medium text-gray-900"><?= htmlspecialchars($comment['user_name']) ?></p>
                                    <p class="text-xs text-gray-500"><?= date('d/m/Y H:i', strtotime($comment['created_at'])) ?></p>
                                </div>
                            </div>
                            <?php if ($comment['is_internal']): ?>
                            <span class="px-2 py-1 bg-yellow-100 text-yellow-800 text-xs font-semibold rounded">
                                <i class="fas fa-lock mr-1"></i>Interno
                            </span>
                            <?php endif; ?>
                        </div>
                        <p class="text-gray-700 ml-11"><?= nl2br(htmlspecialchars($comment['comment'])) ?></p>
                    </div>
                    <?php endforeach; ?>

                    <?php if (empty($comments)): ?>
                    <p class="text-center text-gray-500 py-8">No hay comentarios aún</p>
                    <?php endif; ?>
                </div>

                <!-- Formulario nuevo comentario -->
                <form action="/requirements" method="POST" class="border-t pt-4">
                    <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                    <input type="hidden" name="action" value="add_comment">
                    <input type="hidden" name="requirement_id" value="<?= $requirement['id'] ?>">
                    
                    <textarea name="comment" rows="3" required
                              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                              placeholder="Escribe un comentario..."></textarea>
                    
                    <div class="flex items-center justify-between mt-2">
                        <?php if ($isAdmin): ?>
                        <label class="flex items-center text-sm text-gray-700">
                            <input type="checkbox" name="is_internal" value="1" class="mr-2 rounded">
                            Comentario interno (solo visible para equipo TI)
                        </label>
                        <?php else: ?>
                        <span></span>
                        <?php endif; ?>
                        
                        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                            <i class="fas fa-comment mr-2"></i>Comentar
                        </button>
                    </div>
                </form>
            </div>

            <!-- Backlog Items Asociados -->
            <?php if ($requirement['project_id']): ?>
            <div class="bg-white shadow rounded-lg p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">Items de Backlog</h3>
                    <?php if (in_array($requirement['status'], ['approved', 'in_development', 'in_testing'])): ?>
                    <button onclick="showCreateBacklogItemModal()" class="px-3 py-1 bg-green-600 text-white text-sm rounded-md hover:bg-green-700">
                        <i class="fas fa-plus mr-1"></i>Crear Item
                    </button>
                    <?php endif; ?>
                </div>

                <?php if (empty($backlogItems)): ?>
                    <div class="text-center text-gray-500 py-8">
                        <i class="fas fa-list-ul text-4xl mb-3 text-gray-300"></i>
                        <p>No hay items de backlog asociados a este requerimiento</p>
                        <?php if (in_array($requirement['status'], ['approved', 'in_development', 'in_testing'])): ?>
                        <p class="text-sm mt-1">Crea un item para iniciar el desarrollo</p>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <!-- Resumen de Trazabilidad -->
                    <?php 
                    $totalTasks = array_sum(array_column($backlogItems, 'tasks_count'));
                    $completedTasks = array_sum(array_column($backlogItems, 'tasks_completed'));
                    $projectInfo = !empty($backlogItems[0]['project_code']) ? $backlogItems[0] : null;
                    ?>
                    
                    <?php if ($projectInfo): ?>
                    <div class="mb-4 p-4 bg-gradient-to-r from-blue-50 to-purple-50 border border-blue-200 rounded-lg">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-3">
                                <div class="flex-shrink-0 w-10 h-10 bg-blue-500 rounded-lg flex items-center justify-center">
                                    <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-xs text-blue-600 font-medium">ASIGNADO AL PROYECTO</p>
                                    <p class="text-sm font-semibold text-gray-900"><?= htmlspecialchars($projectInfo['project_code']) ?> - <?= htmlspecialchars($projectInfo['project_name']) ?></p>
                                </div>
                            </div>
                            <div class="text-right">
                                <p class="text-xs text-gray-600">Progreso del Backlog</p>
                                <div class="flex items-center gap-2 mt-1">
                                    <div class="w-24 bg-gray-200 rounded-full h-2">
                                        <div class="bg-green-500 h-2 rounded-full" style="width: <?= $totalTasks > 0 ? round(($completedTasks / $totalTasks) * 100) : 0 ?>%"></div>
                                    </div>
                                    <span class="text-xs font-medium text-gray-700"><?= $completedTasks ?>/<?= $totalTasks ?> tareas</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                <div class="space-y-3">
                    <?php foreach ($backlogItems as $item): ?>
                    <div class="border border-gray-200 rounded-lg p-3 hover:bg-gray-50 transition-colors">
                        <div class="flex items-start justify-between">
                            <div class="flex-1">
                                <!-- Título del Item -->
                                <div class="flex items-start gap-2 mb-2">
                                    <div class="flex-shrink-0 w-6 h-6 bg-purple-100 rounded flex items-center justify-center mt-0.5">
                                        <span class="text-purple-600 font-bold text-xs">B</span>
                                    </div>
                                    <h4 class="font-medium text-gray-900 flex-1"><?= htmlspecialchars($item['title']) ?></h4>
                                </div>
                                
                                <!-- Badges y Metadata -->
                                <div class="ml-8 flex flex-wrap gap-2 text-xs">
                                    <?php
                                    $itemStatusLabels = [
                                        'backlog' => ['text' => 'Por Hacer', 'class' => 'bg-gray-100 text-gray-800'],
                                        'ready' => ['text' => 'Preparado', 'class' => 'bg-blue-100 text-blue-800'],
                                        'in_progress' => ['text' => 'En Progreso', 'class' => 'bg-yellow-100 text-yellow-800'],
                                        'done' => ['text' => 'Hecho', 'class' => 'bg-green-100 text-green-800']
                                    ];
                                    $itemStatus = $itemStatusLabels[$item['status']] ?? ['text' => $item['status'], 'class' => 'bg-gray-100 text-gray-800'];
                                    ?>
                                    <span class="px-2 py-0.5 rounded-full font-medium <?= $itemStatus['class'] ?>">
                                        <?= $itemStatus['text'] ?>
                                    </span>
                                    
                                    <?php if ($item['sprint_name']): ?>
                                    <a href="/sprints/<?= $item['sprint_id'] ?>" class="px-2 py-0.5 bg-purple-100 text-purple-800 rounded-full font-medium hover:bg-purple-200">
                                        <i class="fas fa-rocket mr-1"></i><?= htmlspecialchars($item['sprint_name']) ?>
                                    </a>
                                    <?php endif; ?>
                                    
                                    <?php if ($item['story_points']): ?>
                                    <span class="px-2 py-0.5 bg-indigo-50 text-indigo-700 rounded-full">
                                        <i class="fas fa-chart-line mr-1"></i><?= $item['story_points'] ?> pts
                                    </span>
                                    <?php endif; ?>
                                    
                                    <?php if ($item['assigned_first_name']): ?>
                                    <span class="px-2 py-0.5 bg-gray-50 text-gray-700 rounded-full">
                                        <i class="fas fa-user mr-1"></i><?= htmlspecialchars($item['assigned_first_name'] . ' ' . $item['assigned_last_name']) ?>
                                    </span>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Trazabilidad de Tareas -->
                                <?php if ($item['tasks_count'] > 0): ?>
                                <div class="ml-8 mt-2 flex items-center gap-2 text-xs text-gray-600">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/>
                                    </svg>
                                    <span><?= $item['tasks_completed'] ?> de <?= $item['tasks_count'] ?> tareas completadas</span>
                                    <div class="w-16 bg-gray-200 rounded-full h-1.5">
                                        <div class="bg-green-500 h-1.5 rounded-full" style="width: <?= round(($item['tasks_completed'] / $item['tasks_count']) * 100) ?>%"></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            
                            <?php if ($item['sprint_id']): ?>
                            <a href="/sprints/<?= $item['sprint_id'] ?>" class="ml-2 text-blue-600 hover:text-blue-800">
                                <i class="fas fa-arrow-right"></i>
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Nota de Flujo -->
                <div class="mt-4 p-3 bg-blue-50 border border-blue-100 rounded text-xs text-blue-800">
                    <strong>📊 Trazabilidad:</strong> 
                    Este requerimiento genera <?= count($backlogItems) ?> item(s) de backlog<?= $totalTasks > 0 ? ", que contienen {$totalTasks} tareas en total" : "" ?>.
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Historial de Cambios -->
            <div class="bg-white shadow rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Historial de Cambios</h3>
                <div class="flow-root">
                    <ul class="-mb-8">
                        <?php foreach ($history as $index => $item): ?>
                        <li>
                            <div class="relative pb-8">
                                <?php if ($index !== count($history) - 1): ?>
                                <span class="absolute top-4 left-4 -ml-px h-full w-0.5 bg-gray-200"></span>
                                <?php endif; ?>
                                <div class="relative flex space-x-3">
                                    <div>
                                        <span class="h-8 w-8 rounded-full bg-blue-500 flex items-center justify-center ring-8 ring-white">
                                            <i class="fas fa-history text-white text-xs"></i>
                                        </span>
                                    </div>
                                    <div class="min-w-0 flex-1 pt-1.5">
                                        <div>
                                            <p class="text-sm text-gray-500">
                                                <span class="font-medium text-gray-900"><?= htmlspecialchars($item['user_name']) ?></span>
                                                <?= htmlspecialchars($item['action']) ?>
                                                <?php if ($item['field_name']): ?>
                                                    <span class="font-medium"><?= htmlspecialchars($item['field_name']) ?></span>
                                                <?php endif; ?>
                                            </p>
                                            <?php if ($item['old_value'] && $item['new_value']): ?>
                                            <p class="text-xs text-gray-400 mt-1">
                                                De: <span class="font-mono"><?= htmlspecialchars($item['old_value']) ?></span> →
                                                A: <span class="font-mono"><?= htmlspecialchars($item['new_value']) ?></span>
                                            </p>
                                            <?php endif; ?>
                                            <p class="text-xs text-gray-400 mt-1">
                                                <?= date('d/m/Y H:i', strtotime($item['created_at'])) ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Sidebar con información -->
        <div class="space-y-6">
            <!-- Estado y Clasificación -->
            <div class="bg-white shadow rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Estado</h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-sm font-medium text-gray-500">Estado Actual</label>
                        <?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'],
                            'rejected' => ['text' => 'Rechazado', 'class' => 'bg-red-100 text-red-800'],
                            'in_development' => ['text' => 'En Desarrollo', 'class' => 'bg-purple-100 text-purple-800'],
                            'in_testing' => ['text' => 'En Pruebas', 'class' => 'bg-indigo-100 text-indigo-800'],
                            'completed' => ['text' => 'Completado', 'class' => 'bg-gray-100 text-gray-800'],
                        ];
                        $status = $statusLabels[$requirement['status']] ?? ['text' => $requirement['status'], 'class' => 'bg-gray-100 text-gray-800'];
                        ?>
                        <div class="mt-1">
                            <span class="px-3 py-1 inline-flex text-sm font-semibold rounded-full <?= $status['class'] ?>">
                                <?= $status['text'] ?>
                            </span>
                        </div>
                    </div>

                    <div>
                        <label class="text-sm font-medium text-gray-500">Tipo</label>
                        <?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[$requirement['type']] ?? ['text' => $requirement['type'], 'class' => 'bg-gray-100 text-gray-800'];
                        ?>
                        <div class="mt-1">
                            <span class="px-3 py-1 inline-flex text-sm font-semibold rounded-full <?= $type['class'] ?>">
                                <?= $type['text'] ?>
                            </span>
                        </div>
                    </div>

                    <div>
                        <label class="text-sm font-medium text-gray-500">Prioridad</label>
                        <?php
                        $priorityLabels = [
                            'low' => ['text' => 'Baja', 'class' => 'text-gray-600'],
                            'medium' => ['text' => 'Media', 'class' => 'text-blue-600'],
                            'high' => ['text' => 'Alta', 'class' => 'text-orange-600'],
                            'critical' => ['text' => 'Crítica', 'class' => 'text-red-600'],
                        ];
                        $priority = $priorityLabels[$requirement['priority']] ?? ['text' => $requirement['priority'], 'class' => 'text-gray-600'];
                        ?>
                        <p class="mt-1 text-sm font-semibold <?= $priority['class'] ?>"><?= $priority['text'] ?></p>
                    </div>
                </div>
            </div>

            <!-- Asignación -->
            <div class="bg-white shadow rounded-lg p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">Asignación</h3>
                    <?php if ($canEdit): ?>
                    <button onclick="showReassignModal()" class="text-sm text-blue-600 hover:text-blue-800 font-medium">
                        <i class="fas fa-exchange-alt mr-1"></i>Reasignar
                    </button>
                    <?php endif; ?>
                </div>
                <div class="space-y-4">
                    <div>
                        <label class="text-sm font-medium text-gray-500">Tipo de Requerimiento</label>
                        <?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[$requirement['type']] ?? ['text' => $requirement['type'], 'class' => 'bg-gray-100 text-gray-800'];
                        ?>
                        <div class="mt-1">
                            <span class="px-3 py-1 inline-flex text-sm font-semibold rounded-full <?= $type['class'] ?>">
                                <?= $type['text'] ?>
                            </span>
                        </div>
                    </div>
                    
                    <div>
                        <label class="text-sm font-medium text-gray-500">Equipo Asignado</label>
                        <?php
                        $teamLabels = [
                            'support' => 'Operación y Soporte',
                            'automation' => 'Automatización y Mejora',
                            'erp_projects' => 'Proyectos ERP',
                            'infrastructure' => 'Infraestructura',
                        ];
                        ?>
                        <p class="mt-1 text-sm font-semibold text-gray-900">
                            <?= $teamLabels[$requirement['assigned_team']] ?? 'No asignado' ?>
                        </p>
                    </div>

                    <div>
                        <label class="text-sm font-medium text-gray-500">Asignado a</label>
                        <p class="mt-1 text-sm text-gray-900">
                            <?= $requirement['assigned_user_name'] ?? 'Sin asignar' ?>
                        </p>
                        <?php if ($canEdit && !$requirement['assigned_user_id']): ?>
                        <button onclick="showAssignModal()" class="mt-2 text-xs text-blue-600 hover:text-blue-800">
                            <i class="fas fa-user-plus mr-1"></i>Asignar usuario
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- SLA y Fechas -->
            <div class="bg-white shadow rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Fechas y SLA</h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-sm font-medium text-gray-500">Fecha de Creación</label>
                        <p class="mt-1 text-sm text-gray-900"><?= date('d/m/Y H:i', strtotime($requirement['created_at'])) ?></p>
                    </div>

                    <div>
                        <label class="text-sm font-medium text-gray-500">SLA</label>
                        <p class="mt-1 text-sm text-gray-900"><?= $requirement['sla_hours'] ?> horas</p>
                    </div>

                    <div>
                        <label class="text-sm font-medium text-gray-500">Fecha Límite</label>
                        <?php if ($requirement['due_date']): ?>
                        <?php
                        $now = new DateTime();
                        $dueDate = new DateTime($requirement['due_date']);
                        $diff = $now->diff($dueDate);
                        $isOverdue = $now > $dueDate;
                        ?>
                        <p class="mt-1 text-sm font-semibold <?= $isOverdue ? 'text-red-600' : 'text-gray-900' ?>">
                            <?= date('d/m/Y H:i', strtotime($requirement['due_date'])) ?>
                        </p>
                        <?php if (!$isOverdue && $requirement['status'] != 'completed'): ?>
                        <p class="mt-1 text-xs text-gray-500">
                            <?= $diff->days ?> días, <?= $diff->h ?> horas restantes
                        </p>
                        <?php elseif ($isOverdue && $requirement['status'] != 'completed'): ?>
                        <p class="mt-1 text-xs text-red-600">
                            <i class="fas fa-exclamation-triangle mr-1"></i>Vencido
                        </p>
                        <?php endif; ?>
                        <?php else: ?>
                        <p class="mt-1 text-sm text-gray-500">No definida</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Solicitante -->
            <div class="bg-white shadow rounded-lg p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Solicitante</h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-sm font-medium text-gray-500">Usuario</label>
                        <p class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($requirement['requester_name']) ?></p>
                    </div>

                    <?php if (!empty($requirement['department'])): ?>
                    <div>
                        <label class="text-sm font-medium text-gray-500">Área</label>
                        <p class="mt-1 text-sm text-gray-900"><?= htmlspecialchars($requirement['department']) ?></p>
                    </div>
                    <?php endif; ?>

                    <?php if ($requirement['affected_users']): ?>
                    <div>
                        <label class="text-sm font-medium text-gray-500">Usuarios Afectados</label>
                        <p class="mt-1 text-sm text-gray-900"><?= $requirement['affected_users'] ?></p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Crear Backlog Item -->
<div id="createBacklogItemModal" class="hidden fixed z-50 inset-0 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
            <form action="/backlog/items/create" method="POST">
                <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                <input type="hidden" name="project_id" value="<?= $requirement['project_id'] ?>">
                <input type="hidden" name="requirement_id" value="<?= $requirement['id'] ?>">
                
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">Crear Item de Backlog</h3>
                        <div class="text-sm text-gray-500">
                            <i class="fas fa-link mr-1"></i>Desde: <?= htmlspecialchars($requirement['code']) ?>
                        </div>
                    </div>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Título *</label>
                            <input type="text" name="title" required value="<?= htmlspecialchars($requirement['title']) ?>"
                                   class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Tipo *</label>
                                <select name="type" required class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md">
                                    <option value="user_story" selected>Historia de Usuario</option>
                                    <option value="task">Tarea</option>
                                    <option value="bug">Bug</option>
                                    <option value="improvement">Mejora</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Prioridad *</label>
                                <select name="priority" required class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md">
                                    <option value="low">Baja</option>
                                    <option value="medium" selected>Media</option>
                                    <option value="high">Alta</option>
                                    <option value="critical">Crítica</option>
                                </select>
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Descripción</label>
                            <textarea name="description" rows="3" 
                                      class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"><?= htmlspecialchars($requirement['description']) ?></textarea>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Historia de Usuario (Como... Quiero... Para...)</label>
                            <textarea name="user_story" rows="2" placeholder="Como [rol], quiero [funcionalidad], para [beneficio]"
                                      class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"></textarea>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Criterios de Aceptación</label>
                            <textarea name="acceptance_criteria" rows="3" placeholder="- Dado que... Cuando... Entonces...&#10;- ..."
                                      class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"></textarea>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Story Points</label>
                                <select name="story_points" class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md">
                                    <option value="">Sin estimar</option>
                                    <option value="1">1 - Muy simple</option>
                                    <option value="2">2 - Simple</option>
                                    <option value="3">3 - Moderado</option>
                                    <option value="5">5 - Complejo</option>
                                    <option value="8">8 - Muy complejo</option>
                                    <option value="13">13 - Épica (dividir)</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Asignar a</label>
                                <select name="assigned_to" class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md">
                                    <option value="">Sin asignar</option>
                                    <?php
                                    $team = $requirement['assigned_team'] ?? 'automation';
                                    if (isset($usersByTeam[$team])):
                                        foreach ($usersByTeam[$team] as $user):
                                    ?>
                                    <option value="<?= $user['id'] ?>"><?= htmlspecialchars($user['name']) ?></option>
                                    <?php 
                                        endforeach;
                                    endif;
                                    ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="submit" class="w-full sm:w-auto sm:ml-3 px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
                        <i class="fas fa-plus mr-2"></i>Crear Item
                    </button>
                    <button type="button" onclick="hideCreateBacklogItemModal()" class="mt-3 sm:mt-0 w-full sm:w-auto px-4 py-2 bg-white text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">
                        Cancelar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Reasignar -->
<div id="reassignModal" class="hidden fixed z-50 inset-0 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form action="/requirements" method="POST">
                <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                <input type="hidden" name="action" value="reassign">
                <input type="hidden" name="requirement_id" value="<?= $requirement['id'] ?>">
                
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Reasignar Requerimiento</h3>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Tipo de Requerimiento</label>
                            <select name="type" id="reassign_type" required class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                <option value="incident" <?= $requirement['type'] === 'incident' ? 'selected' : '' ?>>Incidente</option>
                                <option value="support" <?= $requirement['type'] === 'support' ? 'selected' : '' ?>>Soporte</option>
                                <option value="improvement" <?= $requirement['type'] === 'improvement' ? 'selected' : '' ?>>Mejora</option>
                                <option value="project_minor" <?= $requirement['type'] === 'project_minor' ? 'selected' : '' ?>>Proyecto Menor</option>
                                <option value="project_major" <?= $requirement['type'] === 'project_major' ? 'selected' : '' ?>>Proyecto Mayor</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Equipo</label>
                            <select name="team" id="reassign_team" required class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                <option value="support" <?= $requirement['assigned_team'] === 'support' ? 'selected' : '' ?>>Operación y Soporte</option>
                                <option value="automation" <?= $requirement['assigned_team'] === 'automation' ? 'selected' : '' ?>>Automatización y Mejora</option>
                                <option value="erp_projects" <?= $requirement['assigned_team'] === 'erp_projects' ? 'selected' : '' ?>>Proyectos ERP</option>
                                <option value="infrastructure" <?= $requirement['assigned_team'] === 'infrastructure' ? 'selected' : '' ?>>Infraestructura</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Usuario (opcional)</label>
                            <select name="assigned_user_id" id="reassign_user" class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                <option value="">Sin asignar</option>
                                <?php foreach ($allUsers as $user): ?>
                                <option value="<?= $user['id'] ?>" data-teams="<?php
                                    $teams = [];
                                    foreach ($usersByTeam as $teamCode => $members) {
                                        foreach ($members as $member) {
                                            if ($member['id'] == $user['id']) {
                                                $teams[] = $teamCode;
                                            }
                                        }
                                    }
                                    echo htmlspecialchars(json_encode($teams));
                                ?>" <?= $requirement['assigned_user_id'] == $user['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($user['name']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="mt-1 text-xs text-gray-500">Solo se mostrarán usuarios del equipo seleccionado</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Motivo de reasignación</label>
                            <textarea name="reason" rows="3" required placeholder="Explique por qué se está reasignando..." 
                                class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"></textarea>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="submit" class="w-full sm:w-auto sm:ml-3 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">Reasignar</button>
                    <button type="button" onclick="hideReassignModal()" class="mt-3 sm:mt-0 w-full sm:w-auto px-4 py-2 bg-white text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">Cancelar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Cambiar Estado -->
<div id="statusModal" class="hidden fixed z-50 inset-0 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form action="/requirements" method="POST">
                <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                <input type="hidden" name="action" value="change_status">
                <input type="hidden" name="requirement_id" value="<?= $requirement['id'] ?>">
                
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">Cambiar Estado</h3>
                    <select name="status" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                        <option value="classified">Clasificado</option>
                        <option value="in_analysis">En Análisis</option>
                        <option value="approved">Aprobado</option>
                        <option value="rejected">Rechazado</option>
                        <option value="in_development">En Desarrollo</option>
                        <option value="in_testing">En Pruebas</option>
                        <option value="completed">Completado</option>
                    </select>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="submit" class="w-full sm:w-auto sm:ml-3 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">Cambiar</button>
                    <button type="button" onclick="hideStatusModal()" class="mt-3 sm:mt-0 w-full sm:w-auto px-4 py-2 bg-white text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">Cancelar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showChangeStatusModal() {
    document.getElementById('statusModal').classList.remove('hidden');
}

function hideStatusModal() {
    document.getElementById('statusModal').classList.add('hidden');
}

function showReassignModal() {
    document.getElementById('reassignModal').classList.remove('hidden');
}

function hideReassignModal() {
    document.getElementById('reassignModal').classList.add('hidden');
}

function showCreateBacklogItemModal() {
    document.getElementById('createBacklogItemModal').classList.remove('hidden');
}

function hideCreateBacklogItemModal() {
    document.getElementById('createBacklogItemModal').classList.add('hidden');
}

// Auto-seleccionar equipo según tipo de requerimiento
document.getElementById('reassign_type')?.addEventListener('change', function() {
    const typeToTeam = {
        'incident': 'support',
        'support': 'support',
        'improvement': 'automation',
        'project_minor': 'automation',
        'project_major': 'erp_projects'
    };
    const teamSelect = document.getElementById('reassign_team');
    if (teamSelect && typeToTeam[this.value]) {
        teamSelect.value = typeToTeam[this.value];
        // Disparar evento de cambio de equipo para filtrar usuarios
        teamSelect.dispatchEvent(new Event('change'));
    }
});

// Filtrar usuarios cuando cambie el equipo
document.getElementById('reassign_team')?.addEventListener('change', function() {
    const selectedTeam = this.value;
    const userSelect = document.getElementById('reassign_user');
    
    if (!userSelect) return;
    
    const currentValue = userSelect.value;
    
    // Mostrar todas las opciones primero
    Array.from(userSelect.options).forEach(option => {
        if (option.value === '') {
            option.style.display = 'block';
            return;
        }
        
        const userTeams = JSON.parse(option.getAttribute('data-teams') || '[]');
        
        // Mostrar solo usuarios que pertenecen al equipo seleccionado
        if (userTeams.includes(selectedTeam)) {
            option.style.display = 'block';
        } else {
            option.style.display = 'none';
            // Si la opción oculta estaba seleccionada, deseleccionarla
            if (option.value === currentValue) {
                userSelect.value = '';
            }
        }
    });
});

// === GESTIÓN DE DOCUMENTOS ===

// Cargar documentos al cargar la página
document.addEventListener('DOMContentLoaded', function() {
    loadDocuments();
});

function loadDocuments() {
    const requirementId = <?= $requirement['id'] ?>;
    
    fetch(`/documents/list?requirement_id=${requirementId}`, {
        credentials: 'same-origin'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderDocuments(data.documents);
            } else {
                showDocumentError('Error al cargar documentos');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showDocumentError('Error de conexión');
        });
}

function renderDocuments(documents) {
    const container = document.getElementById('documentsList');
    
    if (!documents || documents.length === 0) {
        container.innerHTML = `
            <div class="text-center text-gray-500 py-8">
                <i class="fas fa-folder-open text-4xl mb-3 text-gray-300"></i>
                <p>No hay documentos cargados</p>
                <p class="text-sm mt-1">Sube el diagrama AS-IS para iniciar el análisis</p>
            </div>
        `;
        return;
    }
    
    const typeLabels = {
        'as_is': { text: 'AS-IS', icon: 'fa-project-diagram', color: 'blue' },
        'to_be': { text: 'TO-BE', icon: 'fa-sitemap', color: 'green' },
        'technical': { text: 'Técnico', icon: 'fa-code', color: 'purple' },
        'user_manual': { text: 'Manual', icon: 'fa-book', color: 'indigo' },
        'other': { text: 'Otro', icon: 'fa-file', color: 'gray' }
    };
    
    const statusLabels = {
        'draft': { text: 'Borrador', color: 'gray' },
        'pending_review': { text: 'Pendiente Revisión', color: 'yellow' },
        'approved': { text: 'Aprobado', color: 'green' },
        'rejected': { text: 'Rechazado', color: 'red' }
    };
    
    // Variables de permisos desde PHP
    const canReview = <?= json_encode(isset($userRole) && ($userRole === 'admin' || $userRole === 'quality')) ?>;
    const isAdmin = <?= json_encode(isset($isAdmin) ? $isAdmin : false) ?>;
    
    const html = documents.map(doc => {
        const type = typeLabels[doc.document_type] || typeLabels.other;
        const status = statusLabels[doc.status] || statusLabels.draft;
        
        return `
            <div class="border border-gray-200 rounded-lg p-4 hover:bg-gray-50">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <div class="flex items-center space-x-2 mb-2">
                            <span class="px-2 py-1 bg-${type.color}-100 text-${type.color}-800 text-xs font-semibold rounded">
                                <i class="fas ${type.icon} mr-1"></i>${type.text}
                            </span>
                            <span class="px-2 py-1 bg-${status.color}-100 text-${status.color}-800 text-xs font-semibold rounded">
                                ${status.text}
                            </span>
                            <span class="text-xs text-gray-500">v${doc.version}</span>
                        </div>
                        
                        <h4 class="font-medium text-gray-900 mb-1">${doc.title}</h4>
                        ${doc.description ? `<p class="text-sm text-gray-600 mb-2">${doc.description}</p>` : ''}
                        
                        <div class="flex items-center text-xs text-gray-500 space-x-4">
                            <span><i class="fas fa-user mr-1"></i>${doc.uploader_name || 'N/A'}</span>
                            <span><i class="fas fa-calendar mr-1"></i>${new Date(doc.created_at).toLocaleDateString('es-ES')}</span>
                            <span><i class="fas fa-file mr-1"></i>${formatFileSize(doc.file_size)}</span>
                        </div>
                        
                        ${doc.reviewed_by ? `
                            <div class="mt-2 pt-2 border-t border-gray-200">
                                <p class="text-xs text-gray-600">
                                    <i class="fas fa-user-check mr-1"></i>
                                    Revisado por <strong>${doc.reviewer_name}</strong> 
                                    el ${new Date(doc.review_date).toLocaleDateString('es-ES')}
                                </p>
                                ${doc.review_notes ? `<p class="text-xs text-gray-600 mt-1 italic">${doc.review_notes}</p>` : ''}
                            </div>
                        ` : ''}
                    </div>
                    
                    <div class="flex flex-col space-y-2 ml-4">
                        <a href="/documents/download/${doc.id}" 
                           class="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700">
                            <i class="fas fa-download mr-1"></i>Descargar
                        </a>
                        
                        ${canReview && doc.status === 'pending_review' ? `
                            <button onclick="showReviewModal(${doc.id}, \`${doc.title.replace(/`/g, '\\`').replace(/\$/g, '\\$')}\`)"
                                    class="px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700">
                                <i class="fas fa-check mr-1"></i>Revisar
                            </button>
                        ` : ''}
                        
                        ${isAdmin ? `
                            <button onclick="deleteDocument(${doc.id})"
                                    class="px-3 py-1 bg-red-600 text-white text-sm rounded hover:bg-red-700">
                                <i class="fas fa-trash mr-1"></i>Eliminar
                            </button>
                        ` : ''}
                    </div>
                </div>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
}

function showUploadDocumentModal() {
    const html = `
        <div id="uploadDocumentModal" class="fixed z-50 inset-0 overflow-y-auto">
            <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="hideUploadDocumentModal()"></div>
                <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                    <form id="uploadDocumentForm" onsubmit="uploadDocument(event)">
                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        <input type="hidden" name="requirement_id" value="<?= $requirement['id'] ?>">
                        
                        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">
                                <i class="fas fa-upload text-blue-600 mr-2"></i>
                                Subir Documento de Proceso
                            </h3>
                            
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Tipo de Documento *</label>
                                    <select name="document_type" required class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                        <option value="">Seleccione...</option>
                                        <option value="as_is">Diagrama AS-IS (Proceso Actual)</option>
                                        <option value="to_be">Diagrama TO-BE (Proceso Mejorado)</option>
                                        <option value="technical">Documentación Técnica</option>
                                        <option value="user_manual">Manual de Usuario</option>
                                        <option value="other">Otro</option>
                                    </select>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Título *</label>
                                    <input type="text" name="title" required maxlength="200"
                                           placeholder="Ej: Proceso de Matrícula - Estado Actual"
                                           class="mt-1 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">Descripción</label>
                                    <textarea name="description" rows="3" maxlength="500"
                                              placeholder="Descripción opcional del documento..."
                                              class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"></textarea>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Versión</label>
                                    <input type="text" name="version" value="1.0" maxlength="20"
                                           class="mt-1 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">Archivo *</label>
                                    <input type="file" name="document" required accept=".pdf,.doc,.docx,.ppt,.pptx,.vsd,.vsdx,.png,.jpg,.jpeg"
                                           class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                                    <p class="mt-1 text-xs text-gray-500">
                                        Formatos: PDF, Word, PowerPoint, Visio, PNG, JPG • Máximo 10MB
                                    </p>
                                </div>
                                
                                <div class="bg-blue-50 border-l-4 border-blue-400 p-3">
                                    <p class="text-xs text-blue-800">
                                        <i class="fas fa-info-circle mr-1"></i>
                                        <strong>Nota:</strong> Al subir un documento AS-IS, el requerimiento pasará automáticamente a estado "En Análisis".
                                    </p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                            <button type="submit" class="w-full sm:w-auto sm:ml-3 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                                <i class="fas fa-upload mr-2"></i>Subir Documento
                            </button>
                            <button type="button" onclick="hideUploadDocumentModal()" 
                                    class="mt-3 sm:mt-0 w-full sm:w-auto px-4 py-2 bg-white text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">
                                Cancelar
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', html);
}

function hideUploadDocumentModal() {
    const modal = document.getElementById('uploadDocumentModal');
    if (modal) modal.remove();
}

function uploadDocument(event) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const button = form.querySelector('button[type="submit"]');
    
    // Log para debugging
    console.log('=== UPLOAD DOCUMENT ===');
    console.log('Form data entries:');
    for (let pair of formData.entries()) {
        if (pair[0] === 'document') {
            console.log(pair[0] + ': [File] ' + pair[1].name + ' (' + pair[1].size + ' bytes)');
        } else {
            console.log(pair[0] + ': ' + pair[1]);
        }
    }
    
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Subiendo...';
    
    fetch('/documents/upload', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
    })
    .then(response => {
        console.log('Response status:', response.status);
        console.log('Response ok:', response.ok);
        console.log('Response headers:', response.headers.get('content-type'));
        return response.text().then(text => {
            console.log('Response text:', text);
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('Error parsing JSON:', e);
                throw new Error('Respuesta no válida del servidor: ' + text.substring(0, 100));
            }
        });
    })
    .then(data => {
        console.log('Parsed data:', data);
        if (data.success) {
            hideUploadDocumentModal();
            loadDocuments();
            showSuccessMessage('Documento subido correctamente');
            
            // Recargar página si el estado cambió
            if (data.status_changed) {
                setTimeout(() => window.location.reload(), 1500);
            }
        } else {
            alert('Error: ' + data.message);
            button.disabled = false;
            button.innerHTML = '<i class="fas fa-upload mr-2"></i>Subir Documento';
        }
    })
    .catch(error => {
        console.error('Error completo:', error);
        alert('Error al subir el documento: ' + error.message);
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-upload mr-2"></i>Subir Documento';
    });
}

function showReviewModal(docId, docTitle) {
    const html = `
        <div id="reviewDocumentModal" class="fixed z-10 inset-0 overflow-y-auto">
            <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="hideReviewModal()"></div>
                <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                    <form id="reviewDocumentForm" onsubmit="reviewDocument(event, ${docId})">
                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        <input type="hidden" name="document_id" value="${docId}">
                        
                        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">
                                <i class="fas fa-clipboard-check text-green-600 mr-2"></i>
                                Revisar Documento
                            </h3>
                            
                            <p class="text-sm text-gray-600 mb-4">
                                <strong>Documento:</strong> ${docTitle}
                            </p>
                            
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Decisión *</label>
                                    <div class="flex space-x-4">
                                        <label class="flex items-center">
                                            <input type="radio" name="review_status" value="approved" required class="mr-2">
                                            <span class="text-sm text-green-700"><i class="fas fa-check-circle mr-1"></i>Aprobar</span>
                                        </label>
                                        <label class="flex items-center">
                                            <input type="radio" name="review_status" value="rejected" required class="mr-2">
                                            <span class="text-sm text-red-700"><i class="fas fa-times-circle mr-1"></i>Rechazar</span>
                                        </label>
                                    </div>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700">Notas de Revisión</label>
                                    <textarea name="review_notes" rows="4" 
                                              placeholder="Comentarios sobre la revisión (opcional)..."
                                              class="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"></textarea>
                                </div>
                                
                                <div class="bg-yellow-50 border-l-4 border-yellow-400 p-3">
                                    <p class="text-xs text-yellow-800">
                                        <i class="fas fa-exclamation-triangle mr-1"></i>
                                        <strong>Nota:</strong> Si aprueba un documento TO-BE, el requerimiento pasará a estado "Aprobado" y se podrá crear el proyecto.
                                    </p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                            <button type="submit" class="w-full sm:w-auto sm:ml-3 px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
                                <i class="fas fa-check mr-2"></i>Confirmar Revisión
                            </button>
                            <button type="button" onclick="hideReviewModal()" 
                                    class="mt-3 sm:mt-0 w-full sm:w-auto px-4 py-2 bg-white text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">
                                Cancelar
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', html);
}

function hideReviewModal() {
    const modal = document.getElementById('reviewDocumentModal');
    if (modal) modal.remove();
}

function reviewDocument(event, docId) {
    event.preventDefault();
    
    const form = event.target;
    const formData = new FormData(form);
    const button = form.querySelector('button[type="submit"]');
    
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Procesando...';
    
    fetch('/documents/review', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            hideReviewModal();
            loadDocuments();
            showSuccessMessage('Revisión registrada correctamente');
            
            // Recargar página si el estado cambió
            if (data.status_changed) {
                setTimeout(() => window.location.reload(), 1500);
            }
        } else {
            alert('Error: ' + data.message);
            button.disabled = false;
            button.innerHTML = '<i class="fas fa-check mr-2"></i>Confirmar Revisión';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error al procesar la revisión');
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-check mr-2"></i>Confirmar Revisión';
    });
}

function deleteDocument(docId) {
    if (!confirm('¿Está seguro de eliminar este documento? Esta acción no se puede deshacer.')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('csrf_token', '<?= $csrf_token ?>');
    formData.append('document_id', docId);
    
    fetch('/documents/delete', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadDocuments();
            showSuccessMessage('Documento eliminado');
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error al eliminar el documento');
    });
}

function formatFileSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function showSuccessMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 z-50 p-4 bg-green-50 border border-green-200 text-green-800 rounded-lg shadow-lg';
    alertDiv.innerHTML = `
        <i class="fas fa-check-circle mr-2"></i>${message}
    `;
    document.body.appendChild(alertDiv);
    
    setTimeout(() => alertDiv.remove(), 3000);
}

function showDocumentError(message) {
    const container = document.getElementById('documentsList');
    container.innerHTML = `
        <div class="text-center text-red-500 py-8">
            <i class="fas fa-exclamation-triangle text-4xl mb-3"></i>
            <p>${message}</p>
        </div>
    `;
}
</script>

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