<?php
// 1. SEGURIDAD Y CONTEXTO
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Accesso Denegado");
}

$DB_NAME = "MS_Datos"; 
$PREFIX = "1"; // Prefijo de tus tablas
$IDUg_SISTEMA = $_SESSION['IDUg'] ?? 1; 
$hoy_idx = date('N'); 
$mañana_idx = ($hoy_idx == 7) ? 1 : $hoy_idx + 1;
?>

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    :root { 
        --primary: #4e73df; --primary-dark: #224abe; --success: #1cc88a; 
        --warning: #f6c23e; --danger: #e74a3b; --dark: #2c3e50; --bg: #f8f9fc;
    }
    
    body { background-color: var(--bg); font-family: 'Poppins', sans-serif; color: var(--dark); }

    .nav-pills .nav-link { border-radius: 50px; font-weight: 700; padding: 12px 25px; color: var(--dark); border: 1px solid #e3e6f0; margin-right: 10px; background: #fff; transition: 0.3s; }
    .nav-pills .nav-link.active { background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important; color: white !important; box-shadow: 0 4px 12px rgba(78,115,223,0.3); }

    .card-pro { border: none; border-radius: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); background: #fff; margin-bottom: 20px; }
    .modal-content { border-radius: 25px; border: none; box-shadow: 0 20px 60px rgba(0,0,0,0.2); }
    .modal-header { background: linear-gradient(135deg, var(--primary), var(--primary-dark)); color: white; border: none; padding: 25px; }
    .input-custom { background: #f1f3f9; border: 2px solid transparent; border-radius: 12px; padding: 12px 15px; font-weight: 600; width: 100%; margin-bottom: 15px; outline: none; transition: 0.3s; }
    .input-custom:focus { background: #fff; border-color: var(--primary); }

    /* Estilos para la Rutina dentro de la Clase */
    .ejercicio-clase-item {
        background: #f8fafc; border-radius: 12px; padding: 10px 15px;
        margin-bottom: 8px; display: flex; align-items: center; justify-content: space-between;
        border: 1px solid #e2e8f0;
    }
    .img-mini-ex { width: 35px; height: 35px; border-radius: 8px; object-fit: cover; margin-right: 10px; }
    
    .day-pill-container { display: flex; gap: 6px; justify-content: space-between; margin-top: 10px; }
    .day-pill { flex: 1; position: relative; }
    .day-input { position: absolute; opacity: 0; width: 100%; height: 100%; cursor: pointer; }
    .day-label { display: block; padding: 10px 2px; background: #fff; border: 2px solid #eaecf4; border-radius: 12px; font-size: 10px; font-weight: 800; text-align: center; }
    .day-input:checked + .day-label { background: var(--primary); color: white; border-color: var(--primary); }

    .group-header { background: #f8f9fa; padding: 12px 20px; border-radius: 12px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; border-left: 5px solid var(--primary); }
</style>

<div class="container-fluid py-4">
    <div class="row mb-4 no-print">
        <div class="col-md-3"><div class="card-pro p-3 text-center border-bottom border-primary"><small class="text-muted font-weight-bold">CLASES HOY</small><h3 class="mb-0 font-weight-bold text-primary" id="kpi_clases">0</h3></div></div>
        <div class="col-md-3"><div class="card-pro p-3 text-center border-bottom border-success"><small class="text-muted font-weight-bold">ASISTENCIAS</small><h3 class="mb-0 font-weight-bold text-success" id="kpi_asist">0</h3></div></div>
        <div class="col-md-3"><div class="card-pro p-3 text-center border-bottom border-warning"><small class="text-muted font-weight-bold">CAPACIDAD</small><h3 class="mb-0 font-weight-bold text-warning">~95%</h3></div></div>
        <div class="col-md-3"><div class="card-pro p-3 text-center border-bottom border-info"><small class="text-muted font-weight-bold">ESTADO</small><h3 class="mb-0 font-weight-bold text-info">PROTEGIDO</h3></div></div>
    </div>

    <div class="mb-4 no-print">
        <ul class="nav nav-pills" id="pills-tab">
            <li class="nav-item"><a class="nav-link active" data-toggle="pill" href="#v-checkin"><i class="fas fa-user-check mr-2"></i>CHECK-IN</a></li>
            <li class="nav-item"><a class="nav-link" data-toggle="pill" href="#v-horarios" onclick="window.listarHorarios()"><i class="fas fa-clock mr-2"></i>HORARIOS</a></li>
            <li class="nav-item"><a class="nav-link" data-toggle="pill" href="#v-catalogo" onclick="window.listarCatalogo()"><i class="fas fa-book mr-2"></i>CATÁLOGO</a></li>
        </ul>
    </div>

    <div class="tab-content">
        <div class="tab-pane fade show active" id="v-checkin">
            <div class="row">
                <div class="col-lg-4">
                    <div class="card-pro p-4">
                        <label class="small font-weight-bold text-muted uppercase">Buscador de Cliente</label>
                        <div class="d-flex align-items-center bg-light rounded-pill px-3 mb-3">
                            <i class="fas fa-search text-muted mr-2"></i>
                            <input type="text" id="src_asistencia" class="form-control bg-transparent border-0 font-weight-bold" placeholder="Nombre o Token...">
                        </div>
                        <div id="res_asistencia" class="list-group mb-2"></div>
                        <div id="perfil_socio" class="mt-4 text-center d-none animate__animated animate__fadeIn">
                            <div id="avatar_txt" style="width:60px; height:60px; border-radius:50%; background:var(--primary); color:white; display:flex; align-items:center; justify-content:center; margin:0 auto 10px; font-size:1.5rem; font-weight:bold; box-shadow: 0 5px 15px rgba(0,0,0,0.1);"></div>
                            <h5 id="p_nombre" class="font-weight-bold mb-1"></h5>
                            <div id="p_status" class="mb-3"></div>
                            <ul class="nav nav-pills nav-justified mb-3 bg-light rounded-pill p-1">
                                <li class="nav-item"><a class="nav-link active py-1" data-toggle="pill" href="#p-hoy" style="font-size:10px;">HOY</a></li>
                                <li class="nav-item"><a class="nav-link py-1" data-toggle="pill" href="#p-mañana" style="font-size:10px;">MAÑANA</a></li>
                            </ul>
                            <div class="tab-content">
                                <div class="tab-pane fade show active" id="p-hoy"><div id="clases_hoy"></div></div>
                                <div class="tab-pane fade" id="p-mañana"><div id="clases_mañana"></div></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-8">
                    <div class="card-pro p-4">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h6 class="font-weight-bold mb-0 text-muted">REGISTRO POR GRUPOS (HOY)</h6>
                            <button class="btn btn-sm btn-light border rounded-circle shadow-sm" onclick="window.listarAsistenciasHoy()"><i class="fas fa-sync-alt text-primary"></i></button>
                        </div>
                        <div id="contenedor_grupos"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="v-horarios">
            <div class="card-pro p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="font-weight-bold mb-0">Programación Semanal</h5>
                    <button class="btn btn-primary rounded-pill px-4 font-weight-bold shadow-sm" onclick="window.abrirModalHorario()">+ PROGRAMAR CLASE</button>
                </div>
                <div class="table-responsive"><table class="table table-hover"><thead><tr><th>DÍA</th><th>HORA</th><th>CLASE</th><th>SALA</th><th>CUPO</th><th class="text-right">ACCIONES</th></tr></thead><tbody id="tbody_horarios"></tbody></table></div>
            </div>
        </div>

        <div class="tab-pane fade" id="v-catalogo">
            <div class="card-pro p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="font-weight-bold mb-0">Catálogo de Actividades</h5>
                    <button class="btn btn-dark rounded-pill px-4 font-weight-bold shadow-sm" onclick="window.abrirModalCatalogo()">+ NUEVA ACTIVIDAD</button>
                </div>
                <div class="row" id="grid_catalogo"></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCatalogo" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Diseño de Clase / WOD</h5>
                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-5 border-right">
                        <label class="small font-weight-bold text-muted">NOMBRE DE LA CLASE</label>
                        <input id="cat_nombre" class="input-custom" placeholder="Ej: Crossfit WOD 1">
                        
                        <label class="small font-weight-bold text-muted">INTENSIDAD</label>
                        <select id="cat_intensidad" class="input-custom">
                            <option value="Media">Media</option>
                            <option value="Alta">Alta</option>
                            <option value="Baja">Baja</option>
                        </select>
                        
                        <label class="small font-weight-bold text-muted">DESCRIPCIÓN</label>
                        <textarea id="cat_desc" class="input-custom" rows="3" placeholder="Objetivo de la clase..."></textarea>
                    </div>

                    <div class="col-md-7">
                        <label class="small font-weight-bold text-primary">ARMAR RUTINA (Planificación)</label>
                        <div class="d-flex mb-3">
                            <input type="text" id="src_ejercicio_cat" class="form-control form-control-sm rounded-pill border-primary" placeholder="Buscar ejercicio en catálogo maestro...">
                        </div>
                        <div id="res_ejercicios_cat" class="list-group shadow-sm mb-3" style="max-height: 150px; overflow-y: auto;"></div>
                        
                        <div id="lista_ejercicios_clase" style="max-height: 250px; overflow-y: auto;">
                            </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary btn-block py-3 font-weight-bold rounded-pill shadow" onclick="window.guardarCatalogo()">GUARDAR ACTIVIDAD COMPLETA</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalListaAsistentes" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="modal-header border-0 bg-light"><h5 class="modal-title text-dark" id="txt_titulo_grupo">Asistentes</h5><button type="button" class="close" data-dismiss="modal"><span>&times;</span></button></div><div class="modal-body p-0"><div id="lista_nombres_div" class="list-group list-group-flush"></div></div></div></div></div>
<div class="modal fade" id="modalHorario" tabindex="-1"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Programar Agenda</h5><button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div><div class="modal-body"><div class="row"><div class="col-md-6 border-right"><label class="small font-weight-bold text-muted">ACTIVIDAD</label><select id="h_idclase" class="input-custom"></select><label class="small font-weight-bold text-muted">SALA</label><input id="h_ubicacion_sala" class="input-custom"><label class="small font-weight-bold text-muted">DÍAS</label><div class="day-pill-container mb-3"><?php $dNames = ["", "LUN", "MAR", "MIE", "JUE", "VIE", "SAB", "DOM"]; for($i=1; $i<=7; $i++): ?><div class="day-pill"><input type="checkbox" id="hp_<?= $i ?>" class="day-input" value="<?= $i ?>"><label for="hp_<?= $i ?>" class="day-label"><?= $dNames[$i] ?></label></div><?php endfor; ?></div></div><div class="col-md-6"><label class="small font-weight-bold text-muted">COACH</label><input id="h_coach" class="input-custom"><label class="small font-weight-bold text-muted">CUPO</label><input id="h_cupo_max" type="number" class="input-custom" value="20"><div class="row"><div class="col-6"><label class="small font-weight-bold text-muted">INICIO</label><input id="h_inicio" type="time" class="input-custom"></div><div class="col-6"><label class="small font-weight-bold text-muted">FIN</label><input id="h_fin" type="time" class="input-custom"></div></div></div></div></div><div class="modal-footer"><button class="btn btn-primary btn-block py-3 font-weight-bold rounded-pill" onclick="window.guardarHorario()">CREAR PROGRAMACIÓN</button></div></div></div></div>

<script>
window.DB = "<?php echo $DB_NAME; ?>";
window.PREFIX = "<?php echo $PREFIX; ?>";
window.rutinaTemporal = []; // Array para manejar el JSON de ejercicios

const clean = (res) => res.data || (Array.isArray(res) ? res : []);

// --- CATÁLOGO DE CLASES (CON RUTINA) ---
window.abrirModalCatalogo = () => {
    window.rutinaTemporal = [];
    $('#lista_ejercicios_clase').empty();
    $('#modalCatalogo').modal('show');
};

// BUSCADOR DE EJERCICIOS (De la tabla 1-Gym_Ejercicios_Catalogo)
document.getElementById('src_ejercicio_cat').addEventListener('input', function() {
    let t = this.value; if(t.length < 2) return;
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(`SELECT * FROM \`1-Gym_Ejercicios_Catalogo\` WHERE Nombre LIKE '%${t}%' LIMIT 5`)}&db=${window.DB}` })
    .then(r => r.json()).then(res => {
        let h = '';
        clean(res).forEach(e => {
            h += `<a href="#" class="list-group-item list-group-item-action small py-2" onclick='window.agregarEjercicioALaClase(${JSON.stringify(e)})'>
                    <i class="fas fa-plus-circle text-success mr-2"></i><b>${e.Nombre}</b> <small class="text-muted">(${e.Musculo})</small>
                  </a>`;
        });
        document.getElementById('res_ejercicios_cat').innerHTML = h;
    });
});

window.agregarEjercicioALaClase = function(e) {
    // Evitar duplicados en la lista visual
    if(window.rutinaTemporal.find(x => x.IDEC == e.IDEC)) return;

    window.rutinaTemporal.push({ IDEC: e.IDEC, Nombre: e.Nombre, Reps: "12", ImagenURL: e.ImagenURL });
    window.renderizarRutinaClase();
    $('#res_ejercicios_cat').empty();
    $('#src_ejercicio_cat').val('');
};

window.renderizarRutinaClase = function() {
    const div = $('#lista_ejercicios_clase').empty();
    window.rutinaTemporal.forEach((e, idx) => {
        div.append(`
            <div class="ejercicio-clase-item shadow-sm animate__animated animate__fadeIn">
                <div class="d-flex align-items-center">
                    <img src="${e.ImagenURL || 'https://via.placeholder.com/50'}" class="img-mini-ex">
                    <div>
                        <small class="d-block font-weight-bold">${e.Nombre}</small>
                        <input type="text" class="border-0 bg-transparent small text-primary font-weight-bold" value="${e.Reps}" onchange="window.updateReps(${idx}, this.value)" style="width:60px" placeholder="Reps/S">
                    </div>
                </div>
                <button class="btn btn-sm text-danger" onclick="window.quitarEx(${idx})"><i class="fas fa-times"></i></button>
            </div>
        `);
    });
};

window.updateReps = (idx, val) => { window.rutinaTemporal[idx].Reps = val; };
window.quitarEx = (idx) => { window.rutinaTemporal.splice(idx, 1); window.renderizarRutinaClase(); };

window.guardarCatalogo = function() {
    const n = $('#cat_nombre').val(); 
    const i = $('#cat_intensidad').val(); 
    const d = $('#cat_desc').val();
    const rutinaJson = JSON.stringify(window.rutinaTemporal);

    if(!n) return;

    const sql = `INSERT INTO \`1-Gym_Clases_Catalogo\` (Nombre_Clase, Descripcion, Intensidad, Requerimientos, Ejercicios_JSON, Estado) 
                 VALUES ('${n}', '${d}', '${i}', '[]', '${rutinaJson}', 'Activo')`;

    fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${window.DB}` })
    .then(() => { 
        Swal.fire('Clase Guardada', 'La planificación se almacenó correctamente', 'success'); 
        $('#modalCatalogo').modal('hide'); 
        window.listarCatalogo(); 
    });
};

window.listarCatalogo = function() {
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT * FROM `1-Gym_Clases_Catalogo` WHERE Estado='Activo'")}&db=${window.DB}` })
    .then(r => r.json()).then(res => {
        const grid = document.getElementById('grid_catalogo'); grid.innerHTML = '';
        clean(res).forEach(c => {
            let cantEjercicios = 0;
            try { cantEjercicios = JSON.parse(c.Ejercicios_JSON || '[]').length; } catch(e){}

            grid.innerHTML += `
                <div class="col-md-4 mb-3">
                    <div class="card card-pro p-3 border-left border-primary">
                        <div class="d-flex justify-content-between">
                            <b>${c.Nombre_Clase}</b>
                            <span class="badge badge-primary px-2">${c.Intensidad}</span>
                        </div>
                        <small class="text-muted d-block mt-2">${c.Descripcion || 'Sin descripción'}</small>
                        <hr class="my-2">
                        <div class="d-flex justify-content-between align-items-center">
                            <small class="font-weight-bold text-primary"><i class="fas fa-dumbbell mr-1"></i> ${cantEjercicios} Ejercicios</small>
                            <button class="btn btn-sm btn-light rounded-pill px-3" onclick='window.verDetalleClase(${JSON.stringify(c)})'>Ver Plan</button>
                        </div>
                    </div>
                </div>`;
        });
    });
};

window.verDetalleClase = function(c) {
    let exList = JSON.parse(c.Ejercicios_JSON || '[]');
    let html = '<div class="text-left">';
    exList.forEach(e => {
        html += `<div class="p-2 border-bottom d-flex justify-content-between align-items-center">
                    <span><b>${e.Nombre}</b></span>
                    <span class="badge badge-dark">${e.Reps}</span>
                 </div>`;
    });
    html += '</div>';

    Swal.fire({
        title: c.Nombre_Clase,
        html: html,
        confirmButtonText: 'Cerrar',
        confirmButtonColor: '#4e73df'
    });
};

// --- EL RESTO DE FUNCIONES (ASISTENCIA, HORARIOS, ETC) SE MANTIENEN IGUAL ---
window.listarAsistenciasHoy = function() {
    const sql = `SELECT h.IDH, h.Ubicacion_Sala, h.Hora_Inicio, h.Cupo_Max, c.Nombre_Clase, COUNT(a.IDA) as Total FROM \`1-Gym_Asistencias\` a JOIN \`1-Gym_Clases_Horarios\` h ON a.IDH = h.IDH JOIN \`1-Gym_Clases_Catalogo\` c ON h.IDClase = c.IDClase WHERE a.Fecha = CURDATE() GROUP BY h.IDH ORDER BY h.Hora_Inicio ASC`;
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${window.DB}` }).then(r => r.json()).then(res => {
        const div = document.getElementById('contenedor_grupos'); div.innerHTML = '';
        clean(res).forEach(h => {
            div.innerHTML += `<div class="group-header shadow-sm"><div><b>${h.Nombre_Clase}</b><br><small class="text-muted">${h.Hora_Inicio.substring(0,5)} hs | ${h.Ubicacion_Sala || ''}</small></div><div class="d-flex align-items-center"><div class="mr-4 text-center"><b class="text-primary h5 mb-0">${h.Total}</b><br><small style="font-size:9px">SOCIOS</small></div><button class="btn btn-sm btn-light border rounded-circle shadow-sm" onclick="window.verAsistentesGrupo(${h.IDH}, '${h.Nombre_Clase}')"><i class="fas fa-users text-primary"></i></button></div></div>`;
        });
    });
};
window.verAsistentesGrupo = function(idh, nombre) {
    const sql = `SELECT c.Nombre, a.Hora_Checkin FROM \`1-Gym_Asistencias\` a JOIN \`1-Clientes\` c ON a.IDC = c.IDC WHERE a.IDH = ${idh} AND a.Fecha = CURDATE()`;
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${window.DB}` }).then(r => r.json()).then(res => {
        const d = document.getElementById('lista_nombres_div'); d.innerHTML = ''; document.getElementById('txt_titulo_grupo').innerText = nombre;
        clean(res).forEach(s => { d.innerHTML += `<div class="list-group-item d-flex justify-content-between align-items-center"><b>${s.Nombre}</b><small class="text-muted">${s.Hora_Checkin.substring(0,5)}</small></div>`; });
        $('#modalListaAsistentes').modal('show');
    });
};
document.getElementById('src_asistencia').addEventListener('input', function() {
    let t = this.value; if(t.length < 2) return;
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(`SELECT IDC, Nombre, Token FROM \`1-Clientes\` WHERE Nombre LIKE '%${t}%' OR Token='${t}' LIMIT 5`)}&db=${window.DB}` })
    .then(r => r.json()).then(res => {
        let h = ''; clean(res).forEach(s => { h += `<a href="#" class="list-group-item list-group-item-action border-0 mb-1 rounded shadow-sm" onclick='window.prepararCheckIn(${JSON.stringify(s)})'><b>${s.Nombre}</b></a>`; });
        document.getElementById('res_asistencia').innerHTML = h;
    });
});
window.prepararCheckIn = function(s) {
    window.socioActivo = s; $('#p_nombre').text(s.Nombre); $('#avatar_txt').text(s.Nombre.charAt(0)); $('#perfil_socio').removeClass('d-none'); $('#res_asistencia').empty();
    const hoy = new Date().toISOString().split('T')[0];
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(`SELECT * FROM \`1-Gym_Membresias_Asignadas\` WHERE IDC=${s.IDC} AND Fecha_Fin >= '${hoy}' LIMIT 1`)}&db=${window.DB}` }).then(r => r.json()).then(res => {
        if(clean(res).length > 0) {
            $('#p_status').html('<span class="badge bg-success text-white px-3 py-1 rounded-pill">MEMBRESÍA ACTIVA</span>');
            window.cargarOpcionesClases(<?php echo $hoy_idx; ?>, 'clases_hoy', true);
            window.cargarOpcionesClases(<?php echo $mañana_idx; ?>, 'clases_mañana', false);
        } else {
            $('#p_status').html('<span class="badge bg-danger text-white px-3 py-1 rounded-pill">SIN PAGO</span>');
            $('#clases_hoy, #clases_mañana').html('<p class="small text-danger">Bloqueado.</p>');
        }
    });
};
window.cargarOpcionesClases = function(dia, divId, permitirReg) {
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(`SELECT h.*, c.Nombre_Clase FROM \`1-Gym_Clases_Horarios\` h JOIN \`1-Gym_Clases_Catalogo\` c ON h.IDClase = c.IDClase WHERE h.Dia_Semana = ${dia}`)}&db=${window.DB}` })
    .then(r => r.json()).then(res => {
        const div = $('#' + divId).empty();
        clean(res).forEach(h => {
            let html = permitirReg ? `<button class="btn btn-outline-primary btn-block mb-2 text-left small shadow-sm" onclick="window.marcarAsistencia(${h.IDH})"><b>${h.Nombre_Clase}</b><br><small>${h.Hora_Inicio.substring(0,5)} | ${h.Ubicacion_Sala || ''}</small></button>` : `<div class="border rounded p-2 mb-2 bg-white small text-left"><b>${h.Nombre_Clase}</b><br><small class="text-muted">${h.Hora_Inicio.substring(0,5)}</small></div>`;
            div.append(html);
        });
    });
};
window.marcarAsistencia = function(idh) {
    const checkSql = `SELECT COUNT(*) as ya_existe FROM \`1-Gym_Asistencias\` WHERE IDC = ${window.socioActivo.IDC} AND IDH = ${idh} AND Fecha = CURDATE()`;
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(checkSql)}&db=${window.DB}` })
    .then(r => r.json()).then(res => {
        const count = clean(res)[0]?.ya_existe || 0;
        if(count > 0) {
            Swal.fire({ title: 'Registro Duplicado', text: 'Ya registró asistencia hoy.', icon: 'warning'});
            return;
        }
        const insertSql = `INSERT INTO \`1-Gym_Asistencias\` (IDC, IDH, Fecha, Hora_Checkin, Metodo_Validacion, Estatus_Asistencia) VALUES (${window.socioActivo.IDC}, ${idh}, CURDATE(), CURTIME(), 'Manual', 'Confirmada')`;
        fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(insertSql)}&db=${window.DB}` })
        .then(() => { 
            Swal.fire({title: '¡Bienvenido!', icon: 'success', timer: 1000, showConfirmButton: false}); 
            window.updateKPIs(); 
            window.listarAsistenciasHoy(); 
            $('#perfil_socio').addClass('d-none'); 
            $('#src_asistencia').val(''); 
        });
    });
};
window.abrirModalHorario = async function() {
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT IDClase, Nombre_Clase FROM `1-Gym_Clases_Catalogo` WHERE Estado='Activo'")}&db=${window.DB}` }).then(r => r.json());
    document.getElementById('h_idclase').innerHTML = clean(res).map(c => `<option value="${c.IDClase}">${c.Nombre_Clase}</option>`).join('');
    $('.day-input').prop('checked', false); $('#modalHorario').modal('show');
};
window.guardarHorario = function() {
    const idC = $('#h_idclase').val(); const coach = $('#h_coach').val(); const ini = $('#h_inicio').val(); const fin = $('#h_fin').val(); const cupo = $('#h_cupo_max').val(); const sala = $('#h_ubicacion_sala').val();
    let dS = []; $('.day-input:checked').each(function() { dS.push($(this).val()); });
    if(dS.length === 0 || !ini) return;
    let v = dS.map(d => `(${idC}, '${coach}', ${d}, '${ini}', '${fin}', ${cupo}, '${sala}')`).join(',');
    const sql = `INSERT INTO \`1-Gym_Clases_Horarios\` (IDClase, Coach_Nombre, Dia_Semana, Hora_Inicio, Hora_Fin, Cupo_Max, Ubicacion_Sala) VALUES ${v}`;
    fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${window.DB}` }).then(() => { Swal.fire('OK', '', 'success'); $('#modalHorario').modal('hide'); window.listarHorarios(); });
};
window.listarHorarios = function() {
    const dN = ["", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"];
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT h.*, c.Nombre_Clase FROM `1-Gym_Clases_Horarios` h JOIN `1-Gym_Clases_Catalogo` c ON h.IDClase = c.IDClase ORDER BY h.Dia_Semana, h.Hora_Inicio")}&db=${window.DB}` })
    .then(r => r.json()).then(res => {
        const tb = document.getElementById('tbody_horarios'); tb.innerHTML = '';
        clean(res).forEach(h => { tb.innerHTML += `<tr><td><b>${dN[h.Dia_Semana]}</b></td><td>${h.Hora_Inicio.substring(0,5)}</td><td><b>${h.Nombre_Clase}</b></td><td>${h.Ubicacion_Sala || ''}</td><td>${h.Cupo_Max}</td><td class="text-right"><button class="btn btn-sm btn-light border" onclick="window.borrarH(${h.IDH})"><i class="fas fa-trash text-danger"></i></button></td></tr>`; });
    });
};
window.borrarH = (id) => fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(`DELETE FROM \`1-Gym_Clases_Horarios\` WHERE IDH = ${id}`)}&db=${window.DB}` }).then(() => window.listarHorarios());
window.updateKPIs = function() {
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(`SELECT COUNT(*) as t FROM \`1-Gym_Asistencias\` WHERE Fecha = CURDATE()`)}&db=${window.DB}` })
    .then(r => r.json()).then(res => { document.getElementById('kpi_asist').innerText = clean(res)[0]?.t || 0; });
};

window.updateKPIs(); window.listarAsistenciasHoy();
</script>