<?php 
error_reporting(E_ALL & ~E_NOTICE); 
extract($_REQUEST, EXTR_PREFIX_ALL, "P");
extract($_REQUEST, EXTR_PREFIX_ALL, "G");

// Start session at the beginning of the file
session_start();
error_reporting(E_ALL & ~E_NOTICE); 
include_once "utils_database.php";
include_once "utils.php";
require_once "session_check.php";

// Extract request variables with prefix
$prefix = "P";
foreach ($_REQUEST as $key => $value) {
    $varname = $prefix . '_' . $key;
    $$varname = $value;
}



// Get user information if logged in
$vAreasUsuario = isset($_SESSION['usr']) ? getDatUser($_SESSION['usr'], 9) : '';
$vTipo = isset($_SESSION['usr']) ? getDatUser($_SESSION['usr'], 2) : '';
$vIdUsr = isset($_SESSION['usr']) ? getDatUser($_SESSION['usr'], 1) : '';


// Verificar si el usuario está logueado
if (!isset($_SESSION['usr'])) {
    // Usuario no logueado, redirigir a la página de login
    header("Location: login.php");
    exit(); // Importante: detener la ejecución después de la redirección
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Panamtrauma 2025 - Evaluator List">
    <meta name="author" content="Panamtrauma">
    <title>Panamtrauma 2025 - Evaluators</title>
    
    <!-- CSS Libraries -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
    
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #34495e;
            --accent-color: #3498db;
            --background-color: #f4f6f7;
            --card-shadow: 0 10px 25px rgba(0,0,0,0.1);
            --transition-speed: 0.3s;
            --inactive-color: #dc3545;
        }

        * {
            box-sizing: border-box;
            transition: all var(--transition-speed) ease;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--background-color);
            color: #2c3e50;
            line-height: 1.6;
        }

        .page-header {
            background-color: white;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
            padding: 1rem 0;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 1000;
        }

        .evaluator-container {
            max-width: 1200px;
            margin: 100px auto 2rem;
            padding: 0 15px;
        }

        .evaluator-title {
            text-align: center;
            margin-bottom: 2rem;
            color: var(--primary-color);
            font-weight: 700;
            letter-spacing: -0.5px;
        }

        .dashboard-container {
            background-color: white;
            border-radius: 12px;
            margin-bottom: 2rem;
            box-shadow: var(--card-shadow);
            padding: 1.5rem;
        }

        .dashboard-title {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid var(--accent-color);
            padding-bottom: 0.5rem;
        }

        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .stat-card {
            background-color: var(--secondary-color);
            color: white;
            border-radius: 10px;
            padding: 1.25rem;
            text-align: center;
            position: relative;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 50%);
        }

        .stat-icon {
            font-size: 2rem;
            margin-bottom: 0.75rem;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            margin: 0;
        }

        .stat-label {
            font-size: 0.9rem;
            opacity: 0.8;
            margin: 0.5rem 0 0;
        }

        .chart-container {
            background-color: white;
            border-radius: 10px;
            padding: 1.25rem;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            height: 300px;
            position: relative;
        }

        .chart-title {
            color: var(--primary-color);
            font-weight: 600;
            text-align: center;
            margin-bottom: 1rem;
        }

        .evaluator-card {
            background-color: white;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            box-shadow: var(--card-shadow);
            overflow: hidden;
        }

        .evaluator-header {
            display: flex;
            align-items: center;
            padding: 1rem 1.5rem;
            background-color: var(--secondary-color);
            color: white;
            cursor: pointer;
        }

        .evaluator-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 1rem;
            border: 3px solid var(--accent-color);
        }

        .evaluator-info {
            flex-grow: 1;
            display: flex;
            align-items: center;
        }

        .evaluator-name {
            font-weight: 600;
            font-size: 1.1rem;
            margin-right: 1rem;
        }

        .evaluator-id {
            background-color: var(--accent-color);
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.8rem;
            margin-right: 1rem;
        }

        .country-flag {
            width: 30px;
            height: 20px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 0.5rem;
        }

        .expand-icon {
            font-size: 1.2rem;
            color: white;
            transition: transform var(--transition-speed);
        }

        .expand-icon.rotated {
            transform: rotate(180deg);
        }

        .evaluator-details {
            display: none;
            background-color: #f9f9f9;
        }

        .details-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
            padding: 1.5rem;
        }

        .detail-section {
            background-color: white;
            border-radius: 8px;
            padding: 1rem;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }

        .detail-title {
            font-weight: 600;
            color: var(--secondary-color);
            margin-bottom: 0.75rem;
            border-bottom: 2px solid var(--accent-color);
            padding-bottom: 0.5rem;
        }

        .assignments-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
            gap: 0.5rem;
        }

        .assignment-item {
            text-align: center;
            padding: 0.5rem;
            border-radius: 6px;
            font-weight: 500;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .assignment-item.pending {
            background-color: #f1f3f4;
            color: #5f6368;
        }

        .assignment-item.completed {
            background-color: var(--accent-color);
            color: white;
        }

        .assignment-item:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }

        /* Inactive Evaluator Styles */
        .evaluator-card.inactive {
            border: 2px solid var(--inactive-color);
            opacity: 0.7;
        }

        .evaluator-header.inactive {
            background-color: var(--inactive-color);
        }

        .inactive-badge {
            background-color: var(--inactive-color);
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            margin-left: 0.5rem;
            font-size: 0.8rem;
        }

        @media (max-width: 768px) {
            .evaluator-header {
                flex-direction: column;
                text-align: center;
            }

            .evaluator-avatar {
                margin-right: 0;
                margin-bottom: 1rem;
            }

            .details-grid {
                grid-template-columns: 1fr;
            }

            .dashboard-grid {
                grid-template-columns: 1fr;
            }
        }

        .no-evaluators {
            text-align: center;
            color: var(--secondary-color);
            padding: 2rem;
            background-color: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
        }
    </style>
    <!-- Header con botones de navegación y exportación -->
<header class="page-header">
    <div class="container d-flex justify-content-between align-items-center">
        <div class="nav-buttons">
            <a href="index.php" class="btn btn-primary btn-lg me-2">
                <i class="fas fa-home me-2"></i>Home
            </a>
            <a href="logout.php" class="btn btn-danger btn-lg">
                <i class="fas fa-sign-out-alt me-2"></i>Cerrar Sesión
            </a>
        </div>
        <div class="export-buttons">
            <button id="export-excel" class="btn btn-success btn-lg me-2">
                <i class="fas fa-file-excel me-2"></i>Exportar Excel
            </button>
            <button id="export-pdf" class="btn btn-danger btn-lg">
                <i class="fas fa-file-pdf me-2"></i>Exportar PDF
            </button>
        </div>
    </div>
</header>

<!-- Estilos adicionales para los botones del header -->
<style>
    .page-header {
        padding: 1rem 0;
        background-color: white;
        box-shadow: 0 2px 15px rgba(0,0,0,0.05);
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        z-index: 1000;
    }
    
    .nav-buttons .btn, .export-buttons .btn {
        font-weight: 600;
        border-radius: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    
    .nav-buttons .btn:hover, .export-buttons .btn:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 10px rgba(0,0,0,0.15);
    }
    
    .btn-primary {
        background-color: var(--accent-color);
        border-color: var(--accent-color);
    }
    
    .btn-primary:hover {
        background-color: #2980b9;
        border-color: #2980b9;
    }
    
    .btn-danger {
        background-color: #e74c3c;
        border-color: #e74c3c;
    }
    
    .btn-danger:hover {
        background-color: #c0392b;
        border-color: #c0392b;
    }
    
    .btn-success {
        background-color: #2ecc71;
        border-color: #2ecc71;
    }
    
    .btn-success:hover {
        background-color: #27ae60;
        border-color: #27ae60;
    }
    
    @media (max-width: 768px) {
        .page-header .container {
            flex-direction: column;
            padding: 1rem;
        }
        
        .nav-buttons, .export-buttons {
            width: 100%;
            display: flex;
            justify-content: center;
            margin-bottom: 0.5rem;
        }
        
        .evaluator-container {
            margin-top: 140px; /* Ajustar para acomodar el header más alto en móviles */
        }
    }
</style>

<!-- JavaScript para los botones de exportación -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>

<script>
// Función para exportar directamente a PDF usando jsPDF sin html2pdf
function exportToPDF() {
    // Mostrar mensaje de carga
    showExportMessage('Generando PDF...');
    
    try {
        // Verificar que jsPDF esté disponible
        if (typeof window.jspdf === 'undefined') {
            // Si no está disponible, cargar dinámicamente
            const script1 = document.createElement('script');
            script1.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js';
            
            script1.onload = function() {
                // Cargar el plugin autotable después
                const script2 = document.createElement('script');
                script2.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js';
                script2.onload = generatePDFWithTable;
                document.head.appendChild(script2);
            };
            
            document.head.appendChild(script1);
        } else {
            // Si ya está disponible, continuar
            generatePDFWithTable();
        }
    } catch (error) {
        console.error('Error al inicializar PDF:', error);
        hideExportMessage();
        alert('Hubo un error al generar el PDF. Por favor, intente nuevamente.');
    }
}

// Generación de PDF usando autotable con contenido centrado
function generatePDFWithTable() {
    try {
        // Crear instancia de jsPDF
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF({
            orientation: 'landscape',
            unit: 'mm',
            format: 'a4'
        });
        
        // Constantes para posicionamiento
        const pageWidth = doc.internal.pageSize.getWidth();
        const pageHeight = doc.internal.pageSize.getHeight();
        const margin = 15; // Aumentar margen para mejor centrado
        const contentWidth = pageWidth - (margin * 2);
        
        // Centrar título y encabezados
        doc.setFontSize(20); // Título más grande
        doc.setTextColor(44, 62, 80); // #2c3e50
        doc.setFont('helvetica', 'bold');
        
        // Título del documento centrado y con más espaciado
        doc.text('Lista de Evaluadores - Panamtrauma 2025', pageWidth / 2, margin + 10, { align: 'center' });
        
        // Línea separadora centrada
        doc.setDrawColor(52, 152, 219); // #3498db
        doc.setLineWidth(0.8); // Línea más gruesa
        doc.line(margin + 20, margin + 15, pageWidth - margin - 20, margin + 15);
        
        // Sección de estadísticas centrada
        doc.setFontSize(14);
        doc.setFont('helvetica', 'normal');
        doc.text('Resumen Estadístico', pageWidth / 2, margin + 25, { align: 'center' });
        
        // Cajas de estadísticas - Centradas y con mejor espaciado
        const statBoxWidth = 50;
        const statBoxGap = 15;
        const totalStatBoxesWidth = (statBoxWidth * 4) + (statBoxGap * 3);
        const startX = (pageWidth - totalStatBoxesWidth) / 2;
        
        // Primera caja - Azul
        doc.setFillColor(52, 152, 219); // #3498db
        doc.roundedRect(startX, margin + 30, statBoxWidth, 30, 3, 3, 'F');
        
        // Segunda caja - Verde
        doc.setFillColor(46, 204, 113); // #2ecc71
        doc.roundedRect(startX + statBoxWidth + statBoxGap, margin + 30, statBoxWidth, 30, 3, 3, 'F');
        
        // Tercera caja - Amarillo
        doc.setFillColor(243, 156, 18); // #f39c12
        doc.roundedRect(startX + (statBoxWidth * 2) + (statBoxGap * 2), margin + 30, statBoxWidth, 30, 3, 3, 'F');
        
        // Cuarta caja - Rojo
        doc.setFillColor(231, 76, 60); // #e74c3c
        doc.roundedRect(startX + (statBoxWidth * 3) + (statBoxGap * 3), margin + 30, statBoxWidth, 30, 3, 3, 'F');
        
        // Texto de estadísticas
        doc.setTextColor(255, 255, 255); // Blanco
        doc.setFontSize(18);
        doc.setFont('helvetica', 'bold');
        
        // Total evaluadores
        doc.text(document.getElementById('total-evaluators').textContent, startX + (statBoxWidth / 2), margin + 42, { align: 'center' });
        doc.setFontSize(8);
        doc.setFont('helvetica', 'normal');
        doc.text('Total Evaluadores', startX + (statBoxWidth / 2), margin + 50, { align: 'center' });
        
        // Total asignaciones
        doc.setFontSize(18);
        doc.setFont('helvetica', 'bold');
        doc.text(document.getElementById('total-assignments').textContent, startX + statBoxWidth + statBoxGap + (statBoxWidth / 2), margin + 42, { align: 'center' });
        doc.setFontSize(8);
        doc.setFont('helvetica', 'normal');
        doc.text('Total Asignaciones', startX + statBoxWidth + statBoxGap + (statBoxWidth / 2), margin + 50, { align: 'center' });
        
        // Evaluaciones completadas
        doc.setFontSize(18);
        doc.setFont('helvetica', 'bold');
        doc.text(document.getElementById('completed-evaluations').textContent, startX + (statBoxWidth * 2) + (statBoxGap * 2) + (statBoxWidth / 2), margin + 42, { align: 'center' });
        doc.setFontSize(8);
        doc.setFont('helvetica', 'normal');
        doc.text('Evaluaciones Completadas', startX + (statBoxWidth * 2) + (statBoxGap * 2) + (statBoxWidth / 2), margin + 50, { align: 'center' });
        
        // Porcentaje pendiente
        doc.setFontSize(18);
        doc.setFont('helvetica', 'bold');
        doc.text(document.getElementById('pending-percentage').textContent, startX + (statBoxWidth * 3) + (statBoxGap * 3) + (statBoxWidth / 2), margin + 42, { align: 'center' });
        doc.setFontSize(8);
        doc.setFont('helvetica', 'normal');
        doc.text('Evaluaciones Pendientes', startX + (statBoxWidth * 3) + (statBoxGap * 3) + (statBoxWidth / 2), margin + 50, { align: 'center' });
        
        // Recolectar datos para tabla
        const tableData = [];
        document.querySelectorAll('.evaluator-card').forEach(card => {
            const header = card.querySelector('.evaluator-header');
            const name = header.querySelector('.evaluator-name').textContent.trim();
            const id = header.querySelector('.evaluator-id').textContent.replace('ID:', '').trim();
            const assignmentInfo = header.querySelector('.ms-2')?.textContent.trim() || '';
            const isActive = !card.classList.contains('inactive');
            
            // Obtener más detalles si están disponibles
            let email = '', language = '', country = '';
            const details = card.querySelector('.evaluator-details');
            if (details) {
                const personalInfo = details.querySelector('.detail-section:nth-child(1)');
                if (personalInfo) {
                    const paragraphs = personalInfo.querySelectorAll('p');
                    if (paragraphs.length > 0) {
                        email = paragraphs[0].textContent.replace('Email:', '').trim();
                    }
                    if (paragraphs.length > 1) {
                        language = paragraphs[1].textContent.replace('Language:', '').trim();
                    }
                    if (paragraphs.length > 2) {
                        country = paragraphs[2].textContent.replace('Country:', '').trim();
                    }
                }
            }
            
            tableData.push([
                id,
                name,
                email,
                country,
                language,
                assignmentInfo,
                isActive ? 'Activo' : 'Inactivo'
            ]);
        });
        
        // Generar tabla con autoTable - Centrada con márgenes ajustados
        doc.autoTable({
            startY: margin + 70, // Más espacio superior
            margin: { left: margin + 5, right: margin + 5 }, // Márgenes laterales adicionales para centrar
            head: [['ID', 'Nombre', 'Email', 'País', 'Idioma', 'Asignaciones', 'Estado']],
            body: tableData,
            theme: 'grid',
            styles: {
                fontSize: 9, // Tamaño de fuente algo mayor
                cellPadding: 3, // Más relleno para celdas
                lineColor: [200, 200, 200],
                lineWidth: 0.1,
                halign: 'center', // Centra todo el texto por defecto
                valign: 'middle', // Alinea verticalmente al centro
                font: 'helvetica',
            },
            headStyles: {
                fillColor: [52, 73, 94], // #34495e
                textColor: [255, 255, 255],
                fontStyle: 'bold',
                halign: 'center',
                fontSize: 10 // Encabezados con texto más grande
            },
            columnStyles: {
                0: { cellWidth: 15, halign: 'center' }, // ID
                1: { cellWidth: 55, halign: 'left' },   // Nombre
                2: { cellWidth: 60, halign: 'left' },   // Email
                3: { cellWidth: 20, halign: 'center' }, // País
                4: { cellWidth: 20, halign: 'center' }, // Idioma
                5: { cellWidth: 35, halign: 'center' }, // Asignaciones
                6: { cellWidth: 20, halign: 'center' }  // Estado
            },
            alternateRowStyles: {
                fillColor: [245, 246, 247]
            },
            // Colorear el texto de estado según si está activo o inactivo
            didDrawCell: function(data) {
                if (data.column.index === 6 && data.row.index >= 0 && data.section === 'body') {
                    const cell = data.cell;
                    const value = data.cell.raw;
                    
                    if (value === 'Activo') {
                        doc.setTextColor(46, 204, 113); // Verde
                        doc.setFont('helvetica', 'bold');
                    } else {
                        doc.setTextColor(231, 76, 60); // Rojo
                        doc.setFont('helvetica', 'bold');
                    }
                    
                    // Dibujar el texto manualmente
                    doc.text(value, cell.x + cell.width / 2, cell.y + cell.height / 2, {
                        align: 'center',
                        baseline: 'middle'
                    });
                    
                    // No dibujar el texto original
                    data.cell.text = '';
                    
                    // Restaurar color de texto y fuente
                    doc.setTextColor(44, 62, 80);
                    doc.setFont('helvetica', 'normal');
                }
            }
        });
        
        // Pie de página con fecha de generación
        const totalPages = doc.internal.getNumberOfPages();
        for (let i = 1; i <= totalPages; i++) {
            doc.setPage(i);
            doc.setFontSize(8);
            doc.setTextColor(128, 128, 128);
            
            // Fecha de generación
            const today = new Date();
            const dateStr = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
            doc.text('Generado el: ' + dateStr, margin, pageHeight - 5);
            
            // Número de página
            doc.text('Página ' + i + ' de ' + totalPages, pageWidth - margin, pageHeight - 5, { align: 'right' });
            
            // Línea de pie de página centrada
            doc.setDrawColor(200, 200, 200);
            doc.setLineWidth(0.3);
            doc.line(margin + 20, pageHeight - 10, pageWidth - margin - 20, pageHeight - 10);
        }
        
        // Guardar el PDF
        doc.save('evaluadores_panamtrauma.pdf');
        
        // Ocultar mensaje de carga
        hideExportMessage();
        
    } catch (error) {
        console.error('Error al generar PDF con tabla:', error);
        hideExportMessage();
        alert('Hubo un error al generar el PDF. Por favor, intente nuevamente.');
    }
}

// Funciones para mostrar/ocultar mensaje de carga durante exportación
function showExportMessage(message) {
    // Crear overlay para mensaje de carga
    const overlay = document.createElement('div');
    overlay.id = 'export-overlay';
    overlay.style.position = 'fixed';
    overlay.style.top = '0';
    overlay.style.left = '0';
    overlay.style.width = '100%';
    overlay.style.height = '100%';
    overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    overlay.style.display = 'flex';
    overlay.style.justifyContent = 'center';
    overlay.style.alignItems = 'center';
    overlay.style.zIndex = '9999';
    
    // Contenido del mensaje
    overlay.innerHTML = `
        <div style="background-color: white; padding: 20px; border-radius: 10px; text-align: center;">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <h4>${message}</h4>
            <p>Por favor espere...</p>
        </div>
    `;
    
    document.body.appendChild(overlay);
}

function hideExportMessage() {
    const overlay = document.getElementById('export-overlay');
    if (overlay) {
        document.body.removeChild(overlay);
    }
}

// Función de exportación a Excel optimizada
function exportToExcel() {
    // Mostrar mensaje de carga
    showExportMessage('Generando archivo Excel...');
    
    // Preparar datos de evaluadores
    let evaluatorsData = [];
    document.querySelectorAll('.evaluator-card').forEach(card => {
        const header = card.querySelector('.evaluator-header');
        const name = header.querySelector('.evaluator-name').textContent.trim();
        const id = header.querySelector('.evaluator-id').textContent.replace('ID:', '').trim();
        const assignmentInfo = header.querySelector('.ms-2')?.textContent.trim() || '';
        const isActive = !card.classList.contains('inactive');
        
        // Expandir detalles para obtener información
        let email = '', country = '', language = '';
        let areas = [];
        let assignments = [];
        
        const details = card.querySelector('.evaluator-details');
        if (details) {
            const emailEl = details.querySelector('p:nth-child(1)');
            if (emailEl) email = emailEl.textContent.replace('Email:', '').trim();
            
            const langEl = details.querySelector('p:nth-child(2)');
            if (langEl) language = langEl.textContent.replace('Language:', '').trim();
            
            const countryEl = details.querySelector('p:nth-child(3)');
            if (countryEl) country = countryEl.textContent.replace('Country:', '').trim();
            
            // Extraer áreas temáticas
            details.querySelectorAll('.detail-section:nth-child(2) li').forEach(li => {
                areas.push(li.textContent.trim());
            });
            
            // Extraer asignaciones
            details.querySelectorAll('.assignment-item').forEach(item => {
                assignments.push({
                    code: item.textContent.trim(),
                    evaluated: item.classList.contains('completed')
                });
            });
        }
        
        evaluatorsData.push({
            id,
            name,
            email,
            country,
            language,
            status: isActive ? 'Activo' : 'Inactivo',
            assignmentInfo,
            thematicAreas: areas,
            assignments: assignments
        });
    });
    
    // Crear contenido CSV
    let csvContent = "data:text/csv;charset=utf-8,";
    
    // Encabezados
    csvContent += "ID,Nombre,Email,País,Idioma,Estado,Total Asignaciones,Evaluaciones Completadas,Áreas Temáticas\r\n";
    
    // Datos
    evaluatorsData.forEach(eval => {
        const completedCount = eval.assignments.filter(a => a.evaluated).length;
        const row = [
            eval.id,
            `"${eval.name}"`,
            `"${eval.email}"`,
            `"${eval.country}"`,
            `"${eval.language}"`,
            eval.status,
            eval.assignments.length,
            completedCount,
            `"${eval.thematicAreas.join('; ')}"`
        ];
        csvContent += row.join(',') + "\r\n";
    });
    
    // Crear enlace de descarga
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "evaluadores_panamtrauma.csv");
    document.body.appendChild(link);
    
    // Simular retardo para mostrar mensaje de carga
    setTimeout(() => {
        hideExportMessage();
        link.click();
        document.body.removeChild(link);
    }, 1000);
}

// Agregar event listeners a los botones
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('export-excel').addEventListener('click', exportToExcel);
    document.getElementById('export-pdf').addEventListener('click', exportToPDF);
});

// Funciones para mostrar/ocultar mensaje de carga durante exportación
function showExportMessage(message) {
    // Crear overlay para mensaje de carga
    const overlay = document.createElement('div');
    overlay.id = 'export-overlay';
    overlay.style.position = 'fixed';
    overlay.style.top = '0';
    overlay.style.left = '0';
    overlay.style.width = '100%';
    overlay.style.height = '100%';
    overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    overlay.style.display = 'flex';
    overlay.style.justifyContent = 'center';
    overlay.style.alignItems = 'center';
    overlay.style.zIndex = '9999';
    
    // Contenido del mensaje
    overlay.innerHTML = `
        <div style="background-color: white; padding: 20px; border-radius: 10px; text-align: center;">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <h4>${message}</h4>
            <p>Por favor espere...</p>
        </div>
    `;
    
    document.body.appendChild(overlay);
}

function hideExportMessage() {
    const overlay = document.getElementById('export-overlay');
    if (overlay) {
        document.body.removeChild(overlay);
    }
}

// Agregar event listeners a los botones
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('export-excel').addEventListener('click', exportToExcel);
    document.getElementById('export-pdf').addEventListener('click', exportToPDF);
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
</head>
<body>
    <!-- Header -->

    <!-- Main Content -->
    <section class="evaluator-container">
        <h1 class="evaluator-title">
            <i class="fas fa-user-check me-2"></i>Evaluator List by Country
        </h1>

        <!-- Dashboard Section -->
        <div class="dashboard-container">
            <h2 class="dashboard-title">
                <i class="fas fa-chart-line me-2"></i>Dashboard Estadístico
            </h2>
            
            <!-- Stats Overview -->
            <div class="dashboard-grid">
                <div class="stat-card" style="background-color: #3498db;">
                    <i class="fas fa-users stat-icon"></i>
                    <p class="stat-value" id="total-evaluators">0</p>
                    <p class="stat-label">Total Evaluadores</p>
                </div>
                
                <div class="stat-card" style="background-color: #2ecc71;">
                    <i class="fas fa-file-alt stat-icon"></i>
                    <p class="stat-value" id="total-assignments">0</p>
                    <p class="stat-label">Total Asignaciones</p>
                </div>
                
                <div class="stat-card" style="background-color: #f39c12;">
                    <i class="fas fa-check-circle stat-icon"></i>
                    <p class="stat-value" id="completed-evaluations">0</p>
                    <p class="stat-label">Evaluaciones Completadas</p>
                </div>
                
                <div class="stat-card" style="background-color: #e74c3c;">
                    <i class="fas fa-clock stat-icon"></i>
                    <p class="stat-value" id="pending-percentage">0%</p>
                    <p class="stat-label">Evaluaciones Pendientes</p>
                </div>
            </div>
            
            <!-- Charts Row -->
            <div class="dashboard-grid">
                <div class="chart-container">
                    <h3 class="chart-title">Evaluación por País</h3>
                    <canvas id="country-chart" style="max-height: 220px;"></canvas>
                </div>
                
                <div class="chart-container">
                    <h3 class="chart-title">Estado de Evaluaciones</h3>
                    <canvas id="evaluation-status-chart" style="max-height: 220px;"></canvas>
                </div>
            </div>
        </div>

        <?php
        // Get all evaluators, both active and inactive
        $vEvaluadores = GetFile("tusuario", "tipousuario='E'", "nombre");
        $counter = 0;
        
        // Arrays for dashboard stats
        $totalEvaluators = 0;
        $totalAssignments = 0;
        $completedEvaluations = 0;
        $countryStats = [];
        $evaluationStatusData = [0, 0]; // [Completed, Pending]
        $pendingPercentage = 0;

        if (mysqli_num_rows($vEvaluadores) > 0) {
            while ($vEvaluador = mysqli_fetch_assoc($vEvaluadores)) {
                $counter++;
                $totalEvaluators++;
                $vDiv_Evaluador = "evaluator_" . $vEvaluador['id'];
                
                // Determine active status
                $isActive = $vEvaluador['activo'] == 1;
                
                // Use avatar from database with specified path, fallback to UI Avatars
                $avatarUrl = !empty($vEvaluador['avatar']) 
                    ? "dist/pages/evaluadores/acciones_evaluador/fotos_empleados/" . htmlspecialchars($vEvaluador['avatar']) 
                    : "https://ui-avatars.com/api/?name=" . urlencode($vEvaluador['nombre']) . "&background=2c3e50&color=ffffff&size=60&rounded=true";
                
           // Mapeo de banderas de países
$countryFlagMap = [
    'AF' => 'af', 'AL' => 'al', 'DE' => 'de', 'AD' => 'ad', 'AO' => 'ao',
    'AI' => 'ai', 'AG' => 'ag', 'SA' => 'sa', 'DZ' => 'dz', 'AR' => 'ar',
    'AM' => 'am', 'AU' => 'au', 'AT' => 'at', 'AZ' => 'az', 'BS' => 'bs',
    'BD' => 'bd', 'BB' => 'bb', 'BH' => 'bh', 'BE' => 'be', 'BZ' => 'bz',
    'BJ' => 'bj', 'BY' => 'by', 'MM' => 'mm', 'BO' => 'bo', 'BA' => 'ba',
    'BW' => 'bw', 'BR' => 'br', 'BN' => 'bn', 'BG' => 'bg', 'BF' => 'bf',
    'BI' => 'bi', 'BT' => 'bt', 'CV' => 'cv', 'KH' => 'kh', 'CM' => 'cm',
    'CA' => 'ca', 'QA' => 'qa', 'TD' => 'td', 'CL' => 'cl', 'CN' => 'cn',
    'CY' => 'cy', 'VA' => 'va', 'CO' => 'co', 'KM' => 'km', 'CD' => 'cd',
    'CG' => 'cg', 'KR' => 'kr', 'CI' => 'ci', 'CR' => 'cr', 'HR' => 'hr',
    'CU' => 'cu', 'DK' => 'dk', 'DM' => 'dm', 'EC' => 'ec', 'EG' => 'eg',
    'SV' => 'sv', 'AE' => 'ae', 'ER' => 'er', 'SK' => 'sk', 'SI' => 'si',
    'ES' => 'es', 'US' => 'us', 'EE' => 'ee', 'ET' => 'et', 'PH' => 'ph',
    'FI' => 'fi', 'FJ' => 'fj', 'FR' => 'fr', 'GA' => 'ga', 'GM' => 'gm',
    'GE' => 'ge', 'GH' => 'gh', 'GD' => 'gd', 'GR' => 'gr', 'GT' => 'gt',
    'GN' => 'gn', 'GQ' => 'gq', 'GW' => 'gw', 'GY' => 'gy', 'HT' => 'ht',
    'HN' => 'hn', 'HU' => 'hu', 'IN' => 'in', 'ID' => 'id', 'IQ' => 'iq',
    'IR' => 'ir', 'IE' => 'ie', 'IS' => 'is', 'IL' => 'il', 'IT' => 'it',
    'JM' => 'jm', 'JP' => 'jp', 'JO' => 'jo', 'KZ' => 'kz', 'KE' => 'ke',
    'KG' => 'kg', 'KI' => 'ki', 'KW' => 'kw', 'LA' => 'la', 'LS' => 'ls',
    'LV' => 'lv', 'LB' => 'lb', 'LR' => 'lr', 'LY' => 'ly', 'LI' => 'li',
    'LT' => 'lt', 'LU' => 'lu', 'MG' => 'mg', 'MY' => 'my', 'MW' => 'mw',
    'MV' => 'mv', 'ML' => 'ml', 'MT' => 'mt', 'MA' => 'ma', 'MU' => 'mu',
    'MR' => 'mr', 'MX' => 'mx', 'FM' => 'fm', 'MD' => 'md', 'MC' => 'mc',
    'MN' => 'mn', 'ME' => 'me', 'MZ' => 'mz', 'NA' => 'na', 'NR' => 'nr',
    'NP' => 'np', 'NI' => 'ni', 'NE' => 'ne', 'NG' => 'ng', 'NO' => 'no',
    'NZ' => 'nz', 'OM' => 'om', 'NL' => 'nl', 'PK' => 'pk', 'PW' => 'pw',
    'PA' => 'pa', 'PG' => 'pg', 'PY' => 'py', 'PE' => 'pe', 'PL' => 'pl',
    'PT' => 'pt', 'GB' => 'gb', 'CF' => 'cf', 'CZ' => 'cz', 'DO' => 'do',
    'RE' => 're', 'RW' => 'rw', 'RO' => 'ro', 'RU' => 'ru', 'WS' => 'ws',
    'SM' => 'sm', 'ST' => 'st', 'SN' => 'sn', 'RS' => 'rs', 'SC' => 'sc',
    'SL' => 'sl', 'SG' => 'sg', 'SY' => 'sy', 'SO' => 'so', 'ZA' => 'za',
    'SD' => 'sd', 'SE' => 'se', 'CH' => 'ch', 'SR' => 'sr', 'TH' => 'th',
    'TZ' => 'tz', 'TJ' => 'tj', 'TG' => 'tg', 'TO' => 'to', 'TT' => 'tt',
    'TN' => 'tn', 'TR' => 'tr', 'UA' => 'ua', 'UG' => 'ug', 'UY' => 'uy',
    'UZ' => 'uz', 'VU' => 'vu', 'VE' => 've', 'VN' => 'vn', 'YE' => 'ye',
    'ZM' => 'zm', 'ZW' => 'zw'
];

                $countryCode = strtoupper(substr($vEvaluador['cod_ciudad'], 0, 2));
                $flagCode = isset($countryFlagMap[$countryCode]) ? $countryFlagMap[$countryCode] : 'un';
                $flagUrl = "https://flagcdn.com/w40/{$flagCode}.png";
                
                // Update country stats for dashboard
                if (!isset($countryStats[$countryCode])) {
                    $countryStats[$countryCode] = 0;
                }
                $countryStats[$countryCode]++;

                // Calculate total and evaluated assignments
                $vTrabajos = GetFile("ttrabajo", 
                    "activo=1 and estado!=1 and (evaluador1='" . $vEvaluador['id'] . "' or evaluador2='" . $vEvaluador['id'] . "' or evaluador3='" . $vEvaluador['id'] . "')", 
                    "area_tematica, id");
                $totalAssignments += mysqli_num_rows($vTrabajos);
                
                // Reset pointer for second pass
                mysqli_data_seek($vTrabajos, 0);
                
                $evaluatedAssignments = 0;
                $assignmentDetails = [];
                
                while ($vTrabajo = mysqli_fetch_assoc($vTrabajos)) {
                    if ($vTrabajo['evaluador1'] === $vEvaluador['id'] || $vTrabajo['evaluador2'] === $vEvaluador['id'] || $vTrabajo['evaluador3'] === $vEvaluador['id']) {
                        $isEvaluated = (($vTrabajo['evaluador1'] == $vEvaluador['id'] && $vTrabajo['calificacion1_fecha'] != NULL) || 
                                       ($vTrabajo['evaluador2'] == $vEvaluador['id'] && $vTrabajo['calificacion2_fecha'] != NULL) || 
                                       ($vTrabajo['evaluador3'] == $vEvaluador['id'] && $vTrabajo['calificacion3_fecha'] != NULL));
                        
                        if ($isEvaluated) {
                            $evaluatedAssignments++;
                            $completedEvaluations++;
                            $evaluationStatusData[0]++; // Increment completed count
                        } else {
                            $evaluationStatusData[1]++; // Increment pending count
                        }
                        
                        $assignmentDetails[] = [
                            'codigo' => $vTrabajo['codigo'],
                            'isEvaluated' => $isEvaluated
                        ];
                    }
                }
        ?>
        <div class="evaluator-card <?php echo $isActive ? '' : 'inactive'; ?>">
            <div class="evaluator-header <?php echo $isActive ? '' : 'inactive'; ?>" onclick="toggleEvaluator(this)">
                <img src="<?php echo htmlspecialchars($avatarUrl); ?>" 
                     alt="<?php echo htmlspecialchars($vEvaluador['nombre']); ?> Avatar" 
                     class="evaluator-avatar">
                <div class="evaluator-info">
                    <span class="evaluator-name">
                        <?php echo htmlspecialchars($vEvaluador['nombre']); ?>
                        <span class="evaluator-id">ID: <?php echo htmlspecialchars($vEvaluador['id']); ?></span>
                    </span>
                    <img src="<?php echo $flagUrl; ?>" alt="Country Flag" class="country-flag">
                    <span class="ms-2">
                        <?php echo mysqli_num_rows($vTrabajos); ?> Assignments 
                        (<?php echo $evaluatedAssignments; ?> Evaluated)
                    </span>
                    <?php if (!$isActive): ?>
                        <span class="inactive-badge">Inactive</span>
                    <?php endif; ?>
                </div>
                <i class="fas fa-chevron-down expand-icon"></i>
            </div>

            <div class="evaluator-details">
                <div class="details-grid">
                    <div class="detail-section">
                        <h3 class="detail-title">Personal Information</h3>
                        <p><strong>Email:</strong> <?php echo htmlspecialchars($vEvaluador['correo']); ?></p>
                        <p><strong>Language:</strong> <?php echo htmlspecialchars($vEvaluador['Idioma']); ?></p>
                        <p><strong>Country:</strong> <?php echo htmlspecialchars($vEvaluador['cod_ciudad']); ?></p>
                        <p><strong>Status:</strong> <?php echo $isActive ? 'Active' : 'Inactive'; ?></p>
                    </div>

                    <div class="detail-section">
                        <h3 class="detail-title">Thematic Areas</h3>
                        <ul class="list-unstyled">
                            <?php 
                            $vAreas = GetFile("tarea", "", "codigo");
                            while ($vArea = mysqli_fetch_assoc($vAreas)) {
                                if (strstr($vEvaluador['areas'], $vArea['codigo'])) {
                                    echo '<li><span class="text-muted">(' . htmlspecialchars($vArea['codigo']) . ')</span> ' . 
                                         htmlspecialchars($vArea['descripcion']) . '</li>';
                                }
                            }
                            ?>
                        </ul>
                    </div>

                    <div class="detail-section">
                        <h3 class="detail-title">Assigned Papers</h3>
                        <div class="assignments-grid">
                            <?php 
                            if (empty($assignmentDetails)) {
                                echo '<p class="text-muted">No assignments</p>';
                            } else {
                                foreach ($assignmentDetails as $assignment) {
                                    $statusClass = $assignment['isEvaluated'] ? 'completed' : 'pending';
                                    $statusIcon = $assignment['isEvaluated'] ? '<i class="fas fa-check-circle"></i>' : '';
                                    
                                    echo '<a href="trabajo.php?opc=A' . $assignment['codigo'] . '&m=' . md5($assignment['codigo']) . '&U=' . ($vIdUsr ?? '') . '" 
                                            class="assignment-item ' . $statusClass . '" 
                                            title="' . ($assignment['isEvaluated'] ? 'Evaluated' : 'Pending evaluation') . '">
                                            ' . $assignment['codigo'] . ' ' . $statusIcon . '
                                          </a>';
                                }
                            }
                            ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
                // End of while loop for evaluators
            } 
            
            // Calculate pending percentage for dashboard
            $pendingPercentage = ($totalAssignments > 0) ? 
                round((($totalAssignments - $completedEvaluations) / $totalAssignments) * 100) : 0;
                
        } else { 
        ?>
        <div class="no-evaluators">
            <i class="fas fa-info-circle me-2"></i>No evaluators found in the system.
        </div>
        <?php 
        } 
        ?>
    </section>

    <!-- Footer -->
    <footer class="bg-light py-4 mt-5">
        <div class="container text-center">
            <p>© Panamtrauma 2025 | All Rights Reserved</p>
        </div>
    </footer>

    <!-- JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleEvaluator(header) {
            const details = header.nextElementSibling;
            const icon = header.querySelector('.expand-icon');
            
            if (details.style.display === 'block') {
                details.style.display = 'none';
                icon.classList.remove('rotated');
            } else {
                details.style.display = 'block';
                icon.classList.add('rotated');
            }
        }
        
        // Initialize Dashboard data
        window.addEventListener('load', function() {
            // Update statistics from PHP variables
            document.getElementById('total-evaluators').textContent = '<?php echo $totalEvaluators; ?>';
            document.getElementById('total-assignments').textContent = '<?php echo $totalAssignments; ?>';
            document.getElementById('completed-evaluations').textContent = '<?php echo $completedEvaluations; ?>';
            document.getElementById('pending-percentage').textContent = '<?php echo $pendingPercentage; ?>%';
            
            // Country chart with flags
            const countryData = <?php echo json_encode($countryStats, JSON_NUMERIC_CHECK); ?>;
            const countryLabels = Object.keys(countryData);
            const countryValues = Object.values(countryData);
            
            // Country flag mapping
            const countryFlagMap = {
                'US': 'us', 'EC': 'ec', 'VE': 've', 'PE': 'pe', 
                'GT': 'gt', 'AR': 'ar', 'CU': 'cu', 'MX': 'mx', 
                'CO': 'co', 'CL': 'cl', 'PA': 'pa', 'DO': 'do', 
                'PR': 'pr', 'AR': 'ar', 'BR': 'br'
            };
            
            // Create flag icons for labels
            const flagLabels = countryLabels.map(country => {
                const flagCode = countryFlagMap[country] || 'un';
                return [
                    `<img src="https://flagcdn.com/16x12/${flagCode}.png" style="vertical-align: middle; margin-right: 5px;" />`,
                    `<span>${country}</span>`
                ].join('');
            });
            
            const countryCtx = document.getElementById('country-chart');
            if(countryCtx) {
                new Chart(countryCtx, {
                    type: 'bar',
                    data: {
                        labels: flagLabels,
                        datasets: [{
                            label: 'Evaluadores por País',
                            data: countryValues,
                            backgroundColor: [
                                '#3498db', '#2ecc71', '#f39c12', '#e74c3c', '#9b59b6',
                                '#1abc9c', '#d35400', '#34495e', '#16a085', '#27ae60'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    precision: 0
                                }
                            },
                            x: {
                                ticks: {
                                    callback: function(value, index) {
                                        return countryLabels[index];
                                    }
                                }
                            }
                        },
                        plugins: {
                            tooltip: {
                                callbacks: {
                                    title: function(tooltipItems) {
                                        return countryLabels[tooltipItems[0].dataIndex];
                                    }
                                }
                            },
                            legend: {
                                display: false
                            }
                        }
                    }
                });
                
                // Add flags below the chart
                const flagContainer = document.createElement('div');
                flagContainer.style.display = 'flex';
                flagContainer.style.justifyContent = 'center';
                flagContainer.style.flexWrap = 'wrap';
                flagContainer.style.marginTop = '10px';
                
                countryLabels.forEach((country, index) => {
                    const flagCode = countryFlagMap[country] || 'un';
                    const flagItem = document.createElement('div');
                    flagItem.style.display = 'flex';
                    flagItem.style.alignItems = 'center';
                    flagItem.style.margin = '0 10px 5px 0';
                    flagItem.innerHTML = `
                        <img src="https://flagcdn.com/16x12/${flagCode}.png" style="margin-right: 5px;" />
                        <span style="font-size: 12px;">${country}: ${countryValues[index]}</span>
                    `;
                    flagContainer.appendChild(flagItem);
                });
                
                countryCtx.parentNode.appendChild(flagContainer);
            }
            
            // Evaluation Status chart
            const evalStatusCtx = document.getElementById('evaluation-status-chart');
            if(evalStatusCtx) {
                new Chart(evalStatusCtx, {
                    type: 'pie',
                    data: {
                        labels: ['Completadas', 'Pendientes'],
                        datasets: [{
                            data: <?php echo json_encode($evaluationStatusData, JSON_NUMERIC_CHECK); ?>,
                            backgroundColor: ['#2ecc71', '#e74c3c'],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        plugins: {
                            legend: {
                                position: 'bottom'
                            }
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>