<?php
// archivo: get_lineCuestionariosSatisfaccionChartData.php


header('Content-Type: application/json');
include 'db_config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Modalidades específicas (en minúsculas y sin acentos)
$modalitiesSpecific = [
    "baja intensidad y equilibrio",
    "resistencia moderada",
    "aerobicos adaptados"
];

// Función para eliminar acentos
function removeAccents($string) {
    return iconv('UTF-8', 'ASCII//TRANSLIT', $string);
}

// Definir los nombres de los campos de interés
$fields = [
    'bienestar_pre',
    'bienestar_post',
    'motivacion_pre',
    'motivacion_post'
];

$data = [];
foreach ($fields as $f) {
    $data[$f] = [];
}
$allDates = [];

// Consulta SQL: agrupar por modalidad y mes y sumar los puntajes
$sql = "SELECT 
            LOWER(TRIM(modalidad_deporte)) AS modality,
            DATE_FORMAT(fecha_registro, '%Y-%m') AS mes,
            SUM(bienestar_pre) AS sum_bienestar_pre,
            SUM(bienestar_post) AS sum_bienestar_post,
            SUM(motivacion_pre) AS sum_motivacion_pre,
            SUM(motivacion_post) AS sum_motivacion_post
        FROM cuestionarios_satisfaccion
        GROUP BY modality, mes
        ORDER BY mes ASC, modality ASC";

$result = $conn->query($sql);
if (!$result) {
    die("Error en la consulta: " . $conn->error);
}

while ($row = $result->fetch_assoc()) {
    $mod = $row['modality'];
    $modNormalized = removeAccents($mod);
    if (!in_array($modNormalized, $modalitiesSpecific)) {
        $modNormalized = "ninguna";
    }
    $mes = $row['mes'];
    $allDates[$mes] = true;
    
    $data['bienestar_pre'][$modNormalized][$mes] = (int)$row['sum_bienestar_pre'];
    $data['bienestar_post'][$modNormalized][$mes] = (int)$row['sum_bienestar_post'];
    $data['motivacion_pre'][$modNormalized][$mes] = (int)$row['sum_motivacion_pre'];
    $data['motivacion_post'][$modNormalized][$mes] = (int)$row['sum_motivacion_post'];
}

$conn->close();

// Crear array de fechas ordenadas
$dates = array_keys($allDates);
sort($dates);

// Calcular totales acumulados por modalidad para cada grupo
$totals_bienestar = [];
$totals_motivacion = [];
foreach (["baja intensidad y equilibrio", "resistencia moderada", "aerobicos adaptados", "ninguna"] as $mod) {
    $totals_bienestar[$mod] = 0;
    $totals_motivacion[$mod] = 0;
}
foreach ($data['bienestar_pre'] as $mod => $values) {
    foreach ($values as $mes => $val) {
        $totals_bienestar[$mod] += $val;
    }
}
foreach ($data['bienestar_post'] as $mod => $values) {
    foreach ($values as $mes => $val) {
        $totals_bienestar[$mod] += $val;
    }
}
foreach ($data['motivacion_pre'] as $mod => $values) {
    foreach ($values as $mes => $val) {
        $totals_motivacion[$mod] += $val;
    }
}
foreach ($data['motivacion_post'] as $mod => $values) {
    foreach ($values as $mes => $val) {
        $totals_motivacion[$mod] += $val;
    }
}

// Estructura final
$output = [
    "dates" => $dates,
    "bienestar_pre" => $data['bienestar_pre'],
    "bienestar_post" => $data['bienestar_post'],
    "motivacion_pre" => $data['motivacion_pre'],
    "motivacion_post" => $data['motivacion_post'],
    "totals_bienestar" => $totals_bienestar,
    "totals_motivacion" => $totals_motivacion
];

echo json_encode($output);
?>
