<?php
session_start();
require_once "../librerias/Conexion.php";

// 1. CONFIGURACIÓN DE IDENTIDAD Y PREFIJO
$idUser   = $_GET['idu'] ?? 1; 
$idSocio  = $_GET['idc'] ?? 1;
$prefix   = $idUser; 

$db = new Conexion("MS_Datos");

// 2. PERFIL Y MEMBRESÍA
$sqlSocio = "SELECT c.Nombre, m.Nombre as PlanNombre, a.Fecha_Fin, m.Duracion_Dias
             FROM `{$prefix}-Clientes` c
             LEFT JOIN `{$prefix}-Gym_Membresias_Asignadas` a ON c.IDC = a.IDC
             LEFT JOIN `{$prefix}-Gym_Membresias_Planes` m ON a.IDM = m.IDM
             WHERE c.IDC = '$idSocio' 
             ORDER BY a.IDMA DESC LIMIT 1";
$resSocio = $db->obtenerDatos($sqlSocio);
$datosSocio = $resSocio['data'][0] ?? null;

// Cálculo de días y progreso
$diasRestantes = 0;
$porcentajeMembresia = 0;
if($datosSocio && $datosSocio['Fecha_Fin']){
    $fin = new DateTime($datosSocio['Fecha_Fin']);
    $hoy = new DateTime();
    $diff = $hoy->diff($fin);
    $diasRestantes = $diff->invert ? 0 : $diff->days;
    $totalDias = $datosSocio['Duracion_Dias'] ?? 30;
    $porcentajeMembresia = max(0, min(100, ($diasRestantes * 100) / $totalDias));
}

// 3. CLASES DE HOY
$dia_hoy = date('N'); 
$sqlClases = "SELECT h.IDH, h.Hora_Inicio, h.Coach_Nombre, h.Ubicacion_Sala, c.Nombre_Clase, c.Ejercicios_JSON 
              FROM `{$prefix}-Gym_Clases_Horarios` h 
              JOIN `{$prefix}-Gym_Clases_Catalogo` c ON h.IDClase = c.IDClase 
              WHERE h.Dia_Semana = '$dia_hoy' ORDER BY h.Hora_Inicio ASC";
$clasesHoy = $db->obtenerDatos($sqlClases)['data'] ?? [];
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Elite Fitness | Socio App</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&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>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        :root { --primary: #6366f1; --dark: #0f172a; --bg: #f4f7ff; --accent: #c7d2fe; }
        body { background: var(--bg); font-family: 'Plus Jakarta Sans', sans-serif; padding-bottom: 110px; color: var(--dark); }
        
        .app-header { background: linear-gradient(135deg, var(--dark) 0%, #1e293b 100%); color: white; padding: 50px 20px 90px; border-radius: 0 0 50px 50px; }
        .dash-card { background: white; border-radius: 30px; padding: 25px; margin-top: -65px; box-shadow: 0 20px 40px rgba(0,0,0,0.06); border:none; }
        
        .progress-premium { height: 12px; background: #f1f5f9; border-radius: 20px; overflow: hidden; }
        .progress-bar-fill { height: 100%; background: linear-gradient(90deg, var(--primary), #818cf8); border-radius: 20px; transition: width 1.5s ease; }

        .exercise-card { background: white; border-radius: 25px; padding: 20px; margin-bottom: 20px; box-shadow: 0 10px 15px rgba(0,0,0,0.02); border: 1px solid rgba(0,0,0,0.01); }
        .muscle-badge { background: var(--accent); color: var(--primary); font-size: 0.65rem; font-weight: 800; padding: 4px 10px; border-radius: 8px; text-transform: uppercase; }
        
        .input-premium { background: #f8fafc; border: 2px solid #f1f5f9; border-radius: 15px; padding: 10px; font-weight: 700; text-align: center; width: 100%; }
        .input-premium:focus { border-color: var(--primary); outline: none; background: white; }

        .bottom-nav { position: fixed; bottom: 20px; left: 20px; right: 20px; background: rgba(255,255,255,0.9); backdrop-filter: blur(15px); display: flex; justify-content: space-around; padding: 18px; box-shadow: 0 15px 35px rgba(0,0,0,0.1); border-radius: 28px; z-index: 1000; border: 1px solid rgba(255,255,255,0.5); }
        .nav-item { color: #94a3b8; text-decoration: none; text-align: center; font-size: 0.7rem; font-weight: 700; }
        .nav-item.active { color: var(--primary); transform: translateY(-5px); transition: 0.3s; }
        .nav-item i { display: block; font-size: 1.6rem; margin-bottom: 5px; }

        .set-row { display: grid; grid-template-columns: 30px 1fr 1fr 40px; gap: 8px; align-items: center; padding: 10px 0; border-bottom: 1px dashed #f1f5f9; }
        .set-num { width: 25px; height: 25px; background: var(--bg); color: var(--primary); border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 9px; font-weight: 900; }
    </style>
</head>
<body>

<div class="app-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h4 class="fw-800 mb-0">¡Hola, <?php echo explode(' ', $datosSocio['Nombre'] ?? 'Socio')[0]; ?>!</h4>
            <small class="opacity-75">IDU: <?php echo $prefix; ?> • IDC: <?php echo $idSocio; ?></small>
        </div>
        <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center fw-bold text-white shadow" style="width:45px; height:45px; border: 2px solid white;">
            <?php echo substr($datosSocio['Nombre'] ?? 'S',0,1); ?>
        </div>
    </div>
</div>

<div class="container px-3">
    
    <div class="card dash-card mb-4">
        <div class="d-flex justify-content-between mb-2">
            <span class="text-muted small fw-bold"><?php echo strtoupper($datosSocio['PlanNombre'] ?? 'Plan Activo'); ?></span>
            <span class="text-primary fw-800"><?php echo $diasRestantes; ?> DÍAS</span>
        </div>
        <div class="progress-premium">
            <div class="progress-bar-fill" style="width: <?php echo $porcentajeMembresia; ?>%"></div>
        </div>
    </div>

    <div id="sec-checkin" class="section-app">
        <h6 class="fw-bold text-muted mb-3 uppercase">Clases de Hoy</h6>
        <?php foreach($clasesHoy as $c): ?>
            <div class="exercise-card d-flex justify-content-between align-items-center" onclick="doCheckin(<?php echo $c['IDH']; ?>, '<?php echo $c['Nombre_Clase']; ?>', '<?php echo base64_encode($c['Ejercicios_JSON']); ?>')">
                <div class="d-flex align-items-center">
                    <div class="bg-primary bg-opacity-10 p-3 rounded-4 me-3 text-primary text-center" style="width:55px">
                        <b class="small d-block"><?php echo substr($c['Hora_Inicio'],0,5); ?></b>
                    </div>
                    <div>
                        <b class="d-block text-dark"><?php echo $c['Nombre_Clase']; ?></b>
                        <small class="text-muted"><i class="fas fa-user-ninja me-1"></i><?php echo $c['Coach_Nombre']; ?></small>
                    </div>
                </div>
                <i class="fas fa-plus-circle text-primary fa-lg"></i>
            </div>
        <?php endforeach; ?>
    </div>

    <div id="sec-progreso" class="section-app d-none">
        <h6 class="fw-bold text-muted mb-3 uppercase">Registro de Entrenamiento</h6>
        <div id="diario-entrenamiento"></div>
    </div>

    <div id="sec-medidas" class="section-app d-none">
        <h6 class="fw-bold text-muted mb-3 uppercase">Medidas Corporales</h6>
        <div class="exercise-card">
            <div class="row g-3">
                <div class="col-6"><label class="small fw-bold">Peso (kg)</label><input type="number" step="0.1" id="m_peso" class="input-premium" oninput="calcIMC()"></div>
                <div class="col-6"><label class="small fw-bold">Altura (cm)</label><input type="number" id="m_altura" class="input-premium" oninput="calcIMC()"></div>
                <div class="col-4"><label class="small fw-bold">Cintura</label><input type="number" id="m_cintura" class="input-premium"></div>
                <div class="col-4"><label class="small fw-bold">Pecho</label><input type="number" id="m_pecho" class="input-premium"></div>
                <div class="col-4"><label class="small fw-bold">Cadera</label><input type="number" id="m_cadera" class="input-premium"></div>
                <div class="col-12"><div id="imc_box" class="bg-primary bg-opacity-10 p-3 rounded-4 text-center fw-bold text-primary d-none">IMC: <span id="imc_val">0.0</span></div></div>
                <button class="btn btn-primary w-100 py-3 rounded-4 fw-bold mt-2" onclick="saveMedidas()">GUARDAR CAMBIOS</button>
            </div>
        </div>
        <div class="exercise-card">
            <h6 class="fw-bold mb-3 small">HISTORIAL DE PESO</h6>
            <div style="height: 180px;"><canvas id="chartPeso"></canvas></div>
        </div>
    </div>

    <div id="sec-logros" class="section-app d-none">
        <h6 class="fw-bold text-muted mb-3 uppercase">Evolución de Fuerza</h6>
        <div class="exercise-card">
            <select id="select_ex_stats" class="form-select border-0 bg-light rounded-4 fw-bold mb-4" onchange="loadChart(this.value)"></select>
            <div style="height: 300px; width: 100%;"><canvas id="chartProgreso"></canvas></div>
        </div>
    </div>

</div>

<nav class="bottom-nav">
    <a href="javascript:void(0)" class="nav-item active" onclick="nav('sec-checkin', this)"><i class="fas fa-house"></i>Inicio</a>
    <a href="javascript:void(0)" class="nav-item" onclick="nav('sec-progreso', this); loadDiario();"><i class="fas fa-dumbbell"></i>Diario</a>
    <a href="javascript:void(0)" class="nav-item" onclick="nav('sec-medidas', this); loadPesoChart();"><i class="fas fa-ruler"></i>Cuerpo</a>
    <a href="javascript:void(0)" class="nav-item" onclick="nav('sec-logros', this); loadExList();"><i class="fas fa-chart-line"></i>Fuerza</a>
</nav>

<script>
const socioID = "<?php echo $idSocio; ?>";
const prefijo = "<?php echo $prefix; ?>";

function nav(id, el) {
    document.querySelectorAll('.section-app').forEach(s => s.classList.add('d-none'));
    document.getElementById(id).classList.remove('d-none');
    document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
    el.classList.add('active');
}

// IMC Formula: $IMC = \frac{peso}{altura^2}$
function calcIMC() {
    const p = parseFloat(document.getElementById('m_peso').value);
    const a = parseFloat(document.getElementById('m_altura').value) / 100;
    if(p > 0 && a > 0) {
        const imc = (p / (a * a)).toFixed(1);
        document.getElementById('imc_val').innerText = imc;
        document.getElementById('imc_box').classList.remove('d-none');
    }
}

// CARGAR DIARIO
async function loadDiario() {
    const sql = `SELECT p.IDP, p.Ejercicio_Nombre, p.Repeticiones as Meta, cat.ImagenURL, cat.Musculo 
                 FROM \`${prefijo}-Gym_Progreso_Ejercicios\` p 
                 LEFT JOIN \`${prefijo}-Gym_Ejercicios_Catalogo\` cat ON p.Ejercicio_Nombre = cat.Nombre 
                 WHERE p.IDC = '${socioID}' AND DATE(p.Fecha_Registro) = CURDATE() ORDER BY p.IDP DESC`;
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=MS_Datos`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(r => r.json());
    const cont = document.getElementById('diario-entrenamiento');
    cont.innerHTML = '';
    
    if(!res.data || res.data.length === 0) {
        cont.innerHTML = '<p class="text-center py-5 text-muted small">No hay actividad registrada hoy.</p>';
        return;
    }

    for(let ex of res.data) {
        const resS = await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(`SELECT * FROM \`${prefijo}-Gym_Progreso_Series\` WHERE IDP='${ex.IDP}' ORDER BY IDS ASC`)}&db=MS_Datos`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(r => r.json());
        let sets = (resS.data || []).map((s, i) => `
            <div class="set-row">
                <div class="set-num">${i+1}</div>
                <div class="fw-bold">${s.Peso}kg</div>
                <div class="fw-bold text-muted">${s.Reps} reps</div>
                <i class="fas fa-check-circle text-success ms-auto"></i>
            </div>`).join('');

        cont.innerHTML += `
            <div class="exercise-card">
                <div class="d-flex align-items-center mb-3">
                    <img src="${ex.ImagenURL || 'https://via.placeholder.com/60'}" class="rounded-4 me-3" style="width:60px; height:60px; object-fit:cover;">
                    <div><span class="muscle-badge">${ex.Musculo || 'Full Body'}</span><b class="d-block">${ex.Ejercicio_Nombre}</b></div>
                </div>
                ${sets}
                <div class="set-row border-0 mt-2">
                    <div class="set-num">+</div>
                    <input type="number" id="w_${ex.IDP}" class="input-premium py-1" placeholder="Kg">
                    <input type="number" id="r_${ex.IDP}" class="input-premium py-1" placeholder="Reps">
                    <button class="btn btn-primary btn-sm rounded-3" onclick="addSet(${ex.IDP})"><i class="fas fa-plus"></i></button>
                </div>
            </div>`;
    }
}

async function addSet(idp) {
    const w = document.getElementById('w_'+idp).value;
    const r = document.getElementById('r_'+idp).value;
    if(!w || !r) return;
    await fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: `sql=${encodeURIComponent(`INSERT INTO \`${prefijo}-Gym_Progreso_Series\` (IDP, Peso, Reps) VALUES ('${idp}', '${w}', '${r}')`)}&db=MS_Datos`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} });
    loadDiario();
}

// --- LÓGICA DE EVOLUCIÓN (GRÁFICA) ---

async function loadExList() {
    const sql = `SELECT DISTINCT Ejercicio_Nombre FROM \`${prefijo}-Gym_Progreso_Ejercicios\` WHERE IDC = '${socioID}' ORDER BY Ejercicio_Nombre ASC`;
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=MS_Datos`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(r => r.json());
    const select = document.getElementById('select_ex_stats');
    if(res.data && res.data.length > 0) {
        select.innerHTML = res.data.map(e => `<option value="${e.Ejercicio_Nombre}">${e.Ejercicio_Nombre}</option>`).join('');
        loadChart(res.data[0].Ejercicio_Nombre);
    } else {
        select.innerHTML = '<option>Sin datos disponibles</option>';
    }
}

async function loadChart(exNom) {
    // SQL Corregido: Usamos MAX(IDP) para obtener una referencia única por día
    const sql = `
        SELECT DATE(p.Fecha_Registro) as Fecha, MAX(s.Peso) as MaxPeso, MAX(p.IDP) as IDP_Ref
        FROM \`${prefijo}-Gym_Progreso_Ejercicios\` p
        INNER JOIN \`${prefijo}-Gym_Progreso_Series\` s ON p.IDP = s.IDP
        WHERE p.IDC = '${socioID}' AND p.Ejercicio_Nombre = '${exNom}'
        GROUP BY DATE(p.Fecha_Registro) 
        ORDER BY Fecha ASC LIMIT 10`;

    try {
        const response = await fetch('../librerias/AJAX/Select.php', { 
            method: 'POST', 
            body: `sql=${encodeURIComponent(sql)}&db=MS_Datos`, 
            headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
        });
        const res = await response.json();
        
        const ctx = document.getElementById('chartProgreso').getContext('2d');
        const d = res.data || [];
        
        if(window.fuerzaChart) window.fuerzaChart.destroy();
        
        window.fuerzaChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: d.map(x => x.Fecha.split('-').reverse().slice(0,2).join('/')),
                datasets: [{ 
                    data: d.map(x => x.MaxPeso),
                    ids: d.map(x => x.IDP_Ref),
                    borderColor: '#6366f1',
                    borderDash: [5, 5],
                    backgroundColor: 'rgba(99, 102, 241, 0.1)',
                    fill: true,
                    tension: 0.4,
                    pointRadius: 6,
                    pointHoverRadius: 10,
                    pointBackgroundColor: '#6366f1'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                onClick: (e, activeElements) => {
                    if (activeElements.length > 0) {
                        const index = activeElements[0].index;
                        const idp = window.fuerzaChart.data.datasets[0].ids[index];
                        showSetsDetail(idp, exNom);
                    }
                },
                plugins: { legend: { display: false } },
                scales: { x: { grid: { display: false } }, y: { grid: { color: '#f1f5f9' } } }
            }
        });
    } catch(err) {
        console.error("Error al cargar la gráfica:", err);
    }
}

async function showSetsDetail(idp, nombre) {
    const sql = `SELECT Peso, Reps FROM \`${prefijo}-Gym_Progreso_Series\` WHERE IDP='${idp}' ORDER BY IDS ASC`;
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=MS_Datos`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(r => r.json());
    
    let html = '<div class="text-start mt-2">';
    (res.data || []).forEach((s, i) => {
        html += `<div class="d-flex justify-content-between p-2 border-bottom"><span>Serie ${i+1}</span> <b>${s.Peso}kg x ${s.Reps} reps</b></div>`;
    });
    html += '</div>';

    Swal.fire({ title: nombre, html: html, confirmButtonColor: '#6366f1', customClass: { popup: 'rounded-5' } });
}

// OTRAS GRÁFICAS Y ACCIONES
async function loadPesoChart() {
    const sql = `SELECT Peso, DATE(Fecha) as d FROM \`${prefijo}-Gym_Medidas\` WHERE IDC='${socioID}' ORDER BY Fecha ASC LIMIT 7`;
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=MS_Datos`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).then(r => r.json());
    const ctx = document.getElementById('chartPeso').getContext('2d');
    if(window.pesoChart) window.pesoChart.destroy();
    window.pesoChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: (res.data || []).map(x => x.d.substring(5,10)),
            datasets: [{ data: (res.data || []).map(x => x.Peso), borderColor: '#10b981', tension: 0.4, fill: false }]
        },
        options: { plugins: { legend: { display: false } }, scales: { y: { display: false }, x: { grid: { display: false } } } }
    });
}

async function saveMedidas() {
    const p = document.getElementById('m_peso').value;
    const a = document.getElementById('m_altura').value;
    const c = document.getElementById('m_cintura').value;
    const pe = document.getElementById('m_pecho').value;
    const ca = document.getElementById('m_cadera').value;
    const imc = document.getElementById('imc_val').innerText;
    
    const sql = `INSERT INTO \`${prefijo}-Gym_Medidas\` (IDC, Peso, Altura, Cintura, Pecho, Cadera, IMC) VALUES ('${socioID}', '${p}', '${a}', '${c}', '${pe}', '${ca}', '${imc}')`;
    await fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: `sql=${encodeURIComponent(sql)}&db=MS_Datos`, headers: {'Content-Type': 'application/x-www-form-urlencoded'} });
    Swal.fire('¡Éxito!', 'Medidas actualizadas.', 'success');
}

async function doCheckin(idh, nom, jsonB64) {
    const confirm = await Swal.fire({
        title: '¿Confirmar Asistencia?',
        text: `Vas a entrar a la clase de ${nom}`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#6366f1',
        cancelButtonText: 'Cancelar',
        confirmButtonText: '¡Sí, a entrenar!'
    });

    if (confirm.isConfirmed) {
        Swal.fire({ title: 'Procesando...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

        try {
            // 1. Registro de Asistencia
            const sqlAsist = `INSERT INTO \`${prefijo}-Gym_Asistencias\` (IDC, IDH, Fecha, Hora_Checkin) VALUES ('${socioID}', '${idh}', CURDATE(), CURTIME())`;
            await fetch('../librerias/AJAX/Execute.php', { 
                method: 'POST', 
                body: `sql=${encodeURIComponent(sqlAsist)}&db=MS_Datos`, 
                headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
            });

            // 2. Decodificar y procesar ejercicios
            let ejerciciosRaw = atob(jsonB64);
            let rutina = JSON.parse(ejerciciosRaw || '[]');

            // 3. Insertar ejercicios uno por uno (para evitar errores de multi-query)
            // Usamos un bucle for...of para asegurar que terminen antes de avisar al usuario
            for (let ex of rutina) {
                // Ajustamos nombres de llaves (asegúrate que coincidan con tu JSON)
                let nombreEx = ex.Nombre || ex.nombre || "Ejercicio";
                let repsEx = ex.Reps || ex.reps || "0";
                
                const sqlEx = `INSERT INTO \`${prefijo}-Gym_Progreso_Ejercicios\` (IDC, Ejercicio_Nombre, Repeticiones, Fecha_Registro) VALUES ('${socioID}', '${nombreEx}', '${repsEx}', NOW())`;
                
                await fetch('../librerias/AJAX/Execute.php', { 
                    method: 'POST', 
                    body: `sql=${encodeURIComponent(sqlEx)}&db=MS_Datos`, 
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
                });
            }

            Swal.fire({
                title: '¡Check-in Listo!',
                text: 'Tu rutina ha sido cargada en el Diario.',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            });

            // Cambiar a la pestaña de progreso
            nav('sec-progreso', document.querySelectorAll('.nav-item')[1]);
            loadDiario();

        } catch (error) {
            console.error(error);
            Swal.fire('Error', 'Hubo un problema al cargar la rutina.', 'error');
        }
    }
}
window.onload = loadDiario;
</script>
</body>
</html>