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

// Variables de Configuración
$nombre_bd = "MS_Datos";
// Usa el IDU de la sesión o un default para pruebas
$prefijo = isset($_SESSION['IDU']) ? $_SESSION['IDU'] : '1'; 
$tb_catalogo = $prefijo . "-Gym_Ejercicios_Catalogo"; 
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>

<style>
    /* --- ESTILOS GLOBALES --- */
    body { background-color: #f4f7fa; font-family: 'Poppins', sans-serif; color: #1e293b; }

    /* --- WIDGETS DE GRUPOS MUSCULARES (CINTA SCROLLABLE) --- */
    .muscle-group-container {
        display: flex; gap: 15px; overflow-x: auto; padding: 10px 5px 25px 5px;
        scrollbar-width: thin; scrollbar-color: #cbd5e1 transparent;
    }
    .muscle-group-container::-webkit-scrollbar { height: 8px; }
    .muscle-group-container::-webkit-scrollbar-track { background: transparent; }
    .muscle-group-container::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 20px; border: 2px solid #f4f7fa; }

    .muscle-kpi {
        min-width: 150px; background: white; border-radius: 24px; padding: 20px 15px;
        border: 1px solid #e2e8f0; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.05), 0 4px 6px -2px rgba(0,0,0,0.025);
        text-align: center; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); position: relative; overflow: hidden; cursor: default;
    }
    .muscle-kpi:hover { transform: translateY(-5px); border-color: #818cf8; box-shadow: 0 20px 25px -5px rgba(99, 102, 241, 0.15), 0 10px 10px -5px rgba(99, 102, 241, 0.08); }
    .muscle-kpi::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 5px; background: #818cf8; opacity: 0.7; }
    
    .muscle-kpi i { font-size: 1.8rem; margin-bottom: 12px; color: #6366f1; display: inline-block; background: #eef2ff; padding: 12px; border-radius: 50%; }
    .muscle-kpi .count { font-size: 1.8rem; font-weight: 800; display: block; color: #1e293b; line-height: 1; margin-bottom: 5px; }
    .muscle-kpi .label { font-size: 11px; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 1px; }

    /* --- TABLA ELITE --- */
    .card-elite { border: none; border-radius: 24px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03); background: #fff; overflow: hidden; }
    .table-elite thead th { background-color: #f8fafc; color: #64748b; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; border-bottom: 2px solid #e2e8f0; padding: 18px; font-weight: 700; }
    .table-elite tbody td { padding: 15px 18px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }
    .table-elite tbody tr:hover { background-color: #f8fafc; }
    
    .ex-thumb-container { width: 60px; height: 60px; border-radius: 15px; background: #f1f5f9; border: 2px solid #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.08); overflow: hidden; display: flex; align-items: center; justify-content: center; }
    .ex-thumb { width: 100%; height: 100%; object-fit: cover; }
    .muscle-tag { padding: 5px 12px; border-radius: 30px; font-size: 11px; font-weight: 800; text-transform: uppercase; background: #eef2ff; color: #6366f1; border: 1px solid #c7d2fe; box-shadow: 0 2px 4px rgba(99, 102, 241, 0.1); }
    
    .btn-add { background: #0f172a; color: white; border-radius: 50px; padding: 12px 30px; font-weight: 700; border: none; transition: 0.3s; box-shadow: 0 4px 6px rgba(15, 23, 42, 0.2); display: flex; align-items: center; }
    .btn-add:hover { background: #6366f1; transform: translateY(-2px); box-shadow: 0 8px 12px rgba(99, 102, 241, 0.3); }

    /* --- MODAL Y PREVIEW --- */
    .modal-content-elite { border-radius: 28px; border: none; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); }
    .modal-header-elite { background: #0f172a; color: white; border-radius: 28px 28px 0 0; padding: 25px 30px; border: none; }
    .form-control-elite { border-radius: 12px; border: 2px solid #e2e8f0; padding: 12px 15px; font-weight: 600; transition: 0.3s; background: #f8fafc; }
    .form-control-elite:focus { border-color: #6366f1; background: #fff; box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1); }
    
    /* VISTA PREVIA DE IMAGEN (CRUCIAL) */
    .img-preview-container {
        width: 100%; height: 220px; border-radius: 15px;
        background: #f8fafc; display: flex; align-items: center;
        justify-content: center; overflow: hidden; border: 2px dashed #cbd5e1;
        transition: 0.3s;
    }
    #preview_img { width: 100%; height: 100%; object-fit: contain; }
    .preview-active { border-style: solid; border-color: #6366f1; background: #fff; }
</style>

<div class="container-fluid p-4">
    
    <div class="row mb-4 align-items-center justify-content-between animate__animated animate__fadeInDown">
        <div class="col-md-7 mb-3 mb-md-0">
            <h2 class="font-weight-bold text-dark mb-1" style="letter-spacing: -1px;"><i class="fas fa-dumbbell mr-2 text-primary"></i>Catálogo Maestro</h2>
            <p class="text-muted mb-0 font-weight-medium" style="font-size: 1.1rem;">Biblioteca central de ejercicios y multimedia.</p>
        </div>
        <div class="col-md-5 text-md-right d-flex justify-content-md-end">
             <button class="btn-add" onclick="abrirModalEx()">
                <i class="fas fa-plus-circle mr-2 fa-lg"></i> Nuevo Ejercicio
            </button>
        </div>
    </div>

    <div class="muscle-group-container mb-4 animate__animated animate__fadeIn" id="cont_muscle_kpis" style="animation-delay: 0.2s">
        <div class="text-muted font-italic p-3">Cargando métricas...</div>
    </div>

    <div class="card-elite animate__animated animate__fadeInUp" style="animation-delay: 0.4s">
        <div class="card-header bg-white py-4 border-0 d-flex align-items-center">
            <div class="input-group shadow-sm" style="max-width: 450px; border-radius: 50px; background: #f1f5f9; padding: 5px 10px; border: 1px solid #e2e8f0;">
                <span class="input-group-text bg-transparent border-0 pr-2"><i class="fas fa-search text-muted"></i></span>
                <input type="text" id="buscador_ex" class="form-control bg-transparent border-0 font-weight-bold text-dark" placeholder="Buscar por nombre, músculo..." style="box-shadow: none;">
            </div>
            <div class="ml-auto text-muted small font-weight-bold" id="total_records_label"></div>
        </div>
        <div class="table-responsive">
            <table class="table table-elite align-middle mb-0">
                <thead>
                    <tr>
                        <th class="pl-5">Referencia Visual</th>
                        <th>Nombre del Ejercicio</th>
                        <th>Grupo Muscular</th>
                        <th class="text-center">Estado</th>
                        <th class="text-right pr-5">Acciones</th>
                    </tr>
                </thead>
                <tbody id="tbody_ejercicios"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEx" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content modal-content-elite">
            <div class="modal-header modal-header-elite">
                <h5 class="modal-title font-weight-bold" id="modalTituloEx"><i class="fas fa-dumbbell mr-2"></i>Configurar Ejercicio</h5>
                <button type="button" class="close text-white opacity-75 hover-opacity-100" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <form id="formEx" class="p-4p-5">
                <input type="hidden" id="IDEC">
                <div class="row">
                    <div class="col-md-8">
                         <div class="mb-4">
                            <label class="small font-weight-bold text-muted mb-2">NOMBRE DEL MOVIMIENTO <span class="text-danger">*</span></label>
                            <input type="text" class="form-control form-control-elite font-weight-bold text-dark font-size-lg" id="NombreEx" required placeholder="Ej: Press de Banca Inclinado">
                        </div>
                    </div>
                    <div class="col-md-4">
                         <div class="mb-4">
                            <label class="small font-weight-bold text-muted mb-2">ESTADO</label>
                            <select class="form-control form-control-elite" id="EstadoEx">
                                <option value="Activo">Activo (Visible)</option>
                                <option value="Inactivo">Inactivo (Oculto)</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="small font-weight-bold text-muted mb-2">GRUPO MUSCULAR PRINCIPAL <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <span class="input-group-text bg-white border-right-0" style="border-radius: 12px 0 0 12px; border: 2px solid #e2e8f0;"><i class="fas fa-child text-primary"></i></span>
                         <select class="form-control form-control-elite border-left-0" id="MusculoEx" style="border-radius: 0 12px 12px 0;">
                            <option value="">Seleccione...</option>
                            <optgroup label="Tren Superior">
                                <option value="Pecho">Pecho (Pectorales)</option>
                                <option value="Espalda">Espalda (Dorsales/Trapecio)</option>
                                <option value="Hombro">Hombro (Deltoides)</option>
                                <option value="Bíceps">Bíceps (Brazos)</option>
                                <option value="Tríceps">Tríceps (Brazos)</option>
                            </optgroup>
                            <optgroup label="Tren Inferior">
                                <option value="Cuádriceps">Cuádriceps (Pierna Frontal)</option>
                                <option value="Isquios">Isquios (Femoral/Pierna Trasera)</option>
                                <option value="Glúteo">Glúteo</option>
                                <option value="Pantorrilla">Pantorrilla (Gemelos)</option>
                            </optgroup>
                            <optgroup label="Otros">
                                <option value="Abdomen">Abdomen / Core</option>
                                <option value="Cardio">Cardio / Funcional</option>
                                <option value="Full Body">Full Body / Compuesto</option>
                            </optgroup>
                        </select>
                    </div>
                </div>
               
               <div class="mb-4">
                    <label class="small font-weight-bold text-muted mb-2">URL DEL GIF / IMAGEN DEMOSTRATIVA</label>
                    <div class="input-group mb-3">
                         <span class="input-group-text bg-white border-right-0" style="border-radius: 12px 0 0 12px; border: 2px solid #e2e8f0;"><i class="fas fa-link text-muted"></i></span>
                        <input type="text" class="form-control form-control-elite border-left-0" id="ImagenURLEx" placeholder="Pegue aquí el enlace https://..." oninput="actualizarPreview(this.value)" style="border-radius: 0 12px 12px 0;">
                    </div>
                    
                    <div class="img-preview-container" id="preview_container">
                        <img id="preview_img" src="" style="display:none;" onerror="this.style.display='none'; document.getElementById('preview_placeholder').innerHTML='<i class=\'fas fa-exclamation-circle text-danger fa-3x mb-2\'></i><br><small class=\'text-danger font-weight-bold\'>Error: Imagen no válida</small>'; document.getElementById('preview_placeholder').style.display='block';">
                        <div id="preview_placeholder" class="text-center text-muted opacity-75">
                            <i class="fas fa-photo-video fa-4x mb-3 text-primary opacity-50 animate__animated animate__pulse animate__infinite"></i>
                            <br><small class="font-weight-bold">La vista previa aparecerá aquí</small>
                        </div>
                    </div>
                     <small class="text-muted mt-2 d-block"><i class="fas fa-info-circle mr-1"></i> Se recomiendan GIFs de GIPHY o imágenes directas (JPG/PNG).</small>
                </div>

                <div class="text-right pt-3">
                    <button type="button" class="btn btn-light text-muted font-weight-bold rounded-pill px-4 mr-2" data-dismiss="modal">Cancelar</button>
                    <button type="button" class="btn btn-primary px-5 py-3 font-weight-bold rounded-pill shadow-lg hover-scale" onclick="guardarEjercicio()">
                        <i class="fas fa-save mr-2"></i> GUARDAR EJERCICIO
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // --- CONFIGURACIÓN ---
    const DB = "<?php echo $nombre_bd; ?>";
    const TB_EX = "<?php echo $tb_catalogo; ?>";
    
    // Mapa de iconos para los widgets
    const muscleIcons = {
        "Pecho": "fa-shield-alt", "Espalda": "fa-hand-rock", "Cuádriceps": "fa-bolt",
        "Isquios": "fa-drumstick-bite", "Glúteo": "fa-apple-alt", "Hombro": "fa-dumbbell",
        "Bíceps": "fa-hand-paper", "Tríceps": "fa-hand-lizard", "Abdomen": "fa-th-large", 
        "Cardio": "fa-heartbeat", "Pantorrilla": "fa-arrow-down", "Full Body": "fa-child"
    };

    const safe = (str) => str ? String(str).replace(/'/g, "\\'") : '';
    const clean = (res) => { if (!res) return []; let d = res.data || res; return Array.isArray(d) ? d : []; };

    // --- INICIALIZACIÓN ---
    document.addEventListener('DOMContentLoaded', () => {
        listarEjercicios();
        // Buscador en tiempo real
        document.getElementById('buscador_ex').addEventListener('keyup', (e) => {
            const term = e.target.value.toLowerCase();
            let visibleCount = 0;
            document.querySelectorAll('#tbody_ejercicios tr').forEach(row => {
                const match = row.innerText.toLowerCase().includes(term);
                row.style.display = match ? '' : 'none';
                if(match) visibleCount++;
            });
             document.getElementById('total_records_label').innerText = term ? `${visibleCount} resultados` : `Total: ${document.querySelectorAll('#tbody_ejercicios tr').length}`;
        });
    });

    // --- FUNCIÓN PRINCIPAL: LISTAR ---
    function listarEjercicios() {
        const sql = `SELECT * FROM \`${TB_EX}\` ORDER BY Nombre ASC`;
        fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=${DB}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
        .then(r => r.json()).then(res => {
            const tbody = document.getElementById('tbody_ejercicios');
            const contKpi = document.getElementById('cont_muscle_kpis');
            tbody.innerHTML = ''; contKpi.innerHTML = '';
            
            const data = clean(res);
            let counts = {};
            document.getElementById('total_records_label').innerText = `Total: ${data.length}`;

            if(data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="text-center py-5 text-muted font-italic"><h5><i class="fas fa-inbox fa-3x mb-3 opacity-25"></i><br>El catálogo está vacío.</h5><p>Usa el botón "Nuevo Ejercicio" para comenzar.</p></td></tr>';
                contKpi.innerHTML = '<div class="text-muted p-3 font-italic">Sin datos para métricas.</div>';
                return;
            }


            data.forEach((e, index) => {
                // Contabilizar para KPIs
                const m = e.Musculo || "Otros";
                counts[m] = (counts[m] || 0) + 1;

                // Thumbnail
                const img = e.ImagenURL ? `<img src="${e.ImagenURL}" class="ex-thumb" onerror="this.src='https://via.placeholder.com/60x60?text=Err'">` : `<i class="fas fa-dumbbell text-muted fa-lg opacity-50"></i>`;
                
                // Badge de estado
                const statusBadge = e.Estado === 'Activo' 
                    ? '<span class="badge badge-pill badge-success px-3 py-2 font-weight-bold" style="background:#dcfce7; color:#166534;">ACTIVO</span>' 
                    : '<span class="badge badge-pill badge-danger px-3 py-2 font-weight-bold" style="background:#fee2e2; color:#991b1b;">INACTIVO</span>';

                tbody.innerHTML += `
                    <tr class="animate__animated animate__fadeIn" style="animation-delay: ${index * 0.03}s">
                        <td class="pl-5"><div class="ex-thumb-container">${img}</div></td>
                        <td><div class="font-weight-bold text-dark font-size-lg">${e.Nombre}</div></td>
                        <td><span class="muscle-tag"><i class="fas ${muscleIcons[e.Musculo] || 'fa-circle'} mr-1"></i>${e.Musculo || 'General'}</span></td>
                        <td class="text-center">${statusBadge}</td>
                        <td class="text-right pr-5">
                            <button class="btn btn-sm btn-light text-primary border shadow-sm rounded-circle mr-2" data-toggle="tooltip" title="Editar" onclick='editarEjercicio(${JSON.stringify(e)})' style="width:38px;height:38px;"><i class="fas fa-pen"></i></button>
                            <button class="btn btn-sm btn-light text-danger border shadow-sm rounded-circle" data-toggle="tooltip" title="Eliminar" onclick="eliminarEjercicio(${e.IDEC})" style="width:38px;height:38px;"><i class="fas fa-trash-alt"></i></button>
                        </td>
                    </tr>`;
            });
            $('[data-toggle="tooltip"]').tooltip(); // Activar tooltips de Bootstrap

            // Renderizar WIDGETS DINÁMICOS
            // Primero un total general
            contKpi.innerHTML += `
                <div class="muscle-kpi" style="border-color: #6366f1;">
                    <i class="fas fa-list-ul" style="background:#eef2ff; color:#6366f1;"></i>
                    <span class="count">${data.length}</span>
                    <span class="label">TOTAL GLOBAL</span>
                </div>`;
                
            // Luego los grupos específicos ordenados por cantidad descendente
            Object.entries(counts)
                .sort(([,a],[,b]) => b-a)
                .forEach(([musculo, count]) => {
                contKpi.innerHTML += `
                    <div class="muscle-kpi animate__animated animate__fadeInRight">
                        <i class="fas ${muscleIcons[musculo] || 'fa-dumbbell'}"></i>
                        <span class="count">${count}</span>
                        <span class="label">${musculo}</span>
                    </div>`;
            });
        });
    }

    // --- LÓGICA DE PREVIEW DE IMAGEN (SOLICITADO) ---
    function actualizarPreview(url) {
        const img = document.getElementById('preview_img');
        const placeholder = document.getElementById('preview_placeholder');
        const container = document.getElementById('preview_container');

        // Resetear estado de error por si acaso
        placeholder.innerHTML = '<i class="fas fa-photo-video fa-4x mb-3 text-primary opacity-50 animate__animated animate__pulse animate__infinite"></i><br><small class="font-weight-bold">La vista previa aparecerá aquí</small>';

        if(url && url.length > 8 && (url.startsWith('http://') || url.startsWith('https://'))) {
            img.src = url;
            img.style.display = 'block';
            placeholder.style.display = 'none';
            container.classList.add('preview-active');
        } else {
            img.style.display = 'none';
            placeholder.style.display = 'block';
            container.classList.remove('preview-active');
        }
    }

    // --- FUNCIONES DEL MODAL ---
    function abrirModalEx() { 
        document.getElementById('formEx').reset(); 
        document.getElementById('IDEC').value = ''; 
        document.getElementById('modalTituloEx').innerHTML = '<i class="fas fa-plus-circle mr-2"></i>Nuevo Ejercicio';
        actualizarPreview(''); // Limpiar preview
        $('#modalEx').modal('show'); 
    }

    function editarEjercicio(e) { 
        document.getElementById('IDEC').value = e.IDEC;
        document.getElementById('NombreEx').value = e.Nombre;
        document.getElementById('MusculoEx').value = e.Musculo;
        document.getElementById('ImagenURLEx').value = e.ImagenURL;
        document.getElementById('EstadoEx').value = e.Estado;
        document.getElementById('modalTituloEx').innerHTML = '<i class="fas fa-edit mr-2"></i>Editar: ' + e.Nombre;
        actualizarPreview(e.ImagenURL); // Cargar preview existente
        $('#modalEx').modal('show'); 
    }

    // --- GUARDAR Y ELIMINAR ---
    function guardarEjercicio() {
        const id = document.getElementById('IDEC').value;
        const n = document.getElementById('NombreEx').value.trim();
        const m = document.getElementById('MusculoEx').value;
        const i = document.getElementById('ImagenURLEx').value.trim();
        const e = document.getElementById('EstadoEx').value;
        
        if(!n || !m) {
            Swal.fire({title: 'Faltan datos', text: 'El Nombre y el Grupo Muscular son obligatorios.', icon: 'warning', confirmButtonColor: '#6366f1'});
            return;
        }

        const sql = id 
            ? `UPDATE \`${TB_EX}\` SET Nombre='${safe(n)}', Musculo='${safe(m)}', ImagenURL='${safe(i)}', Estado='${e}' WHERE IDEC=${id}`
            : `INSERT INTO \`${TB_EX}\` (Nombre, Musculo, ImagenURL, Estado) VALUES ('${safe(n)}', '${safe(m)}', '${safe(i)}', '${e}')`;

        fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=${DB}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
        .then(r => r.json())
        .then(res => { 
            if(res.status === 'success' || !res.error) {
                Swal.fire({icon: 'success', title: 'Guardado', toast: true, position: 'top-end', showConfirmButton: false, timer: 1500}); 
                $('#modalEx').modal('hide'); 
                listarEjercicios(); 
            } else { Swal.fire('Error', res.error || 'Error desconocido en BD', 'error'); }
        })
        .catch(err => Swal.fire('Error de Conexión', 'Revisa la consola.', 'error'));
    }

    function eliminarEjercicio(id) {
        Swal.fire({ title: '¿Estás seguro?', text: "El ejercicio se eliminará permanentemente del catálogo.", icon: 'warning', showCancelButton: true, confirmButtonColor: '#ef4444', confirmButtonText: 'Sí, eliminar', cancelButtonText: 'Cancelar' }).then(r => {
            if(r.isConfirmed) fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: `sql=${encodeURIComponent(`DELETE FROM \`${TB_EX}\` WHERE IDEC=${id}`)}&db=${DB}`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(() => {
                 Swal.fire({icon: 'success', title: 'Eliminado', toast: true, position: 'top-end', showConfirmButton: false, timer: 1500});
                 listarEjercicios();
            });
        });
    }
</script>