@model foundation_system.Models.ViewModels.AsistenciaGridViewModel
@{
    ViewData["Title"] = "Control de Asistencia";

    var diasSeleccionadosList = new List<string>();
    if (!string.IsNullOrEmpty(Model.DiasSemanaSeleccionados))
    {
        diasSeleccionadosList = Model.DiasSemanaSeleccionados
            .Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(d => d.Trim())
            .ToList();
    }

    var diasAMostrar = Model.DiasDelMes
        .Where(d => diasSeleccionadosList.Count == 0 ||
                    diasSeleccionadosList.Contains(((int)d.DayOfWeek).ToString()))
        .ToList();
}

<div class="container-fluid">
    <div class="card mb-4">
        <div class="card-header text-white d-flex align-items-center" style="background: linear-gradient(180deg, #2c3e50 0%, #1a2530 100%);">
            <h5 class="mb-0 text-white"><i class="bi bi-funnel"></i> Filtros</h5>
        </div>
        <div class="card-body">
            <form method="get" id="filtroForm" class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">Año</label>
                    <select name="año" class="form-select" id="selectAnio">
                        @foreach (var año in (List<SelectListItem>)ViewBag.Años)
                        {
                            <option value="@año.Value" selected="@año.Selected">
                                @año.Text
                            </option>
                        }
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Mes</label>
                    <select name="mes" class="form-select" id="selectMes">
                        @foreach (var mes in (List<SelectListItem>)ViewBag.Meses)
                        {
                            <option value="@mes.Value" selected="@(mes.Value == Model.Mes.ToString())">
                                @mes.Text
                            </option>
                        }
                    </select>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Días de la semana</label>
                    <div class="dias-semana-checkboxes">
                        @foreach (var dia in (List<SelectListItem>)ViewBag.DiasSemana)
                        {
                            var isChecked = diasSeleccionadosList.Contains(dia.Value);
                            <div class="form-check form-check-inline">
                                <input class="form-check-input dia-checkbox"
                                       type="checkbox"
                                       value="@dia.Value"
                                       id="dia@(dia.Value)"
                                       @(isChecked ? "checked" : "")>
                                <label class="form-check-label" for="dia@(dia.Value)">
                                    @dia.Text
                                </label>
                            </div>
                        }
                        <input type="hidden" name="diasSemana" id="diasSemanaInput"
                               value="@Model.DiasSemanaSeleccionados">
                    </div>
                </div>

                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn w-100"
                            style="background: linear-gradient(180deg, #2c3e50 0%, #1a2530 100%); color: white;">
                        <i class="bi bi-search text-white"></i> Filtrar
                    </button>
                </div>
            </form>
        </div>
    </div>



    <div class="card">
        <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <i class="bi bi-calendar-check"></i>
                Asistencia - @Model.NombreMes @Model.Año
                <span class="badge bg-light text-dark ms-2">@Model.Expedientes.Count niños</span>
            </h5>
            <div>
                <button class="btn btn-light btn-sm" id="btnExportar">
                    <i class="bi bi-file-earmark-excel"></i> Exportar
                </button>
                <button class="btn btn-info btn-sm" id="btnReporte">
                    <i class="bi bi-file-earmark-pdf"></i> Reporte Mensual
                </button>
            </div>
        </div>

        <div class="card-body p-0">
            <div class="table-responsive" style="max-height: 70vh; overflow-y: auto;">
                <table class="table table-bordered table-hover table-sm" id="tablaAsistencia">
                    <thead class="table-dark sticky-top">
                    <tr>
                        <th class="sticky-left bg-dark text-white border-secondary" style="min-width: 200px;">
                            <div class="text-white">Nombre</div>
                            <div class="small text-light">Edad</div>
                        </th>
                        @foreach (var dia in Model.DiasDelMes)
                        {
                            var diaSemana = ((int)dia.DayOfWeek).ToString();
                            var isChecked = Model.DiasSemanaSeleccionados?.Contains(diaSemana) ?? true;

                            if (!string.IsNullOrEmpty(Model.DiasSemanaSeleccionados) && !isChecked)
                            {
                                continue;
                            }

                            var nombreDia = dia.ToString("ddd", new System.Globalization.CultureInfo("es-ES"));
                            var esFinDeSemana = dia.DayOfWeek == DayOfWeek.Saturday || dia.DayOfWeek == DayOfWeek.Sunday;

                            <th class="text-center text-dark border-secondary @(esFinDeSemana ? "" : "")" style="min-width: 50px;">
                                <div class="text-dark">@dia.Day</div>
                                <div class="small text-muted">@nombreDia</div>
                            </th>
                        }
                    </tr>
                    </thead>
                    <tbody>
                    @foreach (var expediente in Model.Expedientes)
                    {
                        var nombreCompleto = $"{expediente.Persona.Nombres} {expediente.Persona.Apellidos}".Trim();
                        var edad = 0;
                        if (expediente.Persona.FechaNacimiento.HasValue)
                        {
                            var birthDate = expediente.Persona.FechaNacimiento.Value;
                            var today = DateOnly.FromDateTime(DateTime.Today);
                            edad = today.Year - birthDate.Year;
                            if (birthDate > today.AddYears(-edad))
                            {
                                edad--;
                            }
                        }

                        <tr data-expediente-id="@expediente.Id">
                            <td class="sticky-left bg-white" style="min-width: 200px;">
                                <div class="d-flex align-items-center">
                                    <a href="javascript:void(0)" class="btn-reporte-individual text-decoration-none" 
                                       data-id="@expediente.Id" title="Ver reporte individual">
                                        <i class="bi bi-file-earmark-person text-info me-2"></i>
                                    </a>
                                    <div>
                                        <div class="fw-bold">@nombreCompleto</div>
                                        <div class="small text-muted">Edad: @edad años</div>
                                    </div>
                                </div>
                            </td>

                            @foreach (var dia in Model.DiasDelMes)
                            {
                                var diaSemana = ((int)dia.DayOfWeek).ToString();
                                var isChecked = Model.DiasSemanaSeleccionados?.Contains(diaSemana) ?? true;

                                if (!string.IsNullOrEmpty(Model.DiasSemanaSeleccionados) && !isChecked)
                                {
                                    continue;
                                }

                                var key = $"{expediente.Id}_{dia:yyyy-MM-dd}";
                                var estadoActual = Model.Asistencias.ContainsKey(key)
                                    ? Model.Asistencias[key]
                                    : "";

                                var claseEstado = estadoActual switch
                                {
                                    "P" => "celda-presente",
                                    "T" => "celda-tarde",
                                    "F" => "celda-falta",
                                    _ => ""
                                };

                                var esFinDeSemana = dia.DayOfWeek == DayOfWeek.Saturday || dia.DayOfWeek == DayOfWeek.Sunday;

                                <td class="text-center p-0 celda-asistencia @claseEstado @(esFinDeSemana ? "bg-light" : "")"
                                    data-expediente="@expediente.Id"
                                    data-fecha="@dia.ToString("yyyy-MM-dd")"
                                    style="min-width: 50px;">

                                    <select class="form-select form-select-sm estado-select border-0 h-100 w-100"
                                            data-initial="@estadoActual">
                                        <option value=""></option>
                                        <option value="P" selected="@(estadoActual == "P")" class="bg-success text-white">P</option>
                                        <option value="T" selected="@(estadoActual == "T")" class="bg-warning">T</option>
                                        <option value="F" selected="@(estadoActual == "F")" class="bg-danger text-white">F</option>
                                        <option value="J" selected="@(estadoActual == "J")" class="bg-info text-white">J</option>
                                        <option value="E" selected="@(estadoActual == "E")" class="bg-secondary text-white">E</option>
                                    </select>
                                </td>
                            }
                        </tr>
                    }
                    </tbody>
                    <tfoot class="table-dark">
                    <tr>
                        <td class="sticky-left bg-dark text-white fw-bold">
                            <div>TOTALES POR DÍA</div>
                            <div class="small text-light">P/T/F</div>
                        </td>

                        @foreach (var dia in Model.DiasDelMes)
                        {
                            var diaSemana = ((int)dia.DayOfWeek).ToString();
                            var isChecked = Model.DiasSemanaSeleccionados?.Contains(diaSemana) ?? true;

                            if (!string.IsNullOrEmpty(Model.DiasSemanaSeleccionados) && !isChecked)
                            {
                                continue;
                            }

                            var esFinDeSemana = dia.DayOfWeek == DayOfWeek.Saturday || dia.DayOfWeek == DayOfWeek.Sunday;

                            var totalPresente = 0;
                            var totalTarde = 0;
                            var totalFalta = 0;
                            var totalJustificado = 0;
                            var totalEnfermo = 0;

                            foreach (var expediente in Model.Expedientes)
                            {
                                var key = $"{expediente.Id}_{dia:yyyy-MM-dd}";
                                if (Model.Asistencias.ContainsKey(key))
                                {
                                    var estado = Model.Asistencias[key];
                                    switch (estado)
                                    {
                                        case "P": totalPresente++; break;
                                        case "T": totalTarde++; break;
                                        case "F": totalFalta++; break;
                                        case "J": totalJustificado++; break;
                                        case "E": totalEnfermo++; break;
                                    }
                                }
                            }

                            var totalDia = totalPresente + totalTarde + totalFalta + totalJustificado + totalEnfermo;

                            <td class="text-center p-1 @(esFinDeSemana ? "bg-secondary" : "bg-dark") text-white"
                                style="min-width: 65px; font-size: 0.85rem;">
                                <div class="fw-bold mb-1">@totalDia</div>
                                <div class="d-flex justify-content-center gap-1 flex-wrap">
                                    <span class="badge bg-success" title="Presentes">@totalPresente</span>
                                    <span class="badge bg-warning text-dark" title="Tardes">@totalTarde</span>
                                    <span class="badge bg-danger" title="Faltas">@totalFalta</span>
                                    <span class="badge bg-info" title="Justificados">@totalJustificado</span>
                                    <span class="badge bg-secondary" title="Enfermos">@totalEnfermo</span>
                                </div>
                            </td>
                        }
                    </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <div class="card-footer">
            <div class="row">
                <div class="col-md-6">
                    <div class="leyenda">
                        <span class="badge bg-success me-2">P = Presente</span>
                        <span class="badge bg-warning me-2 text-dark">T = Tarde</span>
                        <span class="badge bg-danger me-2">F = Falto</span>
                        <span class="badge bg-info me-2">J = Justificado</span>
                        <span class="badge bg-secondary me-2">E = Enfermo</span>
                        <span class="text-muted ms-3">(Vacío = No registrado)</span>
                    </div>
                </div>
                <div class="col-md-6 text-end">
                    <small class="text-muted">
                        Total: @Model.Expedientes.Count niños × @diasAMostrar.Count días =
                        @(Model.Expedientes.Count * diasAMostrar.Count) registros posibles
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCarga" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-body text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Cargando...</span>
                </div>
                <p class="mt-2">Guardando cambios...</p>
            </div>
        </div>
    </div>
</div>

@section Styles {
    <style>
        #estadisticasContainer {
            min-height: 90px;
            transition: min-height 0.3s ease;
        }

        #estadisticasContainer .card {
            height: 100%;
            min-height: 90px;
            display: flex;
            flex-direction: column;
        }

        #estadisticasContainer .card-body {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        #estadisticasContainer .spinner-border {
            width: 1.75rem;
            height: 1.75rem;
        }

        #estadisticasContainer .alert {
            margin: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 90px;
        }

        tfoot.table-dark td {
            vertical-align: middle !important;
            border-color: #495057 !important;
        }

        tfoot .badge {
            font-size: 0.7rem;
            padding: 0.25em 0.5em;
            min-width: 24px;
        }

        tfoot tr:first-child td {
            border-top: 2px solid #6c757d;
        }

        tfoot tr.bg-success td {
            border-top: 2px solid #198754;
        }

        tfoot td[colspan] {
            background: linear-gradient(135deg, #198754 0%, #146c43 100%) !important;
            color: white !important;
        }

        tfoot td[colspan] .badge {
            font-size: 0.8rem;
            padding: 0.4em 0.8em;
        }

        tfoot td[colspan] .text-light {
            color: rgba(255, 255, 255, 0.9) !important;
        }

        tfoot.table-dark .sticky-left {
            background: #343a40 !important;
            color: white !important;
        }

        tfoot.table-dark td.bg-dark {
            background-color: #343a40 !important;
        }

        tfoot.table-dark td.bg-secondary {
            background-color: #6c757d !important;
        }

        tfoot.table-dark .text-white,
        tfoot.table-dark .text-light {
            color: white !important;
        }

        tfoot.table-dark .text-muted {
            color: rgba(255, 255, 255, 0.7) !important;
        }

        .table th, .table td {
            vertical-align: middle;
        }

        .celda-presente {
            background-color: #d1e7dd !important;
        }

        .celda-tarde {
            background-color: #fff3cd !important;
        }

        .celda-falta {
            background-color: #f8d7da !important;
        }

        .celda-justificado {
            background-color: #cff4fc !important;
        }

        .celda-enfermo {
            background-color: #e2e3e5 !important;
        }

        .estado-select {
            cursor: pointer;
            transition: all 0.2s;
            border: 1px solid transparent !important;
            text-align: center;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
        }

        .estado-select::-ms-expand {
            display: none;
        }

        .estado-select:focus {
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
            outline: none;
        }

        .estado-select.bg-success {
            background-color: #198754 !important;
            color: white !important;
            border-color: #198754 !important;
        }

        .estado-select.bg-warning {
            background-color: #ffc107 !important;
            color: black !important;
            border-color: #ffc107 !important;
        }

        .estado-select.bg-danger {
            background-color: #dc3545 !important;
            color: white !important;
            border-color: #dc3545 !important;
        }

        .estado-select.bg-info {
            background-color: #0dcaf0 !important;
            color: white !important;
            border-color: #0dcaf0 !important;
        }

        .estado-select.bg-secondary {
            background-color: #6c757d !important;
            color: white !important;
            border-color: #6c757d !important;
        }

        .estado-select:not([value]):not([value=""]) {
            background-color: white !important;
            color: black !important;
        }

        .celda-asistencia.changed {
            outline: 2px solid #0d6efd;
            outline-offset: -2px;
        }

        .sticky-left {
            position: sticky;
            left: 0;
            background: white;
            z-index: 5;
        }

        .dias-semana-checkboxes {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #dee2e6;
        }

        .bg-lunes { background-color: #e3f2fd !important; }
        .bg-martes { background-color: #f3e5f5 !important; }
        .bg-miercoles { background-color: #e8f5e8 !important; }
        .bg-jueves { background-color: #fff3e0 !important; }
        .bg-viernes { background-color: #fce4ec !important; }
        .bg-sabado { background-color: #f1f8e9 !important; }
        .bg-domingo { background-color: #fff8e1 !important; }

        .table-dark.sticky-top {
            z-index: 10;
        }

        .card .display-6 {
            font-size: 2rem;
            font-weight: bold;
        }

        .progress {
            background-color: rgba(255, 255, 255, 0.3);
        }

        .celda-asistencia:hover {
            background-color: #f8f9fa !important;
        }

        .celda-presente:hover {
            background-color: #c3e6cb !important;
        }

        .celda-tarde:hover {
            background-color: #ffeaa7 !important;
        }

        .celda-falta:hover {
            background-color: #f5c6cb !important;
        }

        .celda-justificado:hover {
            background-color: #b6effb !important;
        }

        .celda-enfermo:hover {
            background-color: #d3d6d8 !important;
        }

        @@media (max-width: 768px) {
            .table-responsive {
                font-size: 0.85rem;
            }

            .estado-select {
                padding: 0.25rem;
                font-size: 0.8rem;
            }

            .dias-semana-checkboxes .form-check-inline {
                display: block;
                margin-right: 0;
                margin-bottom: 5px;
            }
        }

        .celda-asistencia, .estado-select {
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .bg-light {
            background-color: #f8f9fa !important;
        }

        .leyenda .badge {
            font-size: 0.8rem;
            padding: 0.4em 0.8em;
        }

        .celda-asistencia {
            min-width: 65px !important;
        }

        .table th.text-center {
            min-width: 65px !important;
        }

        .sticky-left {
            min-width: 240px !important;
        }

        .estado-select {
            padding: 10px 4px !important;
            font-size: 14px !important;
        }
    </style>
}

@section Scripts {
    <script>
        $(document).ready(function () {
            cargarEstadisticas();

            $('.dia-checkbox').change(function () {
                var diasSeleccionados = $('.dia-checkbox:checked').map(function () {
                    return $(this).val();
                }).get().join(',');
                $('#diasSemanaInput').val(diasSeleccionados);
            });

            inicializarColores();

            $('#btnGuardarTodo').click(function () {
                var cambios = [];
                var celdasCambiadas = $('.celda-asistencia.changed');

                if (celdasCambiadas.length === 0) {
                    toastr.info('No hay cambios para guardar');
                    return;
                }

                if (!confirm(`¿Guardar ${celdasCambiadas.length} cambios?`)) {
                    return;
                }

                $('#modalCarga').modal('show');

                celdasCambiadas.each(function () {
                    var celda = $(this);
                    var select = celda.find('.estado-select');
                    var expedienteId = celda.data('expediente');
                    var fecha = celda.data('fecha');
                    var estado = select.val();

                    cambios.push({
                        expedienteId: expedienteId,
                        fecha: fecha,
                        estado: estado
                    });
                });

                $.ajax({
                    url: '@Url.Action("GuardarAsistenciasMasivas", "Asistencia")',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(cambios),
                    success: function (response) {
                        $('#modalCarga').modal('hide');
                        if (response.success) {
                            $('.celda-asistencia').removeClass('changed');
                            $('.estado-select').each(function () {
                                $(this).data('initial', $(this).val());
                            });
                            toastr.success(response.message);
                            cargarEstadisticas();
                        } else {
                            toastr.error(response.message);
                        }
                    },
                    error: function () {
                        $('#modalCarga').modal('hide');
                        toastr.error('Error al guardar los cambios');
                    }
                });
            });

            $('#btnExportar').click(function () {
                var año = $('#selectAnio').val();
                var mes = $('#selectMes').val();
                var diasSemana = $('#diasSemanaInput').val();

                var url = '@Url.Action("ExportarExcel", "Asistencia")' +
                    '?año=' + año +
                    '&mes=' + mes +
                    '&diasSemana=' + diasSemana;

                window.open(url, '_blank');
            });

            $('#btnReporte').click(function () {
                var año = $('#selectAnio').val();
                var mes = $('#selectMes').val();
                var diasSemana = $('#diasSemanaInput').val();

                var url = '@Url.Action("ReporteMensual", "Asistencia")' +
                    '?año=' + año +
                    '&mes=' + mes +
                    '&diasSemana=' + diasSemana;

                window.open(url, '_blank');
            });

            $('.btn-reporte-individual').click(function () {
                var ninoId = $(this).data('id');
                var año = $('#selectAnio').val();
                var mes = $('#selectMes').val();
                var diasSemana = $('#diasSemanaInput').val();

                var url = '@Url.Action("ReporteIndividual", "Asistencia")' +
                    '?ninoId=' + ninoId +
                    '&año=' + año +
                    '&mes=' + mes +
                    '&diasSemana=' + diasSemana;

                window.open(url, '_blank');
            });

            $('#selectAnio, #selectMes').change(function () {
                $('#filtroForm').submit();
            });

            aplicarColoresDias();

            $('.estado-select').change(function () {
                var estado = $(this).val();
                var celda = $(this).closest('.celda-asistencia');
                var initial = $(this).data('initial');

                aplicarColorSelect($(this), estado);
                aplicarColorCelda(celda, estado);

                if (initial !== estado) {
                    celda.addClass('changed');
                } else {
                    celda.removeClass('changed');
                }

                actualizarFooterTabla();

                var expedienteId = celda.data('expediente');
                var fecha = celda.data('fecha');

                guardarAsistencia(expedienteId, fecha, estado, celda);
            });
        });

        function aplicarColorCelda(celda, estado) {
            celda.removeClass('celda-presente celda-tarde celda-falta celda-justificado celda-enfermo');
            switch (estado) {
                case 'P': celda.addClass('celda-presente'); break;
                case 'T': celda.addClass('celda-tarde'); break;
                case 'F': celda.addClass('celda-falta'); break;
                case 'J': celda.addClass('celda-justificado'); break;
                case 'E': celda.addClass('celda-enfermo'); break;
            }
        }

        function aplicarColorSelect(select, estado) {
            select.removeClass('bg-success bg-warning bg-danger bg-info bg-secondary text-white');
            switch (estado) {
                case 'P': select.addClass('bg-success text-white'); break;
                case 'T': select.addClass('bg-warning'); break;
                case 'F': select.addClass('bg-danger text-white'); break;
                case 'J': select.addClass('bg-info text-white'); break;
                case 'E': select.addClass('bg-secondary text-white'); break;
            }
        }

        function inicializarColores() {
            $('.estado-select').each(function () {
                var estado = $(this).val();
                var celda = $(this).closest('.celda-asistencia');
                aplicarColorSelect($(this), estado);
                aplicarColorCelda(celda, estado);
            });
        }

        function guardarAsistencia(expedienteId, fecha, estado, celda) {
            $.ajax({
                url: '@Url.Action("GuardarAsistencia", "Asistencia")',
                type: 'POST',
                data: {
                    expedienteId: expedienteId,
                    fecha: fecha,
                    estado: estado
                },
                success: function (response) {
                    if (response.success) {
                        celda.removeClass('changed');
                        celda.find('.estado-select').data('initial', estado);
                        toastr.success('Guardado correctamente');
                        actualizarFooterTabla();
                    } else {
                        toastr.error(response.message);
                        var select = celda.find('.estado-select');
                        var initial = select.data('initial');
                        aplicarColorSelect(select, initial);
                        aplicarColorCelda(celda, initial);
                        select.val(initial);
                    }
                },
                error: function () {
                    toastr.error('Error de conexión');
                    var select = celda.find('.estado-select');
                    var initial = select.data('initial');
                    aplicarColorSelect(select, initial);
                    aplicarColorCelda(celda, initial);
                    select.val(initial);
                }
            });
        }

        function cargarEstadisticas() {
            // Statistics cards removed from UI
            actualizarFooterTabla();
        }

        function actualizarFooterTabla() {
            $('tfoot tr td').each(function (index) {
                if (index === 0) return;
                var td = $(this);
                var colIndex = td.index();
                if (td.hasClass('text-center')) {
                    var totalPresente = 0, totalTarde = 0, totalFalta = 0, totalJustificado = 0, totalEnfermo = 0;
                    $('tbody tr').each(function () {
                        var celda = $(this).find('td').eq(colIndex);
                        if (celda.length) {
                            var estado = celda.find('.estado-select').val();
                            if (estado === 'P') totalPresente++;
                            else if (estado === 'T') totalTarde++;
                            else if (estado === 'F') totalFalta++;
                            else if (estado === 'J') totalJustificado++;
                            else if (estado === 'E') totalEnfermo++;
                        }
                    });
                    var totalDia = totalPresente + totalTarde + totalFalta + totalJustificado + totalEnfermo;
                    td.html(`
                        <div class="fw-bold mb-1">${totalDia}</div>
                        <div class="d-flex justify-content-center gap-1 flex-wrap">
                            <span class="badge bg-success" title="Presentes">${totalPresente}</span>
                            <span class="badge bg-warning text-dark" title="Tardes">${totalTarde}</span>
                            <span class="badge bg-danger" title="Faltas">${totalFalta}</span>
                            <span class="badge bg-info" title="Justificados">${totalJustificado}</span>
                            <span class="badge bg-secondary" title="Enfermos">${totalEnfermo}</span>
                        </div>
                    `);
                }
            });
        }

        function aplicarColoresDias() {
            $('th.text-center').each(function () {
                var textoDia = $(this).find('.small').text().trim();
                var claseColor = '';
                switch (textoDia) {
                    case 'lun': claseColor = 'bg-lunes'; break;
                    case 'mar': claseColor = 'bg-martes'; break;
                    case 'mié': claseColor = 'bg-miercoles'; break;
                    case 'jue': claseColor = 'bg-jueves'; break;
                    case 'vie': claseColor = 'bg-viernes'; break;
                    case 'sáb': claseColor = 'bg-sabado'; break;
                    case 'dom': claseColor = 'bg-domingo'; break;
                }
                if (claseColor) $(this).addClass(claseColor);
            });
        }
    </script>
}
