<?php
$title = htmlspecialchars($project['name']) . ' - Sistema de Gestión de Proyectos';
$page_title = 'Detalle de Proyecto';
$current_page = 'projects';
$showSidebar = true;
$csrf_token = csrf_token();

ob_start();

$statusColors = [
    'planning' => 'bg-gray-100 text-gray-800',
    'in_progress' => 'bg-blue-100 text-blue-800',
    'testing' => 'bg-yellow-100 text-yellow-800',
    'deployed' => 'bg-green-100 text-green-800',
    'closed' => 'bg-gray-300 text-gray-700'
];
$statusLabels = [
    'planning' => 'Planificación',
    'in_progress' => 'En Progreso',
    'testing' => 'En Pruebas',
    'deployed' => 'Desplegado',
    'closed' => 'Cerrado'
];
$priorityColors = [
    'low' => 'text-gray-700',
    'medium' => 'text-blue-700',
    'high' => 'text-orange-700',
    'critical' => 'text-red-700'
];
$priorityLabels = [
    'low' => 'Baja',
    'medium' => 'Media',
    'high' => 'Alta',
    'critical' => 'Crítica'
];
?>

<div class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-start justify-between">
            <div class="flex items-start gap-4 flex-1">
                <a href="/projects" class="text-gray-600 hover:text-gray-900 mt-1">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                    </svg>
                </a>
                <div class="flex-1">
                    <div class="flex items-center gap-3 mb-2">
                        <span class="text-sm font-mono text-gray-500"><?= htmlspecialchars($project['code']) ?></span>
                        <span class="px-3 py-1 text-sm font-medium rounded <?= $statusColors[$project['status']] ?>">
                            <?= $statusLabels[$project['status']] ?>
                        </span>
                        <span class="text-sm font-medium <?= $priorityColors[$project['priority']] ?>">
                            Prioridad: <?= $priorityLabels[$project['priority']] ?>
                        </span>
                    </div>
                    <h1 class="text-2xl font-bold text-gray-900 mb-1"><?= htmlspecialchars($project['name']) ?></h1>
                    <?php if (!empty($project['description'])): ?>
                        <p class="text-gray-600"><?= htmlspecialchars($project['description']) ?></p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Cambiar Estado -->
            <div class="ml-4 flex gap-3">
                <a href="/backlog/<?= $project['id'] ?>" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors inline-flex items-center gap-2">
                    <svg class="w-5 h-5" 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>
                    Ver Backlog
                </a>
                
                <select id="statusSelect" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="planning" <?= $project['status'] === 'planning' ? 'selected' : '' ?>>Planificación</option>
                    <option value="in_progress" <?= $project['status'] === 'in_progress' ? 'selected' : '' ?>>En Progreso</option>
                    <option value="testing" <?= $project['status'] === 'testing' ? 'selected' : '' ?>>En Pruebas</option>
                    <option value="deployed" <?= $project['status'] === 'deployed' ? 'selected' : '' ?>>Desplegado</option>
                    <option value="closed" <?= $project['status'] === 'closed' ? 'selected' : '' ?>>Cerrado</option>
                </select>
            </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">
            <!-- Progreso -->
            <div class="bg-white rounded-lg shadow-sm p-6">
                <h2 class="text-lg font-semibold text-gray-900 mb-4">Progreso del Proyecto</h2>
                
                <div class="mb-6">
                    <div class="flex justify-between text-sm mb-2">
                        <span class="text-gray-600">Avance General</span>
                        <span class="font-medium text-gray-900" id="progressText"><?= $project['progress_percentage'] ?>%</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-3">
                        <div id="progressBar" class="bg-blue-600 h-3 rounded-full transition-all" style="width: <?= $project['progress_percentage'] ?>%"></div>
                    </div>
                    <div class="mt-4">
                        <input type="range" id="progressSlider" min="0" max="100" value="<?= $project['progress_percentage'] ?>" 
                               class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
                    </div>
                </div>

                <!-- Estadísticas de Requerimientos -->
                <?php if ($requirementsStats['total'] > 0): ?>
                    <div class="grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg">
                        <div>
                            <p class="text-sm text-gray-600">Total Requerimientos</p>
                            <p class="text-2xl font-bold text-gray-900"><?= $requirementsStats['total'] ?></p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Completados</p>
                            <p class="text-2xl font-bold text-green-600">
                                <?= $requirementsStats['by_status']['completed'] ?? 0 ?> 
                                <span class="text-sm">(<?= $requirementsStats['completed_percentage'] ?>%)</span>
                            </p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Requerimientos Asociados -->
            <div class="bg-white rounded-lg shadow-sm p-6">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-lg font-semibold text-gray-900">Requerimientos Asociados</h2>
                    <button onclick="openAssignRequirementModal()" class="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        + Asignar Requerimiento
                    </button>
                </div>

                <?php if (empty($requirements)): ?>
                    <div class="text-center py-8 text-gray-500">
                        <p>No hay requerimientos asociados a este proyecto</p>
                        <button onclick="openAssignRequirementModal()" class="mt-4 text-blue-600 hover:text-blue-700">
                            Asignar el primer requerimiento
                        </button>
                    </div>
                <?php else: ?>
                    <div class="space-y-3">
                        <?php foreach ($requirements as $req): 
                            $reqStatusColors = [
                                'new' => 'bg-blue-100 text-blue-800',
                                'in_analysis' => 'bg-purple-100 text-purple-800',
                                'in_development' => 'bg-yellow-100 text-yellow-800',
                                'completed' => 'bg-green-100 text-green-800',
                                'cancelled' => 'bg-red-100 text-red-800'
                            ];
                        ?>
                        <div class="flex items-center justify-between p-4 border border-gray-200 rounded-lg hover:bg-gray-50">
                            <div class="flex-1">
                                <div class="flex items-center gap-2 mb-1">
                                    <span class="text-xs font-mono text-gray-500"><?= htmlspecialchars($req['code']) ?></span>
                                    <span class="px-2 py-0.5 text-xs font-medium rounded <?= $reqStatusColors[$req['status']] ?? 'bg-gray-100 text-gray-800' ?>">
                                        <?= htmlspecialchars($req['status']) ?>
                                    </span>
                                </div>
                                <a href="/requirements/<?= $req['id'] ?>" class="text-sm font-medium text-gray-900 hover:text-blue-600">
                                    <?= htmlspecialchars($req['title']) ?>
                                </a>
                                <p class="text-xs text-gray-500 mt-1">
                                    Solicitante: <?= htmlspecialchars($req['requester_first_name'] . ' ' . $req['requester_last_name']) ?>
                                </p>
                            </div>
                            <button onclick="removeRequirement(<?= $req['id'] ?>, '<?= htmlspecialchars($req['code']) ?>')" 
                                    class="ml-4 text-red-600 hover:text-red-700">
                                <svg class="w-5 h-5" 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>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- NUEVA SECCIÓN: Trazabilidad Completa -->
            <?php if (!empty($traceabilityByRequirement)): ?>
            <div class="bg-white rounded-lg shadow-sm p-6">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-lg font-semibold text-gray-900">
                        <svg class="w-5 h-5 inline-block mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 9l3 3m0 0l-3 3m3-3H8m13 0a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        Trazabilidad: Requerimientos → Backlog → Sprints → Tareas
                    </h2>
                    <a href="/backlog/<?= $project['id'] ?>" class="text-sm text-blue-600 hover:text-blue-700">
                        Ver Backlog Completo →
                    </a>
                </div>

                <div class="space-y-4">
                    <?php 
                    $itemStatusColors = [
                        'pending' => 'bg-gray-100 text-gray-700',
                        'in_progress' => 'bg-blue-100 text-blue-700',
                        'done' => 'bg-green-100 text-green-700',
                        'blocked' => 'bg-red-100 text-red-700'
                    ];
                    $priorityIcons = [
                        'critical' => '🔴',
                        'high' => '🟠',
                        'medium' => '🟡',
                        'low' => '⚪'
                    ];
                    
                    foreach ($traceabilityByRequirement as $reqId => $trace): 
                    ?>
                        <div class="border border-gray-200 rounded-lg p-4">
                            <!-- Requerimiento -->
                            <div class="flex items-start gap-3 mb-3">
                                <div class="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                                    <span class="text-blue-600 font-bold text-sm">R</span>
                                </div>
                                <div class="flex-1">
                                    <div class="flex items-center gap-2">
                                        <span class="text-xs font-mono text-gray-500"><?= htmlspecialchars($trace['requirement_code']) ?></span>
                                    </div>
                                    <p class="text-sm font-medium text-gray-900"><?= htmlspecialchars($trace['requirement_title']) ?></p>
                                </div>
                            </div>

                            <!-- Backlog Items -->
                            <?php if (!empty($trace['items'])): ?>
                                <div class="ml-11 space-y-2">
                                    <?php foreach ($trace['items'] as $item): ?>
                                        <div class="border-l-2 border-gray-300 pl-4">
                                            <div class="flex items-start justify-between">
                                                <div class="flex-1">
                                                    <div class="flex items-center gap-2 mb-1">
                                                        <div class="flex-shrink-0 w-6 h-6 bg-purple-100 rounded flex items-center justify-center">
                                                            <span class="text-purple-600 font-bold text-xs">B</span>
                                                        </div>
                                                        <span class="text-xs font-medium text-gray-700"><?= htmlspecialchars($item['backlog_item_title']) ?></span>
                                                        <span class="px-2 py-0.5 text-xs rounded <?= $itemStatusColors[$item['backlog_item_status']] ?? 'bg-gray-100' ?>">
                                                            <?= htmlspecialchars($item['backlog_item_status']) ?>
                                                        </span>
                                                        <span class="text-xs"><?= $priorityIcons[$item['backlog_item_priority']] ?? '' ?></span>
                                                    </div>
                                                    
                                                    <!-- Sprint asociado -->
                                                    <?php if (!empty($item['sprint_name'])): ?>
                                                        <div class="ml-8 flex items-center gap-2 text-xs text-gray-600 mt-1">
                                                            <div class="flex-shrink-0 w-5 h-5 bg-green-100 rounded flex items-center justify-center">
                                                                <span class="text-green-600 font-bold" style="font-size: 10px;">S</span>
                                                            </div>
                                                            <span>Sprint: <?= htmlspecialchars($item['sprint_name']) ?></span>
                                                            <span class="text-gray-400">|</span>
                                                            <span>📋 <?= $item['tasks_completed'] ?>/<?= $item['tasks_count'] ?> tareas</span>
                                                        </div>
                                                    <?php else: ?>
                                                        <div class="ml-8 text-xs text-gray-400 mt-1">
                                                            <span>⚠️ Sin sprint asignado</span>
                                                            <span class="text-gray-400 mx-1">|</span>
                                                            <span>📋 <?= $item['tasks_count'] ?> tareas</span>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="ml-11 text-xs text-gray-400 italic">
                                    Sin items de backlog aún
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>

                <div class="mt-4 p-3 bg-blue-50 border border-blue-100 rounded text-xs text-blue-800">
                    <strong>💡 Flujo Institucional:</strong> 
                    Requerimientos (aprobados) → Proyectos → Product Backlog Items → Sprints → Tareas
                </div>
            </div>
            <?php endif; ?>

            <!-- Documentos Técnicos -->
            <div class="bg-white rounded-lg shadow-sm p-6">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-lg font-semibold text-gray-900">
                        <i class="fas fa-file-code text-blue-600 mr-2"></i>
                        Documentación Técnica
                    </h2>
                    <button onclick="showUploadProjectDocumentModal()" 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>
                </div>

                <div id="projectDocumentsList" 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>
        </div>

        <!-- Columna Lateral -->
        <div class="space-y-6">
            <!-- Información General -->
            <div class="bg-white rounded-lg shadow-sm p-6">
                <h2 class="text-lg font-semibold text-gray-900 mb-4">Información</h2>
                <dl class="space-y-3 text-sm">
                    <?php if (!empty($project['requesting_department'])): ?>
                        <div>
                            <dt class="text-gray-600">Departamento</dt>
                            <dd class="font-medium text-gray-900 mt-1"><?= htmlspecialchars($project['requesting_department']) ?></dd>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($project['team_name'])): ?>
                        <div>
                            <dt class="text-gray-600">Equipo Responsable</dt>
                            <dd class="font-medium text-gray-900 mt-1"><?= htmlspecialchars($project['team_name']) ?></dd>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($project['budget'])): ?>
                        <div>
                            <dt class="text-gray-600">Presupuesto</dt>
                            <dd class="font-medium text-gray-900 mt-1">S/ <?= number_format($project['budget'], 2) ?></dd>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($project['start_date'])): ?>
                        <div>
                            <dt class="text-gray-600">Fecha de Inicio</dt>
                            <dd class="font-medium text-gray-900 mt-1"><?= date('d/m/Y', strtotime($project['start_date'])) ?></dd>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($project['target_date'])): ?>
                        <div>
                            <dt class="text-gray-600">Fecha Meta</dt>
                            <dd class="font-medium text-gray-900 mt-1"><?= date('d/m/Y', strtotime($project['target_date'])) ?></dd>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($project['completion_date'])): ?>
                        <div>
                            <dt class="text-gray-600">Fecha de Cierre</dt>
                            <dd class="font-medium text-gray-900 mt-1"><?= date('d/m/Y', strtotime($project['completion_date'])) ?></dd>
                        </div>
                    <?php endif; ?>

                    <div>
                        <dt class="text-gray-600">Creado por</dt>
                        <dd class="font-medium text-gray-900 mt-1">
                            <?= htmlspecialchars($project['creator_first_name'] . ' ' . $project['creator_last_name']) ?>
                        </dd>
                    </div>

                    <div>
                        <dt class="text-gray-600">Fecha de Creación</dt>
                        <dd class="font-medium text-gray-900 mt-1"><?= date('d/m/Y H:i', strtotime($project['created_at'])) ?></dd>
                    </div>
                </dl>
            </div>
        </div>
    </div>
</div>

<!-- Modal Asignar Requerimiento -->
<div id="assignRequirementModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg max-w-2xl w-full max-h-[80vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-900">Asignar Requerimiento al Proyecto</h3>
        </div>
        <div class="p-6">
            <?php if (empty($availableRequirements)): ?>
                <div class="text-center py-8">
                    <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    <p class="mt-4 text-gray-600 font-medium">No hay requerimientos aprobados disponibles</p>
                    <p class="mt-2 text-sm text-gray-500">Solo se pueden asignar requerimientos con estado "Aprobado"</p>
                    <p class="mt-1 text-sm text-gray-500">Los requerimientos deben pasar por análisis y aprobación antes de ser agregados a un proyecto</p>
                </div>
            <?php else: ?>
                <div class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                    <p class="text-sm text-blue-800">
                        <strong>ℹ️ Nota:</strong> Solo se muestran requerimientos aprobados que no estén asignados a otro proyecto.
                    </p>
                </div>
                <div class="space-y-2">
                    <?php foreach ($availableRequirements as $req): ?>
                        <div class="p-4 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer transition-colors" 
                             onclick="assignRequirement(<?= $req['id'] ?>)">
                            <div class="flex items-start justify-between">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2 mb-1">
                                        <span class="text-xs font-mono text-gray-500 bg-gray-100 px-2 py-1 rounded"><?= htmlspecialchars($req['code']) ?></span>
                                        <span class="text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full font-medium">✓ Aprobado</span>
                                    </div>
                                    <p class="font-medium text-gray-900 mb-1"><?= htmlspecialchars($req['title']) ?></p>
                                    <?php if (!empty($req['requester_name'])): ?>
                                        <p class="text-xs text-gray-500">Solicitante: <?= htmlspecialchars($req['requester_name']) ?></p>
                                    <?php endif; ?>
                                </div>
                                <button class="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors ml-4">
                                    Asignar →
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <div class="p-6 border-t border-gray-200 flex justify-end">
            <button onclick="closeAssignRequirementModal()" class="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">
                Cerrar
            </button>
        </div>
    </div>
</div>

<script>
const projectId = <?= $project['id'] ?>;

// Actualizar estado
document.getElementById('statusSelect').addEventListener('change', async (e) => {
    const formData = new FormData();
    formData.append('action', 'update_status');
    formData.append('status', e.target.value);
    
    try {
        const response = await fetch(`/projects/${projectId}/update`, {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        if (result.success) {
            location.reload();
        } else {
            alert(result.message);
            location.reload();
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error al actualizar el estado');
    }
});

// Actualizar progreso
const progressSlider = document.getElementById('progressSlider');
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');

let progressTimeout;
progressSlider.addEventListener('input', (e) => {
    const value = e.target.value;
    progressBar.style.width = value + '%';
    progressText.textContent = value + '%';
    
    clearTimeout(progressTimeout);
    progressTimeout = setTimeout(() => updateProgress(value), 1000);
});

async function updateProgress(value) {
    const formData = new FormData();
    formData.append('action', 'update_progress');
    formData.append('progress', value);
    
    try {
        const response = await fetch(`/projects/${projectId}/update`, {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        if (!result.success) {
            alert(result.message);
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

// Modal asignar requerimiento
function openAssignRequirementModal() {
    document.getElementById('assignRequirementModal').classList.remove('hidden');
}

function closeAssignRequirementModal() {
    document.getElementById('assignRequirementModal').classList.add('hidden');
}

async function assignRequirement(requirementId) {
    const formData = new FormData();
    formData.append('action', 'assign_requirement');
    formData.append('requirement_id', requirementId);
    
    try {
        const response = await fetch(`/projects/${projectId}/update`, {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        if (result.success) {
            location.reload();
        } else {
            alert(result.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error al asignar requerimiento');
    }
}

async function removeRequirement(requirementId, code) {
    if (!confirm(`¿Remover el requerimiento ${code} de este proyecto?`)) return;
    
    const formData = new FormData();
    formData.append('action', 'remove_requirement');
    formData.append('requirement_id', requirementId);
    
    try {
        const response = await fetch(`/projects/${projectId}/update`, {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        if (result.success) {
            location.reload();
        } else {
            alert(result.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error al remover requerimiento');
    }
}

// === GESTIÓN DE DOCUMENTOS DEL PROYECTO ===

document.addEventListener('DOMContentLoaded', function() {
    loadProjectDocuments();
});

function loadProjectDocuments() {
    const projectId = <?= $project['id'] ?>;
    
    fetch(`/documents/list?project_id=${projectId}`, {
        credentials: 'same-origin'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderProjectDocuments(data.documents);
            } else {
                showProjectDocumentError('Error al cargar documentos');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showProjectDocumentError('Error de conexión');
        });
}

function renderProjectDocuments(documents) {
    const container = document.getElementById('projectDocumentsList');
    
    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 técnicos cargados</p>
                <p class="text-sm mt-1">Sube manuales técnicos, documentación de API, etc.</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">${escapeHtml(doc.title)}</h4>
                        ${doc.description ? `<p class="text-sm text-gray-600 mb-2">${escapeHtml(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>${escapeHtml(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>
                    </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>
                        
                        ${isAdmin ? `
                            <button onclick="deleteProjectDocument(${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 showUploadProjectDocumentModal() {
    const html = `
        <div id="uploadProjectDocumentModal" 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="hideUploadProjectDocumentModal()"></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="uploadProjectDocumentForm" onsubmit="uploadProjectDocument(event)">
                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        <input type="hidden" name="project_id" value="<?= $project['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 Documentación Técnica
                            </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="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: Manual Técnico - Módulo de Matrículas"
                                           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>
                        </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="hideUploadProjectDocumentModal()" 
                                    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 hideUploadProjectDocumentModal() {
    const modal = document.getElementById('uploadProjectDocumentModal');
    if (modal) modal.remove();
}

function uploadProjectDocument(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 PROJECT 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) {
            hideUploadProjectDocumentModal();
            loadProjectDocuments();
            showSuccessMessage('Documento subido correctamente');
        } 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 deleteProjectDocument(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) {
            loadProjectDocuments();
            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 showProjectDocumentError(message) {
    const container = document.getElementById('projectDocumentsList');
    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';
?>
