<?php
$title = 'Reportes y Métricas - Sistema de Gestión de Proyectos';
$page_title = 'Reportes y Métricas';
$current_page = 'reports';
$showSidebar = true;

ob_start();
?>

<div class="max-w-7xl mx-auto">
    <!-- Header -->
    <div class="mb-6">
        <h2 class="text-2xl font-bold text-gray-900">📊 Reportes y Métricas del Área TI</h2>
        <p class="text-gray-600 mt-1">Indicadores de desempeño y análisis de productividad</p>
    </div>

    <!-- Filtros de Fecha -->
    <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="flex items-center gap-4">
            <div class="flex-1">
                <label class="block text-sm font-medium text-gray-700 mb-1">Fecha Inicio</label>
                <input type="date" id="start_date" value="<?= htmlspecialchars($start_date) ?>"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div class="flex-1">
                <label class="block text-sm font-medium text-gray-700 mb-1">Fecha Fin</label>
                <input type="date" id="end_date" value="<?= htmlspecialchars($end_date) ?>"
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div class="pt-6">
                <button onclick="loadMetrics()" class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                    <i class="fas fa-sync mr-2"></i>Actualizar
                </button>
            </div>
        </div>
    </div>

    <!-- Loading State -->
    <div id="loading" class="text-center py-12">
        <i class="fas fa-spinner fa-spin text-4xl text-blue-600"></i>
        <p class="text-gray-600 mt-4">Cargando métricas...</p>
    </div>

    <!-- Metrics Content (se llenará dinámicamente) -->
    <div id="metrics-content" class="hidden space-y-6">
        
        <!-- KPIs Principales -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4" id="main-kpis">
            <!-- Se llenará con JavaScript -->
        </div>

        <!-- Requerimientos -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-inbox mr-2 text-blue-600"></i>Requerimientos
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <canvas id="requirementsByTypeChart"></canvas>
                </div>
                <div>
                    <canvas id="requirementsByStatusChart"></canvas>
                </div>
            </div>
            
            <div class="mt-6">
                <h4 class="font-medium text-gray-900 mb-3">Tiempo Promedio de Resolución por Tipo</h4>
                <div id="avg-time-table"></div>
            </div>
        </div>

        <!-- Proyectos -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-project-diagram mr-2 text-green-600"></i>Proyectos Activos
            </h3>
            <div id="active-projects-table"></div>
        </div>

        <!-- Velocidad del Equipo -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-tachometer-alt mr-2 text-purple-600"></i>Velocidad del Equipo
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <div class="text-center mb-4">
                        <div class="text-4xl font-bold text-purple-600" id="avg-velocity">--</div>
                        <p class="text-sm text-gray-600">Velocidad Promedio (pts/día)</p>
                    </div>
                    <canvas id="velocityTrendChart"></canvas>
                </div>
                <div id="sprint-metrics">
                    <!-- Se llenará con JavaScript -->
                </div>
            </div>
        </div>

        <!-- Carga de Trabajo del Equipo -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-users mr-2 text-orange-600"></i>Carga de Trabajo del Equipo
            </h3>
            <div id="team-workload-table"></div>
        </div>

        <!-- Productividad -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-chart-line mr-2 text-indigo-600"></i>Productividad (Tareas Completadas)
            </h3>
            <div id="productivity-table"></div>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
let charts = {};

// Cargar métricas al iniciar
document.addEventListener('DOMContentLoaded', function() {
    loadMetrics();
});

async function loadMetrics() {
    const startDate = document.getElementById('start_date').value;
    const endDate = document.getElementById('end_date').value;
    
    document.getElementById('loading').classList.remove('hidden');
    document.getElementById('metrics-content').classList.add('hidden');
    
    try {
        const response = await fetch(`/reports/metrics?start_date=${startDate}&end_date=${endDate}`);
        const result = await response.json();
        
        if (result.success) {
            renderMetrics(result.metrics);
            document.getElementById('loading').classList.add('hidden');
            document.getElementById('metrics-content').classList.remove('hidden');
        } else {
            alert('Error al cargar métricas');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error al cargar métricas');
    }
}

function renderMetrics(metrics) {
    // KPIs Principales
    renderMainKPIs(metrics);
    
    // Requerimientos
    renderRequirementsCharts(metrics.requirements);
    renderAvgTimeTable(metrics.requirements.avg_time);
    
    // Proyectos
    renderActiveProjectsTable(metrics.projects.active_projects);
    
    // Sprints y Velocidad
    renderSprintMetrics(metrics.sprints);
    
    // Equipo
    renderTeamWorkload(metrics.team.workload);
    renderProductivity(metrics.team.productivity);
}

function renderMainKPIs(metrics) {
    const kpis = `
        <div class="bg-blue-50 rounded-lg p-4">
            <div class="text-3xl font-bold text-blue-700">${metrics.requirements.total}</div>
            <div class="text-sm text-blue-600">Requerimientos</div>
            <div class="text-xs text-blue-500 mt-1">en el período</div>
        </div>
        <div class="bg-green-50 rounded-lg p-4">
            <div class="text-3xl font-bold text-green-700">${metrics.projects.total}</div>
            <div class="text-sm text-green-600">Proyectos</div>
            <div class="text-xs text-green-500 mt-1">${metrics.projects.avg_progress.toFixed(1)}% promedio</div>
        </div>
        <div class="bg-purple-50 rounded-lg p-4">
            <div class="text-3xl font-bold text-purple-700">${metrics.sprints.avg_velocity.toFixed(2)}</div>
            <div class="text-sm text-purple-600">Velocidad</div>
            <div class="text-xs text-purple-500 mt-1">pts/día promedio</div>
        </div>
        <div class="bg-orange-50 rounded-lg p-4">
            <div class="text-3xl font-bold text-orange-700">${metrics.team.workload.length}</div>
            <div class="text-sm text-orange-600">Miembros</div>
            <div class="text-xs text-orange-500 mt-1">del equipo activos</div>
        </div>
    `;
    
    document.getElementById('main-kpis').innerHTML = kpis;
}

function renderRequirementsCharts(requirements) {
    // Por Tipo
    const typeLabels = requirements.by_type.map(item => {
        const labels = {
            'incident': 'Incidente',
            'support': 'Soporte',
            'improvement': 'Mejora',
            'project_minor': 'Proyecto Menor',
            'project_major': 'Proyecto Mayor'
        };
        return labels[item.type] || item.type;
    });
    const typeData = requirements.by_type.map(item => item.count);
    
    if (charts.typeChart) charts.typeChart.destroy();
    const typeCtx = document.getElementById('requirementsByTypeChart').getContext('2d');
    charts.typeChart = new Chart(typeCtx, {
        type: 'doughnut',
        data: {
            labels: typeLabels,
            datasets: [{
                data: typeData,
                backgroundColor: [
                    'rgb(239, 68, 68)',
                    'rgb(59, 130, 246)',
                    'rgb(34, 197, 94)',
                    'rgb(168, 85, 247)',
                    'rgb(99, 102, 241)'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                },
                title: {
                    display: true,
                    text: 'Requerimientos por Tipo'
                }
            }
        }
    });
    
    // Por Estado
    const statusLabels = requirements.by_status.map(item => {
        const labels = {
            'new': 'Nuevo',
            'classified': 'Clasificado',
            'in_analysis': 'En Análisis',
            'approved': 'Aprobado',
            'in_development': 'En Desarrollo',
            'in_testing': 'En Pruebas',
            'completed': 'Completado',
            'rejected': 'Rechazado'
        };
        return labels[item.status] || item.status;
    });
    const statusData = requirements.by_status.map(item => item.count);
    
    if (charts.statusChart) charts.statusChart.destroy();
    const statusCtx = document.getElementById('requirementsByStatusChart').getContext('2d');
    charts.statusChart = new Chart(statusCtx, {
        type: 'bar',
        data: {
            labels: statusLabels,
            datasets: [{
                label: 'Cantidad',
                data: statusData,
                backgroundColor: 'rgb(59, 130, 246)'
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                },
                title: {
                    display: true,
                    text: 'Requerimientos por Estado'
                }
            }
        }
    });
}

function renderAvgTimeTable(avgTime) {
    if (!avgTime || avgTime.length === 0) {
        document.getElementById('avg-time-table').innerHTML = '<p class="text-gray-500 text-sm">No hay datos suficientes</p>';
        return;
    }
    
    const typeLabels = {
        'incident': 'Incidente',
        'support': 'Soporte',
        'improvement': 'Mejora',
        'project_minor': 'Proyecto Menor',
        'project_major': 'Proyecto Mayor'
    };
    
    const html = `
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Tipo</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Tiempo Promedio</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                ${avgTime.map(item => `
                    <tr>
                        <td class="px-4 py-2 text-sm text-gray-900">${typeLabels[item.type] || item.type}</td>
                        <td class="px-4 py-2 text-sm text-gray-600">${Math.round(item.avg_days)} días</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    
    document.getElementById('avg-time-table').innerHTML = html;
}

function renderActiveProjectsTable(projects) {
    if (!projects || projects.length === 0) {
        document.getElementById('active-projects-table').innerHTML = '<p class="text-gray-500 text-sm">No hay proyectos activos en este período</p>';
        return;
    }
    
    const html = `
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Código</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Proyecto</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Estado</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Progreso</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Responsable</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                ${projects.map(project => `
                    <tr>
                        <td class="px-4 py-2 text-sm font-mono text-gray-900">${project.code}</td>
                        <td class="px-4 py-2 text-sm text-gray-900">${project.name}</td>
                        <td class="px-4 py-2 text-sm">
                            <span class="px-2 py-1 text-xs font-semibold rounded-full ${
                                project.status === 'in_progress' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'
                            }">${project.status === 'in_progress' ? 'En Progreso' : 'Planificación'}</span>
                        </td>
                        <td class="px-4 py-2 text-sm text-gray-600">
                            <div class="flex items-center">
                                <div class="w-full bg-gray-200 rounded-full h-2 mr-2">
                                    <div class="bg-blue-600 h-2 rounded-full" style="width: ${project.progress_percentage}%"></div>
                                </div>
                                <span class="text-xs">${project.progress_percentage}%</span>
                            </div>
                        </td>
                        <td class="px-4 py-2 text-sm text-gray-600">${project.manager || 'N/A'}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    
    document.getElementById('active-projects-table').innerHTML = html;
}

function renderSprintMetrics(sprints) {
    document.getElementById('avg-velocity').textContent = sprints.avg_velocity.toFixed(2);
    
    // Gráfico de tendencia de velocidad
    if (sprints.completed_sprints.length > 0) {
        const labels = sprints.completed_sprints.map(s => s.name);
        const data = sprints.completed_sprints.map(s => {
            const start = new Date(s.start_date);
            const end = new Date(s.end_date);
            const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
            return days > 0 ? (s.completed_points / days).toFixed(2) : 0;
        });
        
        if (charts.velocityChart) charts.velocityChart.destroy();
        const ctx = document.getElementById('velocityTrendChart').getContext('2d');
        charts.velocityChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Velocidad (pts/día)',
                    data: data,
                    borderColor: 'rgb(168, 85, 247)',
                    backgroundColor: 'rgba(168, 85, 247, 0.1)',
                    tension: 0.3,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Tendencia de Velocidad'
                    }
                }
            }
        });
    }
    
    // Información del sprint actual
    let sprintHtml = '<p class="text-gray-500 text-sm">No hay sprint activo actualmente</p>';
    
    if (sprints.current_sprint) {
        const sprint = sprints.current_sprint;
        const progress = sprint.total_points > 0 
            ? ((sprint.completed_points / sprint.total_points) * 100).toFixed(1)
            : 0;
        
        sprintHtml = `
            <div class="border border-purple-200 rounded-lg p-4">
                <h4 class="font-medium text-gray-900 mb-2">${sprint.name}</h4>
                <p class="text-sm text-gray-600 mb-2">${sprint.project_name}</p>
                <div class="space-y-2 text-sm">
                    <div class="flex justify-between">
                        <span class="text-gray-600">Story Points:</span>
                        <span class="font-medium">${sprint.completed_points || 0} / ${sprint.total_points || 0}</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div class="bg-purple-600 h-2 rounded-full" style="width: ${progress}%"></div>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Progreso:</span>
                        <span class="font-medium text-purple-600">${progress}%</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    document.getElementById('sprint-metrics').innerHTML = sprintHtml;
}

function renderTeamWorkload(workload) {
    const teamLabels = {
        'support': 'Soporte',
        'automation': 'Automatización',
        'erp_projects': 'Proyectos ERP',
        'infrastructure': 'Infraestructura'
    };
    
    const html = `
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Usuario</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Equipo</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Requerimientos</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Items Backlog</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Horas Est.</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                ${workload.map(user => `
                    <tr>
                        <td class="px-4 py-2 text-sm text-gray-900">${user.name}</td>
                        <td class="px-4 py-2 text-sm text-gray-600">${teamLabels[user.team] || user.team || 'N/A'}</td>
                        <td class="px-4 py-2 text-sm text-center">${user.requirements_assigned || 0}</td>
                        <td class="px-4 py-2 text-sm text-center">${user.backlog_items_assigned || 0}</td>
                        <td class="px-4 py-2 text-sm text-center">${(user.estimated_hours || 0).toFixed(1)}h</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    
    document.getElementById('team-workload-table').innerHTML = html;
}

function renderProductivity(productivity) {
    if (!productivity || productivity.length === 0) {
        document.getElementById('productivity-table').innerHTML = '<p class="text-gray-500 text-sm">No hay datos de productividad en este período</p>';
        return;
    }
    
    const html = `
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Usuario</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Tareas Completadas</th>
                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Horas Trabajadas</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                ${productivity.map(user => `
                    <tr>
                        <td class="px-4 py-2 text-sm text-gray-900">${user.name}</td>
                        <td class="px-4 py-2 text-sm text-center font-medium text-green-600">${user.tasks_completed}</td>
                        <td class="px-4 py-2 text-sm text-center text-gray-600">${(user.hours_worked || 0).toFixed(1)}h</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;
    
    document.getElementById('productivity-table').innerHTML = html;
}
</script>

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