<?php
// informe_consolidado.php
require 'conexion.php';

$sesiones = $pdo->query("SELECT * FROM sesiones ORDER BY id DESC")->fetchAll();
$mostrar_informe = false;
$datos_informe = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['sesiones_seleccionadas'])) {
    $mostrar_informe = true;
    
    // 1. Preparar los IDs de las sesiones seleccionadas
    $sesiones_ids = array_map('intval', $_POST['sesiones_seleccionadas']);
    $in_sesiones = implode(',', $sesiones_ids);

    // 2. KPIs Globales
    $total_alumnos = $pdo->query("SELECT COUNT(DISTINCT r.token_dispositivo) FROM respuestas r JOIN preguntas p ON r.pregunta_id = p.id WHERE p.sesion_id IN ($in_sesiones)")->fetchColumn();
    $total_votos = $pdo->query("SELECT COUNT(r.id) FROM respuestas r JOIN preguntas p ON r.pregunta_id = p.id WHERE p.sesion_id IN ($in_sesiones)")->fetchColumn();

    $datos_informe['kpis'] = [
        'alumnos' => $total_alumnos,
        'votos' => $total_votos,
        'sesiones_analizadas' => count($sesiones_ids)
    ];

    // ==========================================
    // 3. PREGUNTAS EVALUATIVAS (es_evaluable = 1)
    // ==========================================
    $sql_eval = "SELECT p.texto_pregunta, p.tipo_grafico, r.respuesta_texto, COUNT(*) as cantidad 
                 FROM respuestas r JOIN preguntas p ON r.pregunta_id = p.id 
                 WHERE p.sesion_id IN ($in_sesiones) AND p.es_evaluable = 1 AND p.estado = 'cerrada'
                 GROUP BY p.texto_pregunta, p.tipo_grafico, r.respuesta_texto 
                 ORDER BY p.texto_pregunta, cantidad DESC";
    $resultados_eval = $pdo->query($sql_eval)->fetchAll();

    $evaluativas_agrupadas = [];
    $mayor_consenso = ['pregunta' => '-', 'porcentaje' => 0];
    $mayor_dispersion = ['pregunta' => '-', 'porcentaje' => 100];

    foreach ($resultados_eval as $row) {
        $preg = $row['texto_pregunta'];
        if (!isset($evaluativas_agrupadas[$preg])) {
            $evaluativas_agrupadas[$preg] = ['texto' => $preg, 'tipo_grafico' => $row['tipo_grafico'], 'total_votos' => 0, 'respuestas' => []];
        }
        $evaluativas_agrupadas[$preg]['respuestas'][] = ['texto' => $row['respuesta_texto'], 'cantidad' => $row['cantidad']];
        $evaluativas_agrupadas[$preg]['total_votos'] += $row['cantidad'];
    }

    foreach ($evaluativas_agrupadas as $preg => $datos) {
        if ($datos['total_votos'] > 0) {
            $porcentaje = round(($datos['respuestas'][0]['cantidad'] / $datos['total_votos']) * 100);
            if ($mayor_consenso['porcentaje'] === 0 && $mayor_dispersion['porcentaje'] === 100) {
                $mayor_consenso = ['pregunta' => $preg, 'porcentaje' => $porcentaje];
                $mayor_dispersion = ['pregunta' => $preg, 'porcentaje' => $porcentaje];
            } else {
                if ($porcentaje >= $mayor_consenso['porcentaje']) $mayor_consenso = ['pregunta' => $preg, 'porcentaje' => $porcentaje];
                if ($porcentaje <= $mayor_dispersion['porcentaje']) $mayor_dispersion = ['pregunta' => $preg, 'porcentaje' => $porcentaje];
            }
        }
    }

    $datos_informe['evaluativas'] = array_values($evaluativas_agrupadas);
    $datos_informe['analisis'] = ['consenso' => $mayor_consenso, 'dispersion' => $mayor_dispersion];

    // ==========================================
    // 4. PREGUNTAS DEMOGRÁFICAS (es_evaluable = 0)
    // ==========================================
    $sql_demo = "SELECT p.texto_pregunta, r.respuesta_texto, COUNT(*) as cantidad 
                 FROM respuestas r JOIN preguntas p ON r.pregunta_id = p.id 
                 WHERE p.sesion_id IN ($in_sesiones) AND p.es_evaluable = 0 AND p.estado = 'cerrada'
                 GROUP BY p.texto_pregunta, r.respuesta_texto";
    $resultados_demo = $pdo->query($sql_demo)->fetchAll();

    $edades_rangos = [];
    $ciudades = [];
    $nubes_palabras = [];

    foreach ($resultados_demo as $row) {
        $texto_p = strtolower($row['texto_pregunta']);
        $respuesta = trim($row['respuesta_texto']);
        $cantidad = (int)$row['cantidad'];
        
        // A) Edad (Agrupamos en rangos para una pseudo-pirámide)
        if (strpos($texto_p, 'edad') !== false || strpos($texto_p, 'años') !== false) {
            $edad = intval($respuesta);
            if ($edad >= 15 && $edad <= 80) { // Filtro de cordura
                $rango_inicio = floor($edad / 3) * 3;
                $rango = $rango_inicio . '-' . ($rango_inicio + 2) . ' años';
                $edades_rangos[$rango] = ($edades_rangos[$rango] ?? 0) + $cantidad;
            }
        } 
        // B) Ciudad / País / Origen
        elseif (strpos($texto_p, 'ciudad') !== false || strpos($texto_p, 'donde') !== false || strpos($texto_p, 'dónde') !== false || strpos($texto_p, 'país') !== false || strpos($texto_p, 'pais') !== false) {
            if (!empty($respuesta)) {
                $ciudades[$respuesta] = ($ciudades[$respuesta] ?? 0) + $cantidad;
            }
        } 
        // C) Nubes de Palabras Independientes
        elseif (strpos($texto_p, 'expectativa') !== false) {
            $nubes_palabras['Expectativas sobre la asignatura'][] = [$respuesta, $cantidad];
        } 
        elseif (strpos($texto_p, 'habilidad') !== false) {
            $nubes_palabras['Habilidades profesionales'][] = [$respuesta, $cantidad];
        } 
        elseif (strpos($texto_p, 'medicina') !== false) {
            $nubes_palabras['Motivación para estudiar medicina'][] = [$respuesta, $cantidad];
        } 
        else {
            // Si hay otra pregunta demográfica que no coincida, la mostramos con su propio título
            $nubes_palabras[$row['texto_pregunta']][] = [$respuesta, $cantidad];
        }
    }

    // Ordenar datos demográficos para que se vean bien
    arsort($ciudades);
    ksort($edades_rangos); 

    $datos_informe['demografia'] = [
        'hay_datos' => (!empty($edades_rangos) || !empty($nubes_palabras) || !empty($ciudades)),
        'edades_rangos' => $edades_rangos,
        'lista_ciudades' => $ciudades,
        'total_votos_ciudades' => array_sum($ciudades),
        'nubes_palabras' => $nubes_palabras
    ];
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Informe Consolidado</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/wordcloud2.js/1.2.2/wordcloud2.min.js"></script>
    <style>
        body { background-color: #f8fafc; font-family: 'Segoe UI', sans-serif; }
        .card-custom { border: none; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); margin-bottom: 24px; background: white; }
        .kpi-value { font-size: 2.5rem; font-weight: bold; line-height: 1; margin-bottom: 5px; }
        .chart-box { height: 320px; width: 100%; display: flex; justify-content: center; align-items: center; }
        canvas { width: 100% !important; height: 100% !important; }
        .check-sesion:hover { background-color: #e9ecef !important; }
    </style>
</head>
<body class="p-4">

<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="fw-bold text-primary"><i class="bi bi-pie-chart-fill"></i> Analítica Multi-Sesión</h1>
        <a href="admin.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Volver al Panel</a>
    </div>

    <div class="card-custom p-4 border-top border-4 border-primary mb-5">
        <h4 class="fw-bold mb-3">Selecciona las sesiones a consolidar</h4>
        <form method="POST" class="row g-3">
            <?php foreach($sesiones as $s): ?>
                <div class="col-md-4 col-lg-3">
                    <div class="form-check border p-3 rounded bg-white shadow-sm check-sesion transition">
                        <input class="form-check-input mt-2" type="checkbox" name="sesiones_seleccionadas[]" value="<?= $s['id'] ?>" id="sesion_<?= $s['id'] ?>">
                        <label class="form-check-label w-100 fw-bold small text-truncate ms-1" for="sesion_<?= $s['id'] ?>" style="cursor:pointer;">
                            <?= $s['nombre_sesion'] ?> <br><small class="text-muted fw-normal"><i class="bi bi-calendar-event"></i> <?= date('d/m/Y', strtotime($s['fecha_creacion'])) ?></small>
                        </label>
                    </div>
                </div>
            <?php endforeach; ?>
            <?php if(count($sesiones) === 0): ?><p class="text-muted">No hay sesiones creadas.</p><?php endif; ?>
            
            <div class="col-12 mt-4 text-center">
                <button type="submit" class="btn btn-primary btn-lg px-5 rounded-pill shadow-sm"><i class="bi bi-magic"></i> Generar Informe</button>
            </div>
        </form>
    </div>

    <?php if($mostrar_informe): ?>
        
        <div class="row g-4 mb-5 text-center">
            <div class="col-md-4">
                <div class="card-custom p-4 border-bottom border-4 border-info h-100">
                    <h6 class="text-muted text-uppercase fw-bold"><i class="bi bi-people-fill"></i> Alcance Global</h6>
                    <div class="kpi-value text-info"><?= $datos_informe['kpis']['alumnos'] ?></div>
                    <p class="small text-muted mb-0">Estudiantes en <?= $datos_informe['kpis']['sesiones_analizadas'] ?> sesiones</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card-custom p-4 border-bottom border-4 border-success h-100">
                    <h6 class="text-muted text-uppercase fw-bold"><i class="bi bi-check-circle"></i> Mayor Consenso</h6>
                    <div class="kpi-value text-success"><?= $datos_informe['analisis']['consenso']['porcentaje'] ?>%</div>
                    <p class="small text-muted mb-0 fst-italic px-2">"<?= $datos_informe['analisis']['consenso']['pregunta'] ?>"</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card-custom p-4 border-bottom border-4 border-danger h-100">
                    <h6 class="text-muted text-uppercase fw-bold"><i class="bi bi-exclamation-triangle"></i> Tema Más Discutido</h6>
                    <div class="kpi-value text-danger"><?= $datos_informe['analisis']['dispersion']['porcentaje'] ?>%</div>
                    <p class="small text-muted mb-0 fst-italic px-2">"<?= $datos_informe['analisis']['dispersion']['pregunta'] ?>"</p>
                </div>
            </div>
        </div>

        <?php if($datos_informe['demografia']['hay_datos']): ?>
            <h3 class="fw-bold text-dark mb-4 border-bottom pb-2"><i class="bi bi-person-vcard text-secondary"></i> Análisis Sociodemográfico</h3>
            
            <?php if(!empty($datos_informe['demografia']['lista_ciudades'])): ?>
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card-custom p-4 border-start border-5 border-success">
                            <h5 class="fw-bold mb-4"><i class="bi bi-globe-americas text-success"></i> Distribución Geográfica</h5>
                            <div class="row g-3">
                                <?php 
                                    $ciudades = $datos_informe['demografia']['lista_ciudades'];
                                    $total_c = $datos_informe['demografia']['total_votos_ciudades'];
                                    foreach($ciudades as $ciudad => $cantidad): 
                                        $pct = round(($cantidad / $total_c) * 100);
                                ?>
                                <div class="col-lg-3 col-md-4 col-sm-6">
                                    <div class="p-3 border rounded bg-light h-100 shadow-sm">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span class="text-truncate fw-bold text-dark pe-2" title="<?= htmlspecialchars($ciudad) ?>" style="font-size: 0.95rem;">
                                                <?= htmlspecialchars($ciudad) ?>
                                            </span>
                                            <span class="badge bg-success rounded-pill"><?= $cantidad ?></span>
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <div class="progress flex-grow-1" style="height: 8px;">
                                                <div class="progress-bar bg-success opacity-75" role="progressbar" style="width: <?= $pct ?>%;"></div>
                                            </div>
                                            <span class="small text-muted ms-2 fw-bold" style="font-size: 0.8rem; min-width: 35px; text-align: right;"><?= $pct ?>%</span>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="row mb-5">
                <?php if(!empty($datos_informe['demografia']['edades_rangos'])): ?>
                <div class="col-md-5">
                    <div class="card-custom p-4 h-100 border-start border-5 border-warning">
                        <h5 class="fw-bold mb-4"><i class="bi bi-bar-chart-line-fill text-warning"></i> Distribución de Edades</h5>
                        <div class="chart-box" style="height: 250px;">
                            <canvas id="grafico-edades"></canvas>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php 
                    $col_class = empty($datos_informe['demografia']['edades_rangos']) ? "col-12" : "col-md-7";
                    if(!empty($datos_informe['demografia']['nubes_palabras'])): 
                ?>
                <div class="<?= $col_class ?>">
                    <div class="row g-4 h-100">
                        <?php foreach($datos_informe['demografia']['nubes_palabras'] as $consigna => $palabras): ?>
                            <div class="col-md-6">
                                <div class="card-custom p-4 h-100 bg-dark text-white shadow">
                                    <h6 class="fw-bold mb-3 text-center text-light"><?= $consigna ?></h6>
                                    <div class="chart-box" id="nube-demo-box-<?= md5($consigna) ?>" style="height: 200px;">
                                        <canvas id="nube-demo-<?= md5($consigna) ?>"></canvas>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <h3 class="fw-bold text-dark mb-4 border-bottom pb-2 mt-5"><i class="bi bi-journal-check text-primary"></i> Resultados de Evaluación</h3>
        <div class="row">
            <?php foreach($datos_informe['evaluativas'] as $index => $preg): ?>
                <div class="col-lg-6 mb-4">
                    <div class="card-custom p-4 border-start border-5 border-primary h-100">
                        <div class="d-flex justify-content-between align-items-start">
                            <h6 class="text-primary fw-bold mb-2">Pregunta <?= $index + 1 ?></h6>
                            <span class="badge bg-light text-dark border"><i class="bi bi-people-fill"></i> <?= $preg['total_votos'] ?> votos</span>
                        </div>
                        <h5 class="fw-bold text-dark mb-4" style="min-height:48px;"><?= $preg['texto'] ?></h5>
                        
                        <div class="chart-box">
                            <canvas id="grafico_eval_<?= $index ?>"></canvas>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
            <?php if(empty($datos_informe['evaluativas'])): ?>
                <div class="col-12"><div class="alert alert-light text-center border">No se encontraron preguntas evaluativas marcadas en las sesiones seleccionadas.</div></div>
            <?php endif; ?>
        </div>

        <script>
            const paletaColores = ['#0d6efd', '#198754', '#dc3545', '#ffc107', '#0dcaf0', '#6610f2', '#fd7e14'];

            // 1. DIBUJAR PIRÁMIDE DE EDAD (Gráfico de Barras Horizontal)
            <?php if(!empty($datos_informe['demografia']['edades_rangos'])): ?>
                const ctxEdades = document.getElementById('grafico-edades').getContext('2d');
                const rangos = <?= json_encode(array_keys($datos_informe['demografia']['edades_rangos'])) ?>;
                const valsEdades = <?= json_encode(array_values($datos_informe['demografia']['edades_rangos'])) ?>;
                
                new Chart(ctxEdades, {
                    type: 'bar',
                    data: {
                        labels: rangos,
                        datasets: [{ label: 'Estudiantes', data: valsEdades, backgroundColor: '#ffc107', borderRadius: 4 }]
                    },
                    options: {
                        indexAxis: 'y', // ESTO LO CONVIERTE EN PIRÁMIDE (Horizontal)
                        responsive: true, maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: { x: { beginAtZero: true, ticks: { stepSize: 1 } } }
                    }
                });
            <?php endif; ?>

            // 2. DIBUJAR NUBES DE PALABRAS DEMOGRÁFICAS
            <?php if(!empty($datos_informe['demografia']['nubes_palabras'])): ?>
                <?php foreach($datos_informe['demografia']['nubes_palabras'] as $consigna => $palabras): ?>
                    (function(){
                        const idCanvas = 'nube-demo-<?= md5($consigna) ?>';
                        const idBox = 'nube-demo-box-<?= md5($consigna) ?>';
                        const canvas = document.getElementById(idCanvas);
                        const box = document.getElementById(idBox);
                        
                        canvas.width = box.clientWidth;
                        canvas.height = box.clientHeight;
                        
                        const datos = <?= json_encode($palabras) ?>;
                        const maxV = Math.max(...datos.map(d => d[1]), 1);
                        const lista = datos.map(d => [d[0], 20 + (d[1] / maxV) * 45]); // Tamaño de fuente ajustado
                        
                        WordCloud(canvas, { 
                            list: lista, 
                            weightFactor: 1, 
                            fontFamily: 'Segoe UI', 
                            color: 'random-light', // Color claro porque el fondo es oscuro
                            rotateRatio: 0,
                            backgroundColor: 'transparent'
                        });
                    })();
                <?php endforeach; ?>
            <?php endif; ?>

            // 3. DIBUJAR GRÁFICOS EVALUATIVOS
            const datosEvaluativos = <?= json_encode($datos_informe['evaluativas']) ?>;
            datosEvaluativos.forEach((preg, index) => {
                const ctx = document.getElementById('grafico_eval_' + index).getContext('2d');
                const etiquetas = preg.respuestas.map(r => r.texto);
                const valores = preg.respuestas.map(r => r.cantidad);
                const tipo = preg.tipo_grafico;

                if(tipo === 'barras' || tipo === 'torta') {
                    new Chart(ctx, {
                        type: tipo === 'torta' ? 'pie' : 'bar',
                        data: {
                            labels: etiquetas,
                            datasets: [{ label: 'Votos', data: valores, backgroundColor: tipo === 'torta' ? paletaColores.slice(0, etiquetas.length) : '#0d6efd', borderRadius: tipo === 'barras' ? 6 : 0 }]
                        },
                        options: {
                            responsive: true, maintainAspectRatio: false,
                            plugins: { legend: { display: tipo === 'torta', position: 'right' } },
                            scales: tipo === 'barras' ? { y: { beginAtZero: true, ticks: { stepSize: 1 } } } : { x: { display:false }, y: { display:false } }
                        }
                    });
                } else if (tipo === 'nube_palabras') {
                    const maxVotos = Math.max(...valores, 1);
                    const listaNube = preg.respuestas.map(r => [r.texto, 20 + (r.cantidad / maxVotos) * 60]);
                    
                    const canvas = document.getElementById('grafico_eval_' + index);
                    canvas.width = canvas.parentElement.clientWidth; canvas.height = canvas.parentElement.clientHeight;
                    WordCloud(canvas, { list: listaNube, weightFactor: 1, fontFamily: 'Segoe UI', color: 'random-dark', rotateRatio: 0 });
                }
            });
        </script>
    <?php endif; ?>
</div>

</body>
</html>
