<?php 
// 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
}


?>
<?php
// Initialize variables and include dependencies

$opc = $G_opc ?? '';

// Fetch key statistics from database
$totalAbstracts = GetCantRegs("ttrabajo", NULL);
$activeAbstracts = GetCantRegs("ttrabajo", "activo=1");
$disabledAbstracts = GetCantRegs("ttrabajo", "activo=0");
$fullyEvaluatedAbstracts = GetCantRegs("ttrabajo", "calificacion1_fecha!='NULL' AND calificacion2_fecha!='NULL' AND calificacion3_fecha!='NULL' AND activo=1");
$partiallyEvaluatedAbstracts = GetCantRegs("ttrabajo", "estado='3' OR estado='4' AND activo=1") - $fullyEvaluatedAbstracts;
$unevaluatedAbstracts = $activeAbstracts - ($fullyEvaluatedAbstracts + $partiallyEvaluatedAbstracts);

// Prepare data for charts
$presentationTypes = [];
$presentationTypeCounts = [];
$categoryTypes = [];
$categoryTypeCounts = [];
$thematicAreas = [];
$thematicAreaCounts = [];

// Fetch Presentation Types from database
$vTiposPresentaciones = GetFile("ttipo_presentacion", "", "codigo");
while ($vTipoPresentacion = mysqli_fetch_assoc($vTiposPresentaciones)) {
    $vValor = GetCantRegs("ttrabajo", "activo=1 and cod_tipo_presentacion_propuesto='" . $vTipoPresentacion['codigo'] . "'");
    $presentationTypes[] = $vTipoPresentacion['descripcion_esp'];
    $presentationTypeCounts[] = $vValor;
}
mysqli_free_result($vTiposPresentaciones);

// Fetch Categories from database
$vCategorias = GetFile("ttipo_competicion", "", "codigo");
while ($vCategoria = mysqli_fetch_assoc($vCategorias)) {
    $vValor = GetCantRegs("ttrabajo", "activo=1 and cod_tipo_competicion_propuesto='" . $vCategoria['codigo'] . "'");
    $categoryTypes[] = $vCategoria['descripcion_esp'];
    $categoryTypeCounts[] = $vValor;
}
mysqli_free_result($vCategorias);

// Fetch Thematic Areas from database
$vAreas = GetFile("tarea", "", "codigo");
while ($vArea = mysqli_fetch_assoc($vAreas)) {
    $vValor = GetCantRegs("ttrabajo", "activo=1 and area_tematica='" . $vArea['codigo'] . "'");
    $thematicAreas[] = "(" . $vArea['codigo'] . ") " . $vArea['descripcion'];
    $thematicAreaCounts[] = $vValor;
}
mysqli_free_result($vAreas);

// Fetch Evaluators data from database
$vEvaluadores = GetFile("tusuario", "activo=1", "nombre");
$evaluadoresData = [];

while ($vEvaluador = mysqli_fetch_assoc($vEvaluadores)) {
    $idEvaluador = $vEvaluador['id'];
    
    // Count assigned abstracts for each evaluator
    $asignados = GetCantRegs("ttrabajo", "activo=1 AND (evaluador1=" . $idEvaluador . 
                            " OR evaluador2=" . $idEvaluador . 
                            " OR evaluador3=" . $idEvaluador . ")");
    
    // Count completed evaluations by this evaluator
    // Evaluations as evaluator1
    $evaluadosEv1 = GetCantRegs("ttrabajo", "activo=1 AND evaluador1=" . $idEvaluador . 
                               " AND calificacion1_fecha IS NOT NULL");
    
    // Evaluations as evaluator2
    $evaluadosEv2 = GetCantRegs("ttrabajo", "activo=1 AND evaluador2=" . $idEvaluador . 
                               " AND calificacion2_fecha IS NOT NULL");
    
    // Evaluations as evaluator3
    $evaluadosEv3 = GetCantRegs("ttrabajo", "activo=1 AND evaluador3=" . $idEvaluador . 
                               " AND calificacion3_fecha IS NOT NULL");
    
    // Sum all completed evaluations
    $evaluados = $evaluadosEv1 + $evaluadosEv2 + $evaluadosEv3;
    
    // Calculate pending evaluations
    $pendientes = $asignados - $evaluados;
    
    // Store data only if evaluator has assigned abstracts
    if ($asignados > 0) {
        $evaluadoresData[] = [
            'id' => $idEvaluador,
            'nombre' => $vEvaluador['nombre'],
            'avatar' => $vEvaluador['avatar'] ?? '',  // Store avatar filename
            'asignados' => $asignados,
            'evaluados' => $evaluados,
            'pendientes' => $pendientes
        ];
    }
    
    
   
}
mysqli_free_result($vEvaluadores);

// Sort evaluators by number of pending abstracts (descending)
usort($evaluadoresData, function($a, $b) {
    return $b['pendientes'] - $a['pendientes'];
});
?>


<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panamtrauma 2025 - Abstract Analysis Dashboard</title>
    
    <!-- Modern CSS Frameworks -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/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">
    
    <style>
        :root {
            --primary-color: #0c4a6e;
            --primary-light: #bae6fd;
            --primary-dark: #075985;
            --secondary-color: #0ea5e9;
            --tertiary-color: #7c3aed;
            --danger-color: #b91c1c;
            --warning-color: #ca8a04;
            --success-color: #15803d;
            --dark-color: #1e293b;
            --light-color: #f8fafc;
            --gray-color: #cbd5e1;
            --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            --hover-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        
        html {
            scroll-behavior: smooth;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f3f4f6;
            color: var(--dark-color);
            line-height: 1.6;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        /* MAIN CONTENT */
        .main-content {
            flex: 1;
            padding: 1.5rem;
            transition: all 0.3s ease;
        }
        
        @media (min-width: 992px) {
            .main-content {
                padding: 2rem 3rem;
            }
        }
        
        /* HEADER */
        .header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            padding: 1.5rem;
            border-radius: 0.75rem;
            box-shadow: var(--card-shadow);
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
            color: white;
        }
        
        .header::after {
            content: '';
            position: absolute;
            bottom: 0;
            right: 0;
            width: 30%;
            height: 100%;
            background-image: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcz48cGF0dGVybiBpZD0icGF0dGVybiIgeD0iMCIgeT0iMCIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiBwYXR0ZXJuVW5pdHM9InVzZXJTcGFjZU9uVXNlIj48Y2lyY2xlIGN4PSIxMCIgY3k9IjEwIiByPSIxLjUiIGZpbGw9InJnYmEoMjU1LCAyNTUsIDI1NSwgMC4xKSIgLz48L3BhdHRlcm4+PC9kZWZzPjxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjcGF0dGVybikiIC8+PC9zdmc+');
            opacity: 0.5;
            z-index: 0;
        }
        
        .header-title {
            position: relative;
            z-index: 1;
        }
        
        .header-title h1 {
            margin: 0;
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .header-title p {
            opacity: 0.9;
            margin-bottom: 0;
        }
        
        .header-actions {
            position: relative;
            z-index: 1;
            margin-top: 1rem;
        }
        
        @media (min-width: 768px) {
            .header {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            
            .header-actions {
                margin-top: 0;
            }
        }
        
        /* CARDS */
        .card {
            background-color: white;
            border-radius: 0.75rem;
            box-shadow: var(--card-shadow);
            margin-bottom: 1.5rem;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            border: none;
            overflow: hidden;
        }
        
        .card:hover {
            box-shadow: var(--hover-shadow);
        }
        
        .card-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid rgba(203, 213, 225, 0.5);
            background-color: white;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 0.75rem;
        }
        
        .card-title {
            margin: 0;
            font-weight: 600;
            font-size: 1.1rem;
            color: var(--primary-dark);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .card-title i {
            color: var(--secondary-color);
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        /* STATS CARDS */
        .stats-card {
            padding: 1.5rem;
            text-align: center;
            height: 100%;
            position: relative;
            overflow: hidden;
            z-index: 1;
            background-color: white;
        }
        
        .stats-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: var(--primary-color);
            z-index: -1;
        }
        
        .stats-card.success::before {
            background: var(--success-color);
        }
        
        .stats-card.warning::before {
            background: var(--warning-color);
        }
        
        .stats-card.danger::before {
            background: var(--danger-color);
        }
        
        .stats-card.info::before {
            background: var(--secondary-color);
        }
        
        .stats-card.tertiary::before {
            background: var(--tertiary-color);
        }
        
        .stats-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 56px;
            height: 56px;
            border-radius: 16px;
            font-size: 1.5rem;
            margin-bottom: 1rem;
            color: white;
            background: var(--primary-color);
            box-shadow: 0 4px 6px rgba(12, 74, 110, 0.15);
            position: relative;
            transition: transform 0.3s ease;
        }
        
        .stats-card:hover .stats-icon {
            transform: translateY(-5px);
        }
        
        .stats-card.success .stats-icon {
            background: var(--success-color);
            box-shadow: 0 4px 6px rgba(21, 128, 61, 0.15);
        }
        
        .stats-card.warning .stats-icon {
            background: var(--warning-color);
            box-shadow: 0 4px 6px rgba(202, 138, 4, 0.15);
        }
        
        .stats-card.danger .stats-icon {
            background: var(--danger-color);
            box-shadow: 0 4px 6px rgba(185, 28, 28, 0.15);
        }
        
        .stats-card.info .stats-icon {
            background: var(--secondary-color);
            box-shadow: 0 4px 6px rgba(14, 165, 233, 0.15);
        }
        
        .stats-card.tertiary .stats-icon {
            background: var(--tertiary-color);
            box-shadow: 0 4px 6px rgba(124, 58, 237, 0.15);
        }
        
        .stats-value {
            font-size: 2rem;
            font-weight: 700;
            color: var(--dark-color);
            margin: 0.75rem 0 0.5rem;
            line-height: 1;
        }
        
        .stats-label {
            font-weight: 500;
            color: #64748b;
            font-size: 0.95rem;
            margin-bottom: 0;
        }
        
        /* PROGRESS STYLES */
        .progress {
            height: 8px;
            border-radius: 10px;
            margin: 0.75rem 0;
            background-color: #e2e8f0;
            overflow: hidden;
        }
        
        .progress-bar {
            border-radius: 10px;
            transition: width 1s ease-in-out;
        }
        
        /* TABLES */
        .table-wrapper {
            border-radius: 0.75rem;
            overflow: hidden;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.03);
        }
        
        .table {
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .table thead th {
            background-color: #f8fafc;
            color: var(--primary-dark);
            font-weight: 600;
            border: none;
            padding: 1rem 1.25rem;
            position: relative;
            cursor: pointer;
            white-space: nowrap;
            font-size: 0.875rem;
            letter-spacing: 0.025em;
            text-transform: uppercase;
        }
        
        .table thead th::after {
            content: '⇅';
            position: absolute;
            right: 0.5rem;
            color: #cbd5e1;
            font-size: 0.8rem;
        }
        
        .table thead th:hover {
            background-color: var(--primary-light);
        }
        
        .table tbody tr {
            transition: background-color 0.15s ease;
        }
        
        .table tbody tr:hover {
            background-color: #f1f5f9;
        }
        
        .table tbody td {
            padding: 1rem 1.25rem;
            vertical-align: middle;
            border-top: none;
            border-bottom: 1px solid #e2e8f0;
            color: #334155;
            font-size: 0.9375rem;
        }
        
        .table tbody tr:last-child td {
            border-bottom: none;
        }
        
        
        /* CHART CONTAINER */
        .chart-container {
            position: relative;
            height: 300px;
            width: 100%;
            padding: 1rem;
        }
        
        @media (max-width: 768px) {
            .chart-container {
                height: 250px;
            }
        }
        
        /* BUTTONS STYLING */
        .btn {
            padding: 0.5rem 1.25rem;
            border-radius: 0.5rem;
            font-weight: 500;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.4rem;
            border: none;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }
        
        .btn-primary:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(12, 74, 110, 0.2);
        }
        
        .btn-primary:active {
            transform: translateY(0);
        }
        
        .btn-success {
            background-color: var(--success-color);
            color: white;
        }
        
        .btn-success:hover {
            background-color: #166534;
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(21, 128, 61, 0.2);
        }
        
        .btn-success:active {
            transform: translateY(0);
        }
        
        .btn-outline-primary {
            color: var(--primary-color);
            border: 1px solid var(--primary-color);
            background-color: transparent;
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary-color);
            color: white;
        }
        
        /* BADGE STYLES */
        .badge {
            font-weight: 500;
            padding: 0.35rem 0.75rem;
            border-radius: 0.375rem;
            font-size: 0.75rem;
        }
        
        /* ANIMATIONS */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .fade-in {
            animation: fadeInUp 0.6s ease forwards;
            opacity: 0;
        }
        
        /* FOOTER */
        .footer {
            background-color: white;
            border-top: 1px solid #e2e8f0;
            padding: 1.5rem 0;
            text-align: center;
            font-size: 0.875rem;
            color: #64748b;
            margin-top: auto;
        }
        
        /* PRINT STYLES - For PDF Export */
        @media print {
            @page {
                size: A4;
                margin: 10mm;
            }
            
            body {
                background-color: white !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            .header-actions, 
            .card-actions, 
            .table button,
            .footer {
                display: none !important;
            }
            
            .main-content {
                padding: 0 !important;
            }
            
            .card {
                break-inside: avoid;
                page-break-inside: avoid;
                box-shadow: none !important;
                border: 1px solid #e2e8f0 !important;
                margin-bottom: 15mm !important;
            }
            
            .row {
                display: block !important;
            }
            
            .col-md-4, .col-md-6, .col-12 {
                width: 100% !important;
                max-width: 100% !important;
                flex: 0 0 100% !important;
            }
            
            .chart-container {
                height: 200px !important;
            }
            
            .table {
                font-size: 10pt !important;
            }
            
            .table td, .table th {
                padding: 4mm !important;
            }
        }
        
        /* LOADING SPINNER */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(15, 23, 42, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            backdrop-filter: blur(3px);
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-bottom: 0.75rem;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* ALERT STYLES */
        .alert-float {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
            min-width: 300px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border-radius: 0.5rem;
            border: none;
            animation: slideInRight 0.3s ease-out forwards;
        }
        
        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        
        /* Animation Delays */
        .animation-delay-1 { animation-delay: 0.1s; }
        .animation-delay-2 { animation-delay: 0.2s; }
        .animation-delay-3 { animation-delay: 0.3s; }
        .animation-delay-4 { animation-delay: 0.4s; }
        .animation-delay-5 { animation-delay: 0.5s; }
        .animation-delay-6 { animation-delay: 0.6s; }
        
        /* Responsive Adjustments */
        @media (max-width: 576px) {
            .header {
                padding: 1.25rem;
            }
            
            .header-title h1 {
                font-size: 1.5rem;
            }
            
            .card-header {
                padding: 1rem;
            }
            
            .card-body {
                padding: 1rem;
            }
            
            .stats-card {
                padding: 1.25rem;
            }
            
            .stats-value {
                font-size: 1.75rem;
            }
            
            .table-wrapper {
                overflow-x: auto;
            }
            
            .table td, .table th {
                padding: 0.75rem 1rem;
            }
        }
    </style>
</head>
<body>
    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <header class="header">
            <div class="header-title">
                <h1><i class="fas fa-chart-line me-2"></i>Abstract Analysis Dashboard</h1>
                <p>Comprehensive overview of Panamtrauma 2025 abstract submissions and evaluations</p>
            </div>
            
            <div class="header-actions">
                <button id="export-pdf" class="btn btn-light me-2">
                    <i class="fas fa-file-pdf"></i> Export PDF
                </button>
                <button id="export-csv" class="btn btn-light">
                    <i class="fas fa-file-csv"></i> Export CSV
                </button>
            </div>
        </header>

        <!-- Overview Statistics -->
        <div class="row mb-4">
            <div class="col-md-4 fade-in animation-delay-1">
                <div class="card h-100">
                    <div class="stats-card">
                        <div class="stats-icon">
                            <i class="fas fa-file-alt"></i>
                        </div>
                        <div class="stats-value"><?php echo $totalAbstracts; ?></div>
                        <div class="stats-label">Total Abstracts</div>
                        
                        <div class="mt-3">
                            <small class="text-muted">All submissions received</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4 fade-in animation-delay-2">
                <div class="card h-100">
                    <div class="stats-card success">
                        <div class="stats-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="stats-value"><?php echo $activeAbstracts; ?></div>
                        <div class="stats-label">Active Abstracts</div>
                        
                        <div class="mt-3">
                            <small class="text-muted">Currently active submissions</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4 fade-in animation-delay-3">
                <div class="card h-100">
                    <div class="stats-card warning">
                        <div class="stats-icon">
                            <i class="fas fa-ban"></i>
                        </div>
                        <div class="stats-value"><?php echo $disabledAbstracts; ?></div>
                        <div class="stats-label">Disabled Abstracts</div>
                        
                        <div class="mt-3">
                            <small class="text-muted">Inactive or rejected submissions</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Evaluation Status Statistics -->
        <div class="row mb-4">
            <div class="col-md-4 fade-in animation-delay-2">
                <div class="card h-100">
                    <div class="stats-card success">
                        <div class="stats-icon">
                            <i class="fas fa-clipboard-check"></i>
                        </div>
                        <div class="stats-value"><?php echo $fullyEvaluatedAbstracts; ?></div>
                        <div class="stats-label">Fully Evaluated</div>
                        
                        <div class="progress mt-3">
                            <div class="progress-bar bg-success" style="width: <?php echo ($fullyEvaluatedAbstracts * 100) / $activeAbstracts; ?>%"></div>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted"><?php echo round(($fullyEvaluatedAbstracts * 100) / $activeAbstracts); ?>% of active abstracts</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4 fade-in animation-delay-3">
                <div class="card h-100">
                    <div class="stats-card warning">
                        <div class="stats-icon">
                            <i class="fas fa-tasks"></i>
                        </div>
                        <div class="stats-value"><?php echo $partiallyEvaluatedAbstracts; ?></div>
                        <div class="stats-label">Partially Evaluated</div>
                        
                        <div class="progress mt-3">
                            <div class="progress-bar bg-warning" style="width: <?php echo ($partiallyEvaluatedAbstracts * 100) / $activeAbstracts; ?>%"></div>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted"><?php echo round(($partiallyEvaluatedAbstracts * 100) / $activeAbstracts); ?>% of active abstracts</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4 fade-in animation-delay-4">
                <div class="card h-100">
                    <div class="stats-card danger">
                        <div class="stats-icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <div class="stats-value"><?php echo $unevaluatedAbstracts; ?></div>
                        <div class="stats-label">Unevaluated</div>
                        
                        <div class="progress mt-3">
                            <div class="progress-bar bg-danger" style="width: <?php echo ($unevaluatedAbstracts * 100) / $activeAbstracts; ?>%"></div>
                        </div>
                        <div class="mt-2">
                            <small class="text-muted"><?php echo round(($unevaluatedAbstracts * 100) / $activeAbstracts); ?>% of active abstracts</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Overall Progress Card -->
        <div class="row mb-4">
            <div class="col-12 fade-in animation-delay-5">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-chart-pie"></i> Overall Evaluation Progress
                        </h5>
                        <button class="btn btn-sm btn-outline-primary refresh-btn">
                            <i class="fas fa-sync-alt"></i> Refresh Data
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-lg-6">
                                <div class="chart-container">
                                    <canvas id="evaluationStatusChart"></canvas>
                                </div>
                            </div>
                            <div class="col-lg-6">
                                <div class="d-flex flex-column justify-content-center">
                                    <div class="text-center mb-4">
                                        <div class="position-relative d-inline-block">
                                            <svg width="120" height="120" viewBox="0 0 120 120">
                                                <circle cx="60" cy="60" r="54" fill="none" stroke="#e2e8f0" stroke-width="12" />
                                                <circle cx="60" cy="60" r="54" fill="none" stroke="var(--success-color)" stroke-width="12" stroke-dasharray="339.3" stroke-dashoffset="<?php echo (339.3 * (100 - ($fullyEvaluatedAbstracts * 100) / $activeAbstracts) / 100); ?>" transform="rotate(-90 60 60)" />
                                            </svg>
                                            <div class="position-absolute" style="top: 50%; left: 50%; transform: translate(-50%, -50%);">
                                                <span class="h1 text-success fw-bold"><?php echo round(($fullyEvaluatedAbstracts * 100) / $activeAbstracts); ?>%</span>
                                            </div>
                                        </div>
                                        <span class="d-block text-muted mt-2">Overall Completion</span>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <div class="d-flex justify-content-between mb-1">
                                            <span><i class="fas fa-check-circle text-success me-2"></i> Fully Evaluated</span>
                                            <span class="badge bg-success"><?php echo $fullyEvaluatedAbstracts; ?></span>
                                        </div>
                                        <div class="progress" style="height: 8px;">
                                            <div class="progress-bar bg-success" role="progressbar" 
                                                style="width: <?php echo ($fullyEvaluatedAbstracts * 100) / $activeAbstracts; ?>%" 
                                                aria-valuenow="<?php echo ($fullyEvaluatedAbstracts * 100) / $activeAbstracts; ?>" 
                                                aria-valuemin="0" aria-valuemax="100">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <div class="d-flex justify-content-between mb-1">
                                            <span><i class="fas fa-tasks text-warning me-2"></i> Partially Evaluated</span>
                                            <span class="badge bg-warning"><?php echo $partiallyEvaluatedAbstracts; ?></span>
                                        </div>
                                        <div class="progress" style="height: 8px;">
                                            <div class="progress-bar bg-warning" role="progressbar" 
                                                style="width: <?php echo ($partiallyEvaluatedAbstracts * 100) / $activeAbstracts; ?>%" 
                                                aria-valuenow="<?php echo ($partiallyEvaluatedAbstracts * 100) / $activeAbstracts; ?>" 
                                                aria-valuemin="0" aria-valuemax="100">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <div class="d-flex justify-content-between mb-1">
                                            <span><i class="fas fa-exclamation-triangle text-danger me-2"></i> Unevaluated</span>
                                            <span class="badge bg-danger"><?php echo $unevaluatedAbstracts; ?></span>
                                        </div>
                                        <div class="progress" style="height: 8px;">
                                            <div class="progress-bar bg-danger" role="progressbar" 
                                                style="width: <?php echo ($unevaluatedAbstracts * 100) / $activeAbstracts; ?>%" 
                                                aria-valuenow="<?php echo ($unevaluatedAbstracts * 100) / $activeAbstracts; ?>" 
                                                aria-valuemin="0" aria-valuemax="100">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Distribution Charts -->
        <div class="row mb-4">
            <div class="col-md-6 fade-in animation-delay-3">
                <div class="card h-100">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-chart-column"></i> Presentation Types
                        </h5>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" id="chartTypeDropdown1" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="fas fa-chart-pie me-1"></i> Chart Type
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="chartTypeDropdown1">
                                <li><a class="dropdown-item chart-type" data-chart="presentationTypesChart" data-type="pie" href="#">Pie Chart</a></li>
                                <li><a class="dropdown-item chart-type" data-chart="presentationTypesChart" data-type="doughnut" href="#">Doughnut Chart</a></li>
                                <li><a class="dropdown-item chart-type" data-chart="presentationTypesChart" data-type="bar" href="#">Bar Chart</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="presentationTypesChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 fade-in animation-delay-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-layer-group"></i> Categories Distribution
                        </h5>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" id="chartTypeDropdown2" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="fas fa-chart-pie me-1"></i> Chart Type
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="chartTypeDropdown2">
                                <li><a class="dropdown-item chart-type" data-chart="categoriesChart" data-type="pie" href="#">Pie Chart</a></li>
                                <li><a class="dropdown-item chart-type" data-chart="categoriesChart" data-type="doughnut" href="#">Doughnut Chart</a></li>
                                <li><a class="dropdown-item chart-type" data-chart="categoriesChart" data-type="bar" href="#">Bar Chart</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="categoriesChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-12 fade-in animation-delay-5">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-sitemap"></i> Thematic Areas Distribution
                        </h5>
                        <div class="card-actions">
                            <div class="form-check form-switch d-inline-block me-3">
                                <input class="form-check-input" type="checkbox" id="showDataLabels" checked>
                                <label class="form-check-label" for="showDataLabels">Show Values</label>
                            </div>
                            <button class="btn btn-sm btn-outline-primary" id="sortThematicChart">
                                <i class="fas fa-sort-amount-down me-1"></i> Sort
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="chart-container" style="height: 400px;">
                            <canvas id="thematicAreasChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Evaluators Report -->
        <div class="row mb-4">
            <div class="col-12 fade-in animation-delay-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-user-check"></i> Evaluators Performance
                        </h5>
                        <div class="input-group input-group-sm" style="max-width: 300px;">
                            <input type="text" class="form-control" placeholder="Search evaluator..." id="evaluatorSearch">
                            <button class="btn btn-outline-primary" type="button">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-wrapper">
                            <table class="table table-hover" id="evaluatorsTable">
                                <thead>
                                    <tr>
                                        <th><i class="fas fa-user me-2"></i>Name</th>
                                        <th><i class="fas fa-file-alt me-2"></i>Assigned</th>
                                        <th><i class="fas fa-check-circle me-2"></i>Evaluated</th>
                                        <th><i class="fas fa-hourglass-half me-2"></i>Pending</th>
                                        <th><i class="fas fa-chart-line me-2"></i>Progress</th>
                                        <th><i class="fas fa-cog me-2"></i>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($evaluadoresData as $evaluador): ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <?php if (!empty($evaluador['avatar'])): ?>
                                                    <div class="me-3" style="width: 40px; height: 40px;">
                                                        <img src="dist/pages/evaluadores/acciones_evaluador/fotos_empleados/<?php echo htmlspecialchars($evaluador['avatar']); ?>" 
                                                             class="rounded-circle" 
                                                             style="width: 40px; height: 40px; object-fit: cover;"
                                                             alt="<?php echo htmlspecialchars($evaluador['nombre']); ?>"
                                                             onerror="this.onerror=null; this.src='dist/pages/evaluadores/acciones_evaluador/fotos_empleados/default.png';">
                                                    </div>
                                                <?php else: ?>
                                                    <div class="avatar bg-primary me-3 rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                                        <span class="text-white fw-bold"><?php echo substr($evaluador['nombre'], 0, 1); ?></span>
                                                    </div>
                                                <?php endif; ?>
                                                <?php echo htmlspecialchars($evaluador['nombre']); ?>
                                            </div>
                                        </td>
                                        <td><?php echo $evaluador['asignados']; ?></td>
                                        <td><?php echo $evaluador['evaluados']; ?></td>
                                        <td>
                                            <?php if ($evaluador['pendientes'] > 0): ?>
                                                <span class="badge bg-danger"><?php echo $evaluador['pendientes']; ?></span>
                                            <?php else: ?>
                                                <span class="badge bg-success">0</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php 
                                                $progress = $evaluador['asignados'] > 0 ? 
                                                    round(($evaluador['evaluados'] * 100) / $evaluador['asignados']) : 0;
                                                
                                                $progressClass = 'bg-danger';
                                                if ($progress == 100) {
                                                    $progressClass = 'bg-success';
                                                } elseif ($progress >= 75) {
                                                    $progressClass = 'bg-info';
                                                } elseif ($progress >= 50) {
                                                    $progressClass = 'bg-primary';
                                                } elseif ($progress >= 25) {
                                                    $progressClass = 'bg-warning';
                                                }
                                            ?>
                                            <div class="d-flex align-items-center">
                                                <div class="progress flex-grow-1 me-2" style="height: 8px;">
                                                    <div class="progress-bar <?php echo $progressClass; ?>" 
                                                        role="progressbar" 
                                                        style="width: <?php echo $progress; ?>%" 
                                                        aria-valuenow="<?php echo $progress; ?>" 
                                                        aria-valuemin="0" aria-valuemax="100">
                                                    </div>
                                                </div>
                                                <span><?php echo $progress; ?>%</span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-envelope"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-info">
                                                    <i class="fas fa-chart-bar"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-secondary">
                                                    <i class="fas fa-ellipsis-v"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="card-footer">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <span class="badge bg-info"><?php echo count($evaluadoresData); ?></span> active evaluators
                            </div>
                            <nav aria-label="Evaluators pagination">
                                <ul class="pagination pagination-sm mb-0">
                                    <li class="page-item disabled">
                                        <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Previous</a>
                                    </li>
                                    <li class="page-item active"><a class="page-link" href="#">1</a></li>
                                    <li class="page-item"><a class="page-link" href="#">2</a></li>
                                    <li class="page-item"><a class="page-link" href="#">3</a></li>
                                    <li class="page-item">
                                        <a class="page-link" href="#">Next</a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Detailed Statistics Tables -->
        <div class="row mb-4">
            <div class="col-md-6 fade-in animation-delay-4">
                <div class="card h-100">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-list-ul"></i> Presentation Types Details
                        </h5>
                        <button class="btn btn-sm btn-outline-primary" id="downloadTypeData">
                            <i class="fas fa-download me-1"></i> Download
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-wrapper">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Type</th>
                                        <th>Count</th>
                                        <th>Percentage</th>
                                        <th>Trend</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    for ($i = 0; $i < count($presentationTypes); $i++) {
                                        // Simulating trend data for visualization
                                        $trend = rand(-10, 20);
                                        $trendClass = $trend >= 0 ? 'text-success' : 'text-danger';
                                        $trendIcon = $trend >= 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                                        
                                        echo "<tr>";
                                        echo "<td>" . htmlspecialchars($presentationTypes[$i]) . "</td>";
                                        echo "<td>" . $presentationTypeCounts[$i] . "</td>";
                                        echo "<td>" . round(($presentationTypeCounts[$i] * 100 / $activeAbstracts), 2) . "%</td>";
                                        echo "<td class='{$trendClass}'><i class='fas {$trendIcon} me-1'></i>" . abs($trend) . "%</td>";
                                        echo "</tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6 fade-in animation-delay-5">
                <div class="card h-100">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class="fas fa-tasks"></i> Evaluation Status Details
                        </h5>
                        <button class="btn btn-sm btn-outline-primary" id="downloadStatusData">
                            <i class="fas fa-download me-1"></i> Download
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-wrapper">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Status</th>
                                        <th>Count</th>
                                        <th>Percentage</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            <span class="d-flex align-items-center">
                                                <i class="fas fa-check-circle text-success me-2"></i> Fully Evaluated
                                            </span>
                                        </td>
                                        <td><?php echo $fullyEvaluatedAbstracts; ?></td>
                                        <td><?php echo round(($fullyEvaluatedAbstracts * 100 / $activeAbstracts), 2); ?>%</td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary">View</button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <span class="d-flex align-items-center">
                                                <i class="fas fa-tasks text-warning me-2"></i> Partially Evaluated
                                            </span>
                                        </td>
                                        <td><?php echo $partiallyEvaluatedAbstracts; ?></td>
                                        <td><?php echo round(($partiallyEvaluatedAbstracts * 100 / $activeAbstracts), 2); ?>%</td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-warning">Follow Up</button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <span class="d-flex align-items-center">
                                                <i class="fas fa-exclamation-triangle text-danger me-2"></i> Unevaluated
                                            </span>
                                        </td>
                                        <td><?php echo $unevaluatedAbstracts; ?></td>
                                        <td><?php echo round(($unevaluatedAbstracts * 100 / $activeAbstracts), 2); ?>%</td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-danger">Remind</button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <p class="mb-0">&copy; 2025 Panamtrauma | Abstract Management System</p>
                </div>
                <div class="col-md-6 text-md-end">
                    <ul class="list-inline mb-0">
                        <li class="list-inline-item"><a href="#" class="text-secondary">Privacy Policy</a></li>
                        <li class="list-inline-item"><a href="#" class="text-secondary">Terms of Use</a></li>
                        <li class="list-inline-item"><a href="#" class="text-secondary">Contact Support</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </footer>
    
    <!-- Loading Overlay for PDF Generation -->
    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
        <div class="d-flex flex-column align-items-center">
            <div class="loading-spinner"></div>
            <p class="text-white mt-2">Generating PDF...</p>
        </div>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

    <script>
        // Chart.js Global Settings
        Chart.defaults.font.family = "'Inter', sans-serif";
        Chart.defaults.color = '#64748b';
        Chart.defaults.plugins.tooltip.backgroundColor = 'rgba(17, 24, 39, 0.8)';
        Chart.defaults.plugins.tooltip.padding = 12;
        Chart.defaults.plugins.tooltip.cornerRadius = 8;
        Chart.defaults.plugins.tooltip.titleFont = { weight: 'bold' };
        
        // Color schemes for charts
        const colorSchemes = {
            primary: [
                'rgba(12, 74, 110, 0.8)',
                'rgba(14, 165, 233, 0.8)',
                'rgba(56, 189, 248, 0.8)',
                'rgba(186, 230, 253, 0.8)'
            ],
            mixed: [
                'rgba(12, 74, 110, 0.8)',  // Primary
                'rgba(21, 128, 61, 0.8)',  // Success
                'rgba(202, 138, 4, 0.8)',  // Warning
                'rgba(185, 28, 28, 0.8)',  // Danger
                'rgba(124, 58, 237, 0.8)', // Tertiary
                'rgba(37, 99, 235, 0.8)'   // Info
            ],
            status: [
                'rgba(21, 128, 61, 0.8)',  // Green for fully evaluated
                'rgba(202, 138, 4, 0.8)',  // Yellow for partially evaluated
                'rgba(185, 28, 28, 0.8)'   // Red for unevaluated
            ]
        };

        // Chart instances store
        const chartInstances = {};

        // Initialize charts when document is loaded
        document.addEventListener('DOMContentLoaded', function() {
            // Trigger animations for a cleaner appearance
            document.querySelectorAll('.fade-in').forEach(el => {
                el.style.opacity = 0;
                setTimeout(() => {
                    el.style.opacity = 1;
                }, 100);
            });

            // Presentation Types Chart
            chartInstances.presentationTypesChart = new Chart(document.getElementById('presentationTypesChart'), {
                type: 'pie',
                data: {
                    labels: <?php echo json_encode($presentationTypes); ?>,
                    datasets: [{
                        data: <?php echo json_encode($presentationTypeCounts); ?>,
                        backgroundColor: colorSchemes.mixed,
                        borderColor: colorSchemes.mixed.map(color => color.replace('0.8', '1')),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { 
                            position: 'right',
                            labels: {
                                padding: 20,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
                                    const percentage = Math.round((value / total) * 100);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });

            // Categories Chart
            chartInstances.categoriesChart = new Chart(document.getElementById('categoriesChart'), {
                type: 'doughnut',
                data: {
                    labels: <?php echo json_encode($categoryTypes); ?>,
                    datasets: [{
                        data: <?php echo json_encode($categoryTypeCounts); ?>,
                        backgroundColor: colorSchemes.primary,
                        borderColor: colorSchemes.primary.map(color => color.replace('0.8', '1')),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { 
                            position: 'right',
                            labels: {
                                padding: 20,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
                                    const percentage = Math.round((value / total) * 100);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });

            // Thematic Areas Chart
            chartInstances.thematicAreasChart = new Chart(document.getElementById('thematicAreasChart'), {
                type: 'bar',
                data: {
                    labels: <?php echo json_encode($thematicAreas); ?>,
                    datasets: [{
                        label: 'Number of Abstracts',
                        data: <?php echo json_encode($thematicAreaCounts); ?>,
                        backgroundColor: 'rgba(14, 165, 233, 0.7)',
                        borderColor: 'rgba(12, 74, 110, 1)',
                        borderWidth: 1,
                        borderRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    indexAxis: 'y',
                    scales: {
                        x: {
                            beginAtZero: true,
                            grid: {
                                display: true,
                                drawBorder: false,
                                drawOnChartArea: true,
                                drawTicks: false,
                                color: 'rgba(203, 213, 225, 0.3)'
                            }
                        },
                        y: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    plugins: {
                        legend: { 
                            display: false 
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `${context.formattedValue} abstracts`;
                                }
                            }
                        }
                    }
                }
            });

            // Evaluation Status Chart
            chartInstances.evaluationStatusChart = new Chart(document.getElementById('evaluationStatusChart'), {
                type: 'pie',
                data: {
                    labels: ['Fully Evaluated', 'Partially Evaluated', 'Unevaluated'],
                    datasets: [{
                        data: [
                            <?php echo $fullyEvaluatedAbstracts; ?>, 
                            <?php echo $partiallyEvaluatedAbstracts; ?>, 
                            <?php echo $unevaluatedAbstracts; ?>
                        ],
                        backgroundColor: colorSchemes.status,
                        borderColor: colorSchemes.status.map(color => color.replace('0.8', '1')),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { 
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = <?php echo $activeAbstracts; ?>;
                                    const percentage = Math.round((value / total) * 100);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });

            // Chart type change functionality
            document.querySelectorAll('.chart-type').forEach(function(link) {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const chartId = this.getAttribute('data-chart');
                    const chartType = this.getAttribute('data-type');
                    const chart = chartInstances[chartId];
                    
                    if (chart) {
                        chart.config.type = chartType;
                        chart.update();
                        
                        // Update dropdown button text
                        const dropdownButton = this.closest('.dropdown').querySelector('.dropdown-toggle');
                        dropdownButton.innerHTML = `<i class="fas fa-chart-${chartType === 'bar' ? 'bar' : 'pie'} me-1"></i> ${chartType.charAt(0).toUpperCase() + chartType.slice(1)} Chart`;
                    }
                });
            });
            
            // Sort thematic chart
            document.getElementById('sortThematicChart').addEventListener('click', function() {
                const chart = chartInstances.thematicAreasChart;
                const data = [...chart.data.datasets[0].data];
                const labels = [...chart.data.labels];
                
                // Create pairs and sort
                const pairs = labels.map((label, i) => ({ label, value: data[i] }));
                pairs.sort((a, b) => b.value - a.value);
                
                // Update chart data
                chart.data.labels = pairs.map(pair => pair.label);
                chart.data.datasets[0].data = pairs.map(pair => pair.value);
                chart.update();
                
                // Show notification
                showAlert('Chart sorted by value', 'info');
            });
            
            // Show/hide data labels
            document.getElementById('showDataLabels').addEventListener('change', function() {
                const showLabels = this.checked;
                const chart = chartInstances.thematicAreasChart;
                
                // Toggle data label visibility
                chart.data.datasets[0].datalabels = showLabels ? {
                    color: '#fff',
                    formatter: (value) => value
                } : false;
                
                chart.update();
            });
            
            // Search functionality for evaluators table
            document.getElementById('evaluatorSearch').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = document.querySelectorAll('#evaluatorsTable tbody tr');
                
                rows.forEach(row => {
                    const name = row.querySelector('td:first-child').textContent.toLowerCase();
                    if (name.includes(searchTerm)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            });
            
            // Table sorting functionality
            document.querySelectorAll('#evaluatorsTable th').forEach((header, index) => {
                header.addEventListener('click', () => {
                    sortTable(document.getElementById('evaluatorsTable'), index);
                });
            });
            
            // Refresh button functionality
            document.querySelectorAll('.refresh-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    btn.classList.add('disabled');
                    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Refreshing...';
                    
                    // Simulate data refresh
                    setTimeout(() => {
                        btn.classList.remove('disabled');
                        btn.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh Data';
                        showAlert('Dashboard data refreshed successfully!', 'success');
                    }, 1500);
                });
            });

            // PDF Export functionality with improved formatting
            document.getElementById('export-pdf')?.addEventListener('click', function() {
                // Show loading overlay
                document.getElementById('loadingOverlay').style.display = 'flex';
                
                // Create a clone of the content to modify for PDF
                const contentClone = document.querySelector('.main-content').cloneNode(true);
                
                // Remove search inputs, buttons, and other elements not needed in PDF
                contentClone.querySelectorAll('.header-actions, .dropdown, button:not(.btn-light), input, .pagination').forEach(el => {
                    el.remove();
                });
                
                // Add custom PDF header
                const pdfHeader = document.createElement('div');
                pdfHeader.style.textAlign = 'center';
                pdfHeader.style.marginBottom = '20px';
                pdfHeader.innerHTML = `
                    <h2 style="color: #0c4a6e; margin-bottom: 5px;">Abstract Analysis Report</h2>
                    <p style="color: #64748b; margin: 0;">Panamtrauma 2025 | Generated on ${new Date().toLocaleString()}</p>
                    <hr style="margin: 15px 0; border-color: #e2e8f0;">
                `;
                contentClone.insertBefore(pdfHeader, contentClone.firstChild);
                
                // Add footer with page numbers
                const footer = function(pdf, pageCount) {
                    pdf.setFontSize(10);
                    pdf.setTextColor(100);
                    pdf.text('Page ' + pdf.internal.getNumberOfPages() + ' of ' + pageCount, pdf.internal.pageSize.width / 2, pdf.internal.pageSize.height - 10, { align: 'center' });
                };
                
                const opt = {
                    margin: [15, 15, 20, 15],
                    filename: 'panamtrauma_abstract_analysis.pdf',
                    image: { type: 'jpeg', quality: 0.98 },
                    html2canvas: { 
                        scale: 2,
                        useCORS: true,
                        logging: false
                    },
                    jsPDF: { 
                        unit: 'mm', 
                        format: 'a4', 
                        orientation: 'portrait',
                        compress: true
                    },
                    pagebreak: { mode: ['avoid-all', 'css', 'legacy'] },
                    footer: footer
                };
                
                // Generate PDF
                html2pdf().set(opt).from(contentClone).save().then(() => {
                    // Hide loading overlay
                    document.getElementById('loadingOverlay').style.display = 'none';
                    showAlert('PDF generated successfully!', 'success');
                }).catch(error => {
                    console.error('PDF generation failed:', error);
                    document.getElementById('loadingOverlay').style.display = 'none';
                    showAlert('Error generating PDF. Please try again.', 'danger');
                });
            });

            // CSV Export functionality
            document.getElementById('export-csv')?.addEventListener('click', function() {
                // Prepare CSV content
                let csvContent = "data:text/csv;charset=utf-8,";
                
                // Add header
                csvContent += "ABSTRACT ANALYSIS REPORT - PANAMTRAUMA 2025\r\n";
                csvContent += "Generated on: " + new Date().toLocaleString() + "\r\n\r\n";
                
                // Add Overview Statistics
                csvContent += "OVERVIEW STATISTICS\r\n";
                csvContent += "Metric,Value\r\n";
                csvContent += "Total Abstracts,<?php echo $totalAbstracts; ?>\r\n";
                csvContent += "Active Abstracts,<?php echo $activeAbstracts; ?>\r\n";
                csvContent += "Disabled Abstracts,<?php echo $disabledAbstracts; ?>\r\n\r\n";
                
                // Add Evaluation Status data
                csvContent += "EVALUATION STATUS\r\n";
                csvContent += "Status,Count,Percentage\r\n";
                csvContent += "Fully Evaluated,<?php echo $fullyEvaluatedAbstracts; ?>,<?php echo round(($fullyEvaluatedAbstracts * 100 / $activeAbstracts), 2); ?>%\r\n";
                csvContent += "Partially Evaluated,<?php echo $partiallyEvaluatedAbstracts; ?>,<?php echo round(($partiallyEvaluatedAbstracts * 100 / $activeAbstracts), 2); ?>%\r\n";
                csvContent += "Unevaluated,<?php echo $unevaluatedAbstracts; ?>,<?php echo round(($unevaluatedAbstracts * 100 / $activeAbstracts), 2); ?>%\r\n\r\n";
                
                // Add Presentation Types data
                csvContent += "PRESENTATION TYPES DISTRIBUTION\r\n";
                csvContent += "Type,Count,Percentage\r\n";
                <?php
                for ($i = 0; $i < count($presentationTypes); $i++) {
                    echo "csvContent += \"" . 
                        addslashes($presentationTypes[$i]) . "," . 
                        $presentationTypeCounts[$i] . "," . 
                        round(($presentationTypeCounts[$i] * 100 / $activeAbstracts), 2) . "%\\r\\n\";";
                }
                ?>
                csvContent += "\r\n";
                
                // Add Evaluators Report data
                csvContent += "EVALUATORS PERFORMANCE\r\n";
                csvContent += "Name,Assigned,Evaluated,Pending,Progress(%)\r\n";
                <?php foreach ($evaluadoresData as $evaluador): ?>
                csvContent += "<?php echo addslashes($evaluador['nombre']); ?>,";
                csvContent += "<?php echo $evaluador['asignados']; ?>,";
                csvContent += "<?php echo $evaluador['evaluados']; ?>,";
                csvContent += "<?php echo $evaluador['pendientes']; ?>,";
                csvContent += "<?php echo $evaluador['asignados'] > 0 ? round(($evaluador['evaluados'] * 100) / $evaluador['asignados']) : 0; ?>%\r\n";
                <?php endforeach; ?>
                
                // Create download link
                const encodedUri = encodeURI(csvContent);
                const link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "panamtrauma_abstract_analysis.csv");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                showAlert('CSV file downloaded successfully!', 'success');
            });
            
            // Table sorting function
            function sortTable(table, column) {
                const tbody = table.querySelector('tbody');
                const rows = Array.from(tbody.querySelectorAll('tr'));
                const isNumeric = column > 0; // Assuming only first column is text
                
                // Toggle sort direction
                const currentDir = table.getAttribute('data-sort-dir') || 'asc';
                const newDir = currentDir === 'asc' ? 'desc' : 'asc';
                table.setAttribute('data-sort-dir', newDir);
                
                // Update header indicators
                table.querySelectorAll('th').forEach(th => {
                    th.classList.remove('sorted-asc', 'sorted-desc');
                });
                table.querySelectorAll('th')[column].classList.add(`sorted-${newDir}`);
                
                // Sort the rows
                rows.sort((a, b) => {
                    let aValue = a.cells[column].textContent.trim();
                    let bValue = b.cells[column].textContent.trim();
                    
                    if (isNumeric) {
                        // Extract numbers from text (remove % signs etc)
                        aValue = parseFloat(aValue.replace(/[^0-9.-]+/g, ""));
                        bValue = parseFloat(bValue.replace(/[^0-9.-]+/g, ""));
                    }
                    
                    if (newDir === 'asc') {
                        return isNumeric ? aValue - bValue : aValue.localeCompare(bValue);
                    } else {
                        return isNumeric ? bValue - aValue : bValue.localeCompare(aValue);
                    }
                });
                
                // Remove existing rows
                while (tbody.firstChild) {
                    tbody.removeChild(tbody.firstChild);
                }
                
                // Add sorted rows
                rows.forEach(row => {
                    tbody.appendChild(row);
                });
                
                // Show sorting notification
                showAlert(`Table sorted by ${table.querySelectorAll('th')[column].textContent.trim()}`, 'info');
            }
            
            // Custom alert function
            function showAlert(message, type = 'info') {
                // Remove any existing alerts
                document.querySelectorAll('.alert-float').forEach(alert => {
                    document.body.removeChild(alert);
                });
                
                // Create new alert
                const alertDiv = document.createElement('div');
                alertDiv.className = `alert alert-${type} alert-float alert-dismissible fade show`;
                alertDiv.setAttribute('role', 'alert');
                
                // Add icon based on alert type
                let icon = 'info-circle';
                if (type === 'success') icon = 'check-circle';
                if (type === 'danger') icon = 'exclamation-circle';
                if (type === 'warning') icon = 'exclamation-triangle';
                
                alertDiv.innerHTML = `
                    <i class="fas fa-${icon} me-2"></i>
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                `;
                
                document.body.appendChild(alertDiv);
                
                // Auto dismiss after 3 seconds
                setTimeout(() => {
                    if (document.body.contains(alertDiv)) {
                        alertDiv.classList.remove('show');
                        setTimeout(() => {
                            if (document.body.contains(alertDiv)) {
                                document.body.removeChild(alertDiv);
                            }
                        }, 300);
                    }
                }, 3000);
            }
        });
        
        // Configuración de paginación
const paginationConfig = {
    itemsPerPage: 10,  // Número de evaluadores por página
    currentPage: 1     // Página inicial
};

// Función para inicializar la paginación
function initEvaluatorsPagination() {
    const table = document.getElementById('evaluatorsTable');
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    
    // Obtener elementos de paginación
    const paginationElement = document.querySelector('nav[aria-label="Evaluators pagination"]');
    const paginationUl = paginationElement.querySelector('ul.pagination');
    const prevButton = paginationElement.querySelector('.page-item:first-child');
    const nextButton = paginationElement.querySelector('.page-item:last-child');
    
    // Calcular el número total de páginas
    const totalPages = Math.ceil(rows.length / paginationConfig.itemsPerPage);
    
    // Si solo hay una página, ocultar la paginación
    if (totalPages <= 1) {
        paginationElement.style.display = 'none';
        return;
    }
    
    // Limpiar los elementos de páginas existentes (mantener solo prev y next)
    const pageItems = Array.from(paginationUl.querySelectorAll('.page-item'));
    pageItems.forEach((item, index) => {
        // Mantener solo el primero (prev) y el último (next)
        if (index !== 0 && index !== pageItems.length - 1) {
            paginationUl.removeChild(item);
        }
    });
    
    // Crear elementos de páginas
    for (let i = totalPages; i >= 1; i--) {
        const pageItem = document.createElement('li');
        pageItem.className = 'page-item' + (i === 1 ? ' active' : '');
        
        const pageLink = document.createElement('a');
        pageLink.className = 'page-link';
        pageLink.href = '#';
        pageLink.textContent = i;
        pageLink.setAttribute('data-page', i);
        
        pageItem.appendChild(pageLink);
        
        // Insertar después del botón Prev
        paginationUl.insertBefore(pageItem, prevButton.nextSibling);
    }
    
    // Actualizar el estado de los botones
    updatePaginationButtons();
    
    // Mostrar la primera página inicialmente
    showPage(paginationConfig.currentPage);
    
    // Agregar eventos a los enlaces de paginación
    paginationUl.addEventListener('click', function(e) {
        e.preventDefault();
        
        if (e.target.tagName === 'A') {
            // Botón Anterior
            if (e.target.parentNode === prevButton) {
                if (paginationConfig.currentPage > 1) {
                    paginationConfig.currentPage--;
                    showPage(paginationConfig.currentPage);
                    updateActivePage();
                    updatePaginationButtons();
                }
            } 
            // Botón Siguiente
            else if (e.target.parentNode === nextButton) {
                if (paginationConfig.currentPage < totalPages) {
                    paginationConfig.currentPage++;
                    showPage(paginationConfig.currentPage);
                    updateActivePage();
                    updatePaginationButtons();
                }
            } 
            // Botones de número de página
            else if (e.target.hasAttribute('data-page')) {
                const page = parseInt(e.target.getAttribute('data-page'));
                if (page !== paginationConfig.currentPage) {
                    paginationConfig.currentPage = page;
                    showPage(page);
                    updateActivePage();
                    updatePaginationButtons();
                }
            }
        }
    });
    
    // Función para mostrar una página específica
    function showPage(page) {
        const startIndex = (page - 1) * paginationConfig.itemsPerPage;
        const endIndex = startIndex + paginationConfig.itemsPerPage;
        
        rows.forEach((row, index) => {
            if (index >= startIndex && index < endIndex) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }
    
    // Función para actualizar la página activa
    function updateActivePage() {
        const pageItems = paginationUl.querySelectorAll('.page-item');
        pageItems.forEach(item => {
            item.classList.remove('active');
            const link = item.querySelector('a');
            if (link && link.hasAttribute('data-page')) {
                const page = parseInt(link.getAttribute('data-page'));
                if (page === paginationConfig.currentPage) {
                    item.classList.add('active');
                }
            }
        });
    }
    
    // Función para actualizar el estado de los botones anterior/siguiente
    function updatePaginationButtons() {
        if (paginationConfig.currentPage === 1) {
            prevButton.classList.add('disabled');
        } else {
            prevButton.classList.remove('disabled');
        }
        
        if (paginationConfig.currentPage === totalPages) {
            nextButton.classList.add('disabled');
        } else {
            nextButton.classList.remove('disabled');
        }
    }
}

// Inicializar la paginación cuando el DOM esté listo
document.addEventListener('DOMContentLoaded', function() {
    // Asegurarse de que la inicialización de paginación se ejecute después de que
    // se hayan cargado los otros scripts
    setTimeout(initEvaluatorsPagination, 100);

    // Asegurarse de que la paginación se actualice si se filtra la tabla
    document.getElementById('evaluatorSearch').addEventListener('input', function() {
        // Pequeño retraso para asegurar que la búsqueda se complete primero
        setTimeout(() => {
            // Resetear a la primera página cuando se busca
            paginationConfig.currentPage = 1;
            initEvaluatorsPagination();
        }, 300);
    });
});
    </script>
</body>
</html>