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

$DB_NAME = "MS_Datos"; 
$PREFIX = "1"; // Tu prefijo real
?>

<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: #6366f1; --success: #10b981; --danger: #ef4444; 
        --dark: #0f172a; --bg: #f8fafc; --white: #ffffff;
    }
    
    body { background-color: var(--bg); font-family: 'Poppins', sans-serif; }

    /* --- CARDS DEL CATÁLOGO --- */
    .cat-card {
        background: var(--white); border-radius: 20px; border: 1px solid #e2e8f0;
        padding: 12px; transition: 0.3s; position: relative; height: 100%;
    }
    .cat-card:hover { transform: translateY(-5px); box-shadow: 0 12px 25px rgba(0,0,0,0.08); }
    .cat-img { width: 100%; height: 110px; object-fit: cover; border-radius: 15px; background: #f1f5f9; margin-bottom: 10px; }
    
    .btn-delete-cat {
        position: absolute; top: 10px; right: 10px; width: 32px; height: 32px; border-radius: 10px;
        background: rgba(239, 68, 68, 0.1); color: var(--danger); border: none; display: flex; align-items: center; justify-content: center; z-index: 5;
    }

    /* --- TIRA DE EJERCICIOS (REGISTRO POR SERIES) --- */
    .exercise-strip-item {
        background: #fff; border-radius: 25px; border: 1px solid #e2e8f0;
        margin-bottom: 20px; padding: 20px; border-left: 8px solid var(--primary);
        box-shadow: 0 4px 6px rgba(0,0,0,0.02);
    }
    .ex-header-tira { display: flex; align-items: center; margin-bottom: 15px; }
    .ex-media-mini { width: 55px; height: 55px; border-radius: 12px; background: #f1f5f9; margin-right: 15px; overflow: hidden; flex-shrink: 0; }
    .ex-media-mini img { width: 100%; height: 100%; object-fit: cover; }

    /* Listado de series hechas */
    .sets-history { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 15px; }
    .set-badge { 
        background: #f1f5f9; border: 1px solid #e2e8f0; border-radius: 12px; 
        padding: 5px 12px; font-size: 11px; font-weight: 700; color: var(--dark);
    }
    .set-badge b { color: var(--primary); }

    .capture-row { 
        display: flex; gap: 10px; background: #f8fafc; padding: 10px; 
        border-radius: 15px; align-items: center; 
    }
    .input-field { width: 85px; border-radius: 10px; border: 2px solid #e2e8f0; padding: 8px; font-weight: 800; text-align: center; font-size: 1rem; }
    .input-field:focus { border-color: var(--primary); background: white; outline: none; }

    .btn-save-log { width: 50px; height: 50px; border-radius: 12px; border: none; background: var(--dark); color: white; transition: 0.3s; flex-shrink: 0; }
    .btn-save-log:hover { background: var(--success); transform: scale(1.05); }

    .nav-elite .nav-link { border-radius: 50px; font-weight: 700; color: #64748b; border: 1px solid #e2e8f0; margin-right: 10px; padding: 10px 25px; }
    .nav-elite .nav-link.active { background: var(--primary) !important; color: white !important; }
</style>

<div class="container-fluid py-4">
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="font-weight-bold mb-0">GymAvances <span class="text-primary">Pro</span></h4>
        <ul class="nav nav-pills nav-elite">
            <li class="nav-item"><a class="nav-link active" data-toggle="pill" href="#v-track">TRACKER</a></li>
            <li class="nav-item"><a class="nav-link" data-toggle="pill" href="#v-cat" onclick="window.listarCat()">CATÁLOGO</a></li>
        </ul>
    </div>

    <div class="tab-content">
        <div class="tab-pane fade show active" id="v-track">
            <div class="row">
                <div class="col-lg-3">
                    <div class="card border-0 shadow-sm p-4" style="border-radius:24px;">
                        <label class="small font-weight-bold text-muted mb-2">IDENTIFICAR SOCIO</label>
                        <input type="text" id="src_socio" class="form-control rounded-pill border-0 bg-light font-weight-bold mb-3" placeholder="Nombre o Token...">
                        <div id="res_socio" class="list-group mb-2 shadow-sm"></div>

                        <div id="perfil_socio" class="mt-3 text-center d-none">
                            <div id="avatar" style="width:70px; height:70px; border-radius:20px; background:var(--primary); color:white; display:flex; align-items:center; justify-content:center; margin:0 auto 12px; font-size:1.8rem; font-weight:bold; box-shadow: 0 10px 15px rgba(99,102,241,0.2);"></div>
                            <h6 id="txt_nombre" class="font-weight-bold mb-1 text-dark"></h6>
                            <small class="text-muted d-block mb-4" id="txt_token"></small>
                            <button class="btn btn-primary btn-block rounded-pill font-weight-bold shadow-sm py-3" onclick="window.abrirModalAsignar()">
                                <i class="fas fa-plus-circle mr-2"></i> ASIGNAR EJERCICIO
                            </button>
                        </div>
                    </div>
                </div>
                <div class="col-lg-9">
                    <div id="cont_tira" class="animate__animated animate__fadeIn">
                        <div class="text-center py-5">
                            <i class="fas fa-search fa-4x text-light mb-3"></i>
                            <h5 class="text-muted">Busca un socio para registrar su entrenamiento</h5>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="v-cat">
            <div class="card border-0 shadow-sm p-4" style="border-radius:24px;">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="font-weight-bold mb-0">Gestión de Ejercicios Maestros</h5>
                    <button class="btn btn-dark rounded-pill px-4 font-weight-bold shadow-sm" onclick="window.modalNuevoEjercicio()">+ NUEVO EJERCICIO</button>
                </div>
                <div class="row" id="grid_cat"></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalAsignar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius:25px; border:none;">
            <div class="modal-body p-5 text-center">
                <i class="fas fa-dumbbell fa-3x text-primary mb-3"></i>
                <h5 class="font-weight-bold mb-4">¿Qué ejercicio agregamos hoy?</h5>
                <select id="sel_cat" class="form-control mb-4 font-weight-bold shadow-sm" style="height:60px; border-radius:15px; border:2px solid #f1f5f9;"></select>
                <button class="btn btn-primary btn-block py-3 rounded-pill font-weight-bold shadow-lg" onclick="window.vincularSocio()">EMPEZAR EJERCICIO</button>
            </div>
        </div>
    </div>
</div>

<script>
window.DB = "<?php echo $DB_NAME; ?>";
window.PREFIX = "<?php echo $PREFIX; ?>";
window.socioID = null;

const clean = (res) => { if (!res) return []; let d = res.data || res; return Array.isArray(d) ? d : []; };

/** 1. GESTIÓN DE CATÁLOGO **/
window.listarCat = function() {
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT * FROM `" + window.PREFIX + "-Gym_Ejercicios_Catalogo` WHERE Estado='Activo' ORDER BY Nombre ASC")} &db=${window.DB}` })
    .then(r => r.json()).then(res => {
        const grid = document.getElementById('grid_cat'); grid.innerHTML = '';
        clean(res).forEach(e => {
            const media = e.ImagenURL ? `<img src="${e.ImagenURL}" class="cat-img">` : `<div class="cat-img d-flex align-items-center justify-content-center text-muted"><i class="fas fa-image fa-2x"></i></div>`;
            grid.innerHTML += `
                <div class="col-md-3 mb-4">
                    <div class="cat-card shadow-xs animate__animated animate__fadeIn">
                        <button class="btn-delete-cat" onclick="window.borrarEjercicioCat(${e.IDEC}, '${e.Nombre}')"><i class="fas fa-trash-alt"></i></button>
                        ${media}
                        <b class="small d-block text-uppercase font-weight-bold">${e.Nombre}</b>
                        <small class="text-primary font-weight-bold">${e.Musculo || 'General'}</small>
                    </div>
                </div>`;
        });
    });
};

window.borrarEjercicioCat = (id, nombre) => {
    Swal.fire({ title: '¿Eliminar?', text: `Se borrará "${nombre}" del catálogo.`, icon: 'warning', showCancelButton: true, confirmButtonColor: '#ef4444' }).then(r => {
        if (r.isConfirmed) fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(`DELETE FROM \`${window.PREFIX}-Gym_Ejercicios_Catalogo\` WHERE IDEC = ${id}`)}&db=${window.DB}` }).then(() => window.listarCat());
    });
};

window.modalNuevoEjercicio = () => {
    Swal.fire({
        title: 'Nuevo Ejercicio Maestro',
        html: `<input id="n_e" class="swal2-input" placeholder="Nombre (Ej: Press de Banca)"><input id="n_m" class="swal2-input" placeholder="Músculo (Ej: Pecho)"><input id="n_i" class="swal2-input" placeholder="URL Imagen/GIF">`,
        preConfirm: () => ({ n: $('#n_e').val(), m: $('#n_m').val(), i: $('#n_i').val() })
    }).then(r => {
        if(r.isConfirmed && r.value.n) {
            const sql = `INSERT INTO \`${window.PREFIX}-Gym_Ejercicios_Catalogo\` (Nombre, Musculo, ImagenURL) VALUES ('${r.value.n}', '${r.value.m}', '${r.value.i}')`;
            fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${window.DB}` }).then(() => window.listarCat());
        }
    });
};

/** 2. WORKOUT TRACKER (AVANCES CON SERIES) **/
document.getElementById('src_socio').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 \`${window.PREFIX}-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 font-weight-bold" onclick='window.seleccionarSocio(${JSON.stringify(s)})'>${s.Nombre}</a>`; });
        document.getElementById('res_socio').innerHTML = h;
    });
});

window.seleccionarSocio = function(s) {
    window.socioID = s.IDC; $('#txt_nombre').text(s.Nombre); $('#txt_token').text(s.Token); $('#avatar').text(s.Nombre.charAt(0));
    $('#perfil_socio').removeClass('d-none'); $('#res_socio').empty(); $('#src_socio').val('');
    window.cargarTira();
};

// FUNCIÓN CLAVE: CARGA EJERCICIOS Y SUS SERIES DEL DÍA
window.cargarTira = function() {
    const sql = `SELECT p.*, cat.ImagenURL 
                 FROM \`${window.PREFIX}-Gym_Progreso_Ejercicios\` p 
                 LEFT JOIN \`${window.PREFIX}-Gym_Ejercicios_Catalogo\` cat ON p.Ejercicio_Nombre = cat.Nombre 
                 WHERE p.IDC = ${window.socioID} AND DATE(p.Fecha_Registro) = CURDATE() 
                 ORDER BY p.IDP DESC`;

    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(async res => {
        const cont = document.getElementById('cont_tira'); cont.innerHTML = '';
        const d = clean(res);
        if(d.length === 0) { cont.innerHTML = '<div class="text-center py-5 card border-0" style="border-radius:20px;"><h5>El socio no ha iniciado ejercicios hoy.</h5><p>Usa el botón "+ ASIGNAR" para empezar su rutina.</p></div>'; return; }
        
        for(let ex of d) {
            // Buscamos las series de este ejercicio hoy
            const resS = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(`SELECT * FROM \`${window.PREFIX}-Gym_Progreso_Series\` WHERE IDP=${ex.IDP} ORDER BY IDS ASC`)}&db=${window.DB}` }).then(r => r.json());
            const series = clean(resS);

            let setsHTML = '';
            series.forEach((s, idx) => {
                setsHTML += `<div class="set-badge shadow-xs">S${idx+1}: <b>${s.Peso}kg</b> x <b>${s.Reps}</b></div>`;
            });

            const media = ex.ImagenURL ? `<img src="${ex.ImagenURL}">` : `<i class="fas fa-dumbbell fa-lg text-muted mt-3"></i>`;
            
            cont.innerHTML += `
                <div class="exercise-strip-item animate__animated animate__fadeInRight">
                    <div class="ex-header-tira">
                        <div class="ex-media-mini text-center">${media}</div>
                        <div>
                            <b class="text-dark d-block h5 mb-0">${ex.Ejercicio_Nombre}</b>
                            <span class="badge badge-light text-primary border">${ex.Musculo_Objetivo}</span>
                        </div>
                    </div>
                    
                    <div class="sets-history" id="sets_hist_${ex.IDP}">
                        ${setsHTML || '<small class="text-muted font-italic">Sin series registradas hoy...</small>'}
                    </div>

                    <div class="capture-row">
                        <div class="small fw-bold text-muted mr-auto"><i class="fas fa-plus mr-1"></i> NUEVA SERIE</div>
                        <input type="number" id="w_${ex.IDP}" class="input-field" placeholder="Kilos">
                        <input type="number" id="r_${ex.IDP}" class="input-field" placeholder="Reps">
                        <button class="btn-save-log" onclick="window.registrarSerie(${ex.IDP})">
                            <i class="fas fa-check"></i>
                        </button>
                    </div>
                </div>`;
        }
    });
};

// REGISTRAR SERIE INDIVIDUAL (HACIA CREAR_9)
window.registrarSerie = function(idp) {
    const w = document.getElementById('w_'+idp).value;
    const r = document.getElementById('r_'+idp).value;
    if(!w || !r) return;

    const sql = `INSERT INTO \`${window.PREFIX}-Gym_Progreso_Series\` (IDP, Peso, Reps) VALUES (${idp}, ${w}, ${r})`;
    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({title: 'Serie Guardada', icon: 'success', toast: true, position: 'top-end', timer: 800, showConfirmButton: false});
        window.cargarTira(); // Recargar para ver la nueva serie en la lista
    });
};

window.abrirModalAsignar = async function() {
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT * FROM `" + window.PREFIX + "-Gym_Ejercicios_Catalogo` WHERE Estado='Activo'")} &db=${window.DB}` }).then(r => r.json());
    document.getElementById('sel_cat').innerHTML = clean(res).map(e => `<option value='${JSON.stringify(e)}'>${e.Nombre} (${e.Musculo})</option>`).join('');
    $('#modalAsignar').modal('show');
};

window.vincularSocio = function() {
    const data = JSON.parse($('#sel_cat').val());
    // Se crea el cabezal del ejercicio para hoy en Gym_Progreso_Ejercicios
    const sql = `INSERT INTO \`${window.PREFIX}-Gym_Progreso_Ejercicios\` (IDC, Ejercicio_Nombre, Musculo_Objetivo, Fecha_Registro) VALUES (${window.socioID}, '${data.Nombre}', '${data.Musculo}', NOW())`;
    fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${window.DB}` }).then(() => {
        $('#modalAsignar').modal('hide'); window.cargarTira();
    });
};
</script>