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

$DB_NAME = "MS_Datos"; 
$IDU = $_SESSION['IDUg'] ?? '1'; 
$IDS = $_SESSION['IDS'] ?? '1'; 
$prefijo = $IDU . "-";
$vendedor = $_SESSION['NombreUsuario'] ?? "Admin";

// GENERACIÓN DE FOLIO (V-YYMMDD-XXX)
try {
    $pdo = new PDO("mysql:host=localhost;dbname=$DB_NAME;charset=utf8", "root", "33comRxXMysql"); 
    $hoy = date('ymd'); 
    $prefijoFolio = "V-" . $hoy . "-";
    $sqlF = "SELECT Folio FROM `{$prefijo}Ventas_Cabecera` WHERE Folio LIKE '$prefijoFolio%' ORDER BY ID_Venta DESC LIMIT 1";
    $resF = $pdo->query($sqlF)->fetch(PDO::FETCH_ASSOC);
    $nuevoCont = $resF ? intval(substr($resF['Folio'], -3)) + 1 : 1;
    $folioActual = $prefijoFolio . str_pad($nuevoCont, 3, "0", STR_PAD_LEFT);
} catch (Exception $e) { $folioActual = "V-".date('ymd')."-001"; }

include_once('../librerias/Modulos/ImpresoraNV.php'); 
?>

<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
<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">

<style>
    :root { 
        --neon-blue: #00d2ff; --neon-green: #39ff14; --neon-orange: #ff9f0a;
        --vivid-purple: #6c5ce7; --dark-bg: #1a1a2e; --glass: rgba(255, 255, 255, 0.95);
    }
    body { background-color: #f0f4f8; font-family: 'Outfit', sans-serif; color: #1a1a2e; }

    /* UI VIBRANTE */
    .card-vibrant { 
        border: none; border-radius: 25px; background: #fff; 
        box-shadow: 0 10px 40px rgba(0,0,0,0.08); transition: 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    }
    .card-vibrant:hover { transform: translateY(-10px); box-shadow: 0 20px 50px rgba(0,0,0,0.15); }
    
    .gradient-blue { background: linear-gradient(135deg, #4e73df 0%, #00d2ff 100%); color: white; }
    .gradient-green { background: linear-gradient(135deg, #1cc88a 0%, #39ff14 100%); color: white; }
    .gradient-orange { background: linear-gradient(135deg, #f6c23e 0%, #ff9f0a 100%); color: white; }
    .gradient-purple { background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%); color: white; }

    .glass-header { background: var(--glass); backdrop-filter: blur(15px); border-radius: 30px; border: 1px solid rgba(255,255,255,0.3); }
    
    /* BOTONES */
    .btn-neon { border-radius: 15px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; transition: 0.3s; }
    .btn-neon-primary { background: var(--vivid-purple); color: white; box-shadow: 0 5px 15px rgba(108, 92, 231, 0.4); }
    .btn-neon-primary:hover { transform: scale(1.05); background: #5b4bc4; }

    .btn-action { width: 42px; height: 42px; border-radius: 14px; display: inline-flex; align-items: center; justify-content: center; border: none; color: white; font-size: 1.1rem; }
    .btn-wa { background: #25D366; box-shadow: 0 4px 12px rgba(37,211,102,0.3); }
    .btn-qr { background: var(--neon-blue); box-shadow: 0 4px 12px rgba(0,210,255,0.3); }
    .btn-eye { background: #f1f3f9; color: var(--vivid-purple); }

    /* TABLA */
    .table thead th { border: none; color: #888; font-weight: 600; text-transform: uppercase; font-size: 0.75rem; }
    .table td { vertical-align: middle; border-top: 1px solid #f1f3f9; font-weight: 500; }

    .item-plan-pos { border: 2px solid #f1f3f9; border-radius: 20px; padding: 20px; cursor: pointer; transition: 0.3s; }
    .item-plan-pos.selected { border-color: var(--vivid-purple); background: #f3f0ff; transform: scale(0.95); }
</style>

<div class="container-fluid py-4 no-print">
    <div class="row mb-4">
        <div class="col-md-3 mb-4">
            <div class="card card-vibrant gradient-blue p-4">
                <div class="d-flex justify-content-between">
                    <div><h6 class="font-weight-bold opacity-7">SOCIOS TOTALES</h6><h2 id="kpi_totales" class="font-weight-bold mb-0">0</h2></div>
                    <i class="fas fa-users fa-2x opacity-5"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card card-vibrant gradient-green p-4">
                <div class="d-flex justify-content-between">
                    <div><h6 class="font-weight-bold opacity-7">MEMBRESÍAS ACTIVAS</h6><h2 id="kpi_activos" class="font-weight-bold mb-0">0</h2></div>
                    <i class="fas fa-bolt fa-2x opacity-5"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card card-vibrant gradient-orange p-4">
                <div class="d-flex justify-content-between">
                    <div><h6 class="font-weight-bold opacity-7">VENCEN ESTA SEMANA</h6><h2 id="kpi_vencer" class="font-weight-bold mb-0">0</h2></div>
                    <i class="fas fa-clock fa-2x opacity-5"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card card-vibrant gradient-purple p-4">
                <div class="d-flex justify-content-between">
                    <div><h6 class="font-weight-bold opacity-7">RECAUDADO MES</h6><h2 id="kpi_ingresos" class="font-weight-bold mb-0">$0.00</h2></div>
                    <i class="fas fa-coins fa-2x opacity-5"></i>
                </div>
            </div>
        </div>
    </div>

    <div class="glass-header p-4 d-flex justify-content-between align-items-center shadow-sm">
        <h3 class="font-weight-bold mb-0"><i class="fas fa-rocket mr-2 text-primary"></i>Gym Management <span class="text-primary">PRO</span></h3>
        <div class="d-flex align-items-center">
            <div class="text-right mr-4"><small class="text-muted d-block">FOLIO DE CAJA</small><b class="text-dark font-weight-bold"><?= $folioActual ?></b></div>
            <ul class="nav nav-pills bg-light rounded-pill p-1 shadow-inner">
                <li class="nav-item"><a class="nav-link active rounded-pill px-4" data-toggle="pill" href="#v-venta">CAJA</a></li>
                <li class="nav-item"><a class="nav-link rounded-pill px-4" data-toggle="pill" href="#v-catalogo" onclick="listarCatalogo()">PLANES</a></li>
            </ul>
        </div>
    </div>

    <div class="tab-content mt-5">
        <div class="tab-pane fade show active" id="v-venta">
            <div class="row">
                <div class="col-lg-4">
                    <div class="card card-vibrant p-4 mb-4">
                        <h5 class="font-weight-bold mb-4">1. Identificar Socio</h5>
                        <div class="input-group shadow-sm border rounded-pill overflow-hidden bg-white p-1">
                            <div class="input-group-prepend"><span class="input-group-text bg-white border-0"><i class="fas fa-search text-primary"></i></span></div>
                            <input type="text" id="src_socio" class="form-control border-0" placeholder="Escribe nombre o celular...">
                        </div>
                        <div id="res_socio" class="list-group mt-2 shadow-lg" style="position:absolute; z-index:100; width:88%;"></div>

                        <div id="perfil_socio" class="mt-5 p-4 rounded-xl border bg-light text-center d-none shadow-inner">
                            <div class="avatar gradient-blue text-white rounded-circle mx-auto mb-3 d-flex align-items-center justify-content-center shadow-lg" style="width:90px; height:90px; font-size:2.5rem;" id="p_avatar"></div>
                            <h4 id="p_nombre" class="font-weight-bold text-dark mb-1"></h4>
                            <p id="p_tel" class="text-muted mb-4"></p>
                            <button class="btn btn-neon-primary btn-block btn-lg shadow" onclick="abrirModalVenta()">ACTIVAR PLAN AHORA</button>
                        </div>
                    </div>
                </div>

                <div class="col-lg-8">
                    <div class="card card-vibrant p-4">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h5 class="font-weight-bold mb-0">Movimientos de Hoy</h5>
                            <button class="btn btn-light btn-sm rounded-pill px-3" onclick="listarAsignadas()"><i class="fas fa-sync"></i></button>
                        </div>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr><th>SOCIO</th><th>PLAN</th><th class="text-center">VIGENCIA</th><th class="text-right">PAGO</th><th class="text-center">ACCIONES</th></tr>
                                </thead>
                                <tbody id="tbody_asignadas"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="v-catalogo">
            <div class="d-flex justify-content-end mb-4 px-3">
                <button class="btn btn-neon-primary btn-lg shadow rounded-pill" onclick="nuevoPlan()"><i class="fas fa-plus mr-2"></i>CREAR NUEVO PLAN</button>
            </div>
            <div class="row" id="grid_catalogo"></div>
        </div>
    </div>
</div>

<div class="modal fade no-print" id="modalVenta" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 card-vibrant" style="overflow:hidden;">
            <div class="modal-header border-0 bg-light p-4">
                <h5 class="modal-title font-weight-bold">Confirmar Activación</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body p-5">
                <div class="row" id="venta_grid_planes"></div>
                <div class="row mt-5 align-items-center">
                    <div class="col-md-6">
                        <label class="small font-weight-bold text-muted">MÉTODO DE PAGO</label>
                        <select id="v_metodo" class="form-control rounded-pill mb-4 border-2"><option>Efectivo</option><option>Tarjeta</option></select>
                        <label class="small font-weight-bold text-muted">INICIA EL DÍA</label>
                        <input type="date" id="v_fecha_ini" class="form-control rounded-pill border-2" value="<?= date('Y-m-d') ?>" onchange="recalcVenta()">
                    </div>
                    <div class="col-md-6 text-right">
                        <div class="p-4 rounded-xl border-0 shadow-sm" style="background: #f8f9fc;">
                            <small class="text-muted font-weight-bold">FECHA DE VENCIMIENTO:</small>
                            <h4 id="v_fecha_fin" class="text-danger font-weight-bold mb-3">--</h4>
                            <h1 class="font-weight-bold mb-0 text-dark">$<span id="v_total">0.00</span></h1>
                        </div>
                    </div>
                </div>
                <button id="btn_pagar" class="btn btn-neon-primary btn-block btn-lg mt-5 py-4 shadow-lg font-weight-bold" onclick="finalizarVenta()">PROCESAR PAGO E IMPRIMIR</button>
            </div>
        </div>
    </div>
</div>

<script>
const CFG = { px: '<?= $prefijo ?>', db: '<?= $DB_NAME ?>', idu: '<?= $IDU ?>', ids: '<?= $IDS ?>', fol: '<?= $folioActual ?>', vend: '<?= $vendedor ?>' };
let socioID = null, socioNombre = "", socioTel = "", planSel = null;

// --- 1. WIDGETS ---
function actualizarWidgets() {
    const fd = new FormData(); fd.append('db', CFG.db);
    const hoy = new Date().toISOString().split('T')[0];
    const queries = [
        { sql: `SELECT COUNT(*) as t FROM \`${CFG.px}Clientes\` WHERE EstadoCliente='Activo'`, id: 'kpi_totales' },
        { sql: `SELECT COUNT(DISTINCT IDC) as t FROM \`${CFG.px}Gym_Membresias_Asignadas\` WHERE Fecha_Fin >= '${hoy}'`, id: 'kpi_activos' },
        { sql: `SELECT COUNT(DISTINCT IDC) as t FROM \`${CFG.px}Gym_Membresias_Asignadas\` WHERE Fecha_Fin BETWEEN '${hoy}' AND DATE_ADD('${hoy}', INTERVAL 7 DAY)`, id: 'kpi_vencer' },
        { sql: `SELECT SUM(Monto_Pagado) as t FROM \`${CFG.px}Gym_Membresias_Asignadas\` WHERE Timestamp >= '${hoy.substring(0,8)}01 00:00:00'`, id: 'kpi_ingresos', cur: true }
    ];
    queries.forEach(q => {
        fd.set('sql', q.sql);
        fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd }).then(r => r.json()).then(res => {
            let val = (res.data || [])[0]?.t || 0;
            document.getElementById(q.id).innerText = q.cur ? '$' + parseFloat(val).toFixed(2) : val;
        });
    });
}

// --- 2. ACCIONES: WHATSAPP, QR Y DETALLES ---
function enviarWA(tel, nom, plan, fin) {
    const msg = encodeURIComponent(`¡Hola ${nom}! Tu membresía ${plan} ha sido activada. Vence el ${fin}. ¡A darle con todo! 💪`);
    window.open(`https://wa.me/52${tel}?text=${msg}`, '_blank');
}

function verQR(idS) {
    // LINK EXACTO SOLICITADO
    const link = `http://167.172.224.160/MS/P/PageGym.php?idu=${CFG.idu}&idc=${idS}`;
    Swal.fire({
        title: 'App del Socio',
        text: 'Escanea para ver tus rutinas',
        imageUrl: `https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=${encodeURIComponent(link)}`,
        imageWidth: 250, imageHeight: 250, confirmButtonColor: '#6c5ce7'
    });
}

function verDetalles(b64) {
    const r = JSON.parse(atob(b64));
    Swal.fire({
        title: 'Detalle de Membresía',
        html: `<div class="text-left"><b>Socio:</b> ${r.Socio}<br><b>Plan:</b> ${r.Plan}<br><b>Inicia:</b> ${r.Fecha_Inicio}<br><b>Vence:</b> ${r.Fecha_Fin}<br><b>Monto:</b> $${r.Monto_Pagado}</div>`,
        icon: 'info'
    });
}

// --- 3. FINALIZAR VENTA (INTEGRACIÓN TOTAL) ---
async function finalizarVenta() {
    if(!socioID || !planSel) return;
    const btn = document.getElementById('btn_pagar');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> PROCESANDO...';

    const fIni = document.getElementById('v_fecha_ini').value;
    const fFin = document.getElementById('v_fecha_fin').innerText;
    const total = parseFloat(document.getElementById('v_total').innerText);
    const metodo = document.getElementById('v_metodo').value;

    try {
        // A. CABECERA
        const sqlCab = `INSERT INTO \`${CFG.px}Ventas_Cabecera\` (Folio, IDC_Cliente, IDU_Usuario, IDS_Sucursal, Metodo_Pago, Subtotal, Total, Estado, Notas_Venta) 
                        VALUES ('${CFG.fol}', ${socioID}, '${CFG.idu}', ${CFG.ids}, '${metodo}', ${total}, ${total}, 'Pagado', 'Plan: ${planSel.Nombre}')`;
        const rCab = await apiExec(sqlCab);
        const idV = rCab.last_id;

        // B. DETALLE
        const sqlDet = `INSERT INTO \`${CFG.px}Ventas_Detalle\` (ID_Venta, SKU, Nombre_Producto, Cantidad, Precio_Venta, Costo_Original, Subtotal) 
                        VALUES (${idV}, 'MEM-${planSel.IDM}', '${planSel.Nombre}', 1, ${total}, ${total}, ${total})`;
        
        // C. ASIGNACIÓN GYM
        const sqlMem = `INSERT INTO \`${CFG.px}Gym_Membresias_Asignadas\` (IDC, IDM, Fecha_Inicio, Fecha_Fin, Monto_Pagado, Metodo_Pago) 
                        VALUES (${socioID}, ${planSel.IDM}, '${fIni}', '${fFin}', ${total}, '${metodo}')`;
        
        await apiExec(sqlDet + ";" + sqlMem);

        // D. DOCUMENTO GENERADO (JSON EXACTO)
        const docJSON = {
            dsc: "0.00", iva: "0.00", obs: "", sub: total.toFixed(2),
            folio: CFG.fol, idRef: idV.toString(),
            items: [{ qty: 1, sku: "GEN-" + Math.floor(Math.random()*900000), costo: 0, price: total, nombre: planSel.Nombre }],
            total: total, metodo: metodo, cliente: socioNombre, telefono: socioTel
        };

        const sqlDoc = `INSERT INTO \`${CFG.px}Documentos_Generados\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) 
                        VALUES ('${CFG.fol}', 'NotaVenta', ${idV}, 1, '${JSON.stringify(docJSON)}', 'PENDIENTE')`;
        await apiExec(sqlDoc);

        $('#modalVenta').modal('hide');
        if(typeof PrintEngine !== 'undefined') { PrintEngine.show(docJSON); } else { location.reload(); }

    } catch(e) { btn.disabled = false; btn.innerHTML = 'REINTENTAR'; }
}

// --- HELPERS ---
async function apiExec(sql) {
    const fd = new FormData(); fd.append('sql', sql); fd.append('db', CFG.db);
    return await fetch('../librerias/AJAX/Execute.php', { method: 'POST', body: fd }).then(r => r.json());
}

function listarAsignadas() {
    const fd = new FormData(); fd.append('db', CFG.db);
    fd.append('sql', `SELECT m.*, c.Nombre as Socio, c.Telefono, p.Nombre as Plan FROM \`${CFG.px}Gym_Membresias_Asignadas\` m JOIN \`${CFG.px}Clientes\` c ON m.IDC = c.IDC JOIN \`${CFG.px}Gym_Membresias_Planes\` p ON m.IDM = p.IDM ORDER BY m.IDMA DESC LIMIT 10`);
    fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd }).then(r => r.json()).then(res => {
        const tb = document.getElementById('tbody_asignadas'); tb.innerHTML = '';
        (res.data || []).forEach(r => {
            const b6 = btoa(JSON.stringify(r));
            tb.innerHTML += `<tr>
                <td><b>${r.Socio}</b></td>
                <td><span class="badge badge-light border px-2">${r.Plan}</span></td>
                <td class="text-center small"><b>${r.Fecha_Fin}</b></td>
                <td class="text-right text-success font-weight-bold">$${r.Monto_Pagado}</td>
                <td class="text-center">
                    <button class="btn-action btn-wa" onclick="enviarWA('${r.Telefono}','${r.Socio}','${r.Plan}','${r.Fecha_Fin}')"><i class="fab fa-whatsapp"></i></button>
                    <button class="btn-action btn-qr ml-1" onclick="verQR('${r.IDC}')"><i class="fas fa-qrcode"></i></button>
                    <button class="btn-action btn-eye ml-1" onclick="verDetalles('${b6}')"><i class="fas fa-eye"></i></button>
                </td>
            </tr>`;
        });
    });
}

function listarCatalogo() {
    const fd = new FormData(); fd.append('db', CFG.db);
    fd.append('sql', `SELECT * FROM \`${CFG.px}Gym_Membresias_Planes\` WHERE Estado='Activo'`);
    fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd }).then(r => r.json()).then(res => {
        const g = document.getElementById('grid_catalogo'); g.innerHTML = '';
        (res.data || []).forEach(p => {
            g.innerHTML += `<div class="col-md-4 mb-4"><div class="card card-vibrant p-4 border-top border-primary"><h5>${p.Nombre}</h5><h3 class="text-primary font-weight-bold">$${p.Precio}</h3><p class="small text-muted mb-0">${p.Duracion_Dias} días</p></div></div>`;
        });
    });
}

function nuevoPlan() {
    Swal.fire({
        title: 'Nuevo Plan de Entrenamiento',
        html: `<input id="n_nom" class="swal2-input" placeholder="Nombre (Ej: Mensual VIP)">
               <input id="n_pre" type="number" class="swal2-input" placeholder="Precio ($)">
               <input id="n_dia" type="number" class="swal2-input" placeholder="Duración (Días)">`,
        preConfirm: () => {
            const n = document.getElementById('n_nom').value, p = document.getElementById('n_pre').value, d = document.getElementById('n_dia').value;
            if(!n || !p || !d) return Swal.showValidationMessage('Todos los campos son obligatorios');
            return { n, p, d };
        }
    }).then(r => {
        if(r.isConfirmed) {
            const sql = `INSERT INTO \`${CFG.px}Gym_Membresias_Planes\` (Nombre, Precio, Duracion_Dias, Estado) VALUES ('${r.value.n}', ${r.value.p}, ${r.value.d}, 'Activo')`;
            apiExec(sql).then(() => { listarCatalogo(); actualizarWidgets(); Swal.fire('Plan Creado', '', 'success'); });
        }
    });
}

// Inicialización Búsqueda
document.getElementById('src_socio').addEventListener('input', function() {
    let t = this.value; if(t.length < 2) return;
    const fd = new FormData(); fd.append('db', CFG.db);
    fd.append('sql', `SELECT IDC, Nombre, Telefono FROM \`${CFG.px}Clientes\` WHERE Nombre LIKE '%${t}%' OR Telefono LIKE '%${t}%' LIMIT 5`);
    fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd }).then(r => r.json()).then(res => {
        let h = ''; (res.data || []).forEach(s => { h += `<a href="#" class="list-group-item list-group-item-action border-0 shadow-sm" onclick='setSocio(${JSON.stringify(s)})'>${s.Nombre}</a>`; });
        document.getElementById('res_socio').innerHTML = h;
    });
});
function setSocio(s) {
    socioID = s.IDC; socioNombre = s.Nombre; socioTel = s.Telefono;
    document.getElementById('p_nombre').innerText = s.Nombre;
    document.getElementById('p_avatar').innerText = s.Nombre[0];
    document.getElementById('perfil_socio').classList.remove('d-none'); document.getElementById('res_socio').innerHTML = '';
}
function abrirModalVenta() {
    const fd = new FormData(); fd.append('db', CFG.db);
    fd.append('sql', `SELECT * FROM \`${CFG.px}Gym_Membresias_Planes\` WHERE Estado='Activo'`);
    fetch('../librerias/AJAX/Select.php', { method: 'POST', body: fd }).then(r => r.json()).then(res => {
        const grid = document.getElementById('venta_grid_planes'); grid.innerHTML = '';
        (res.data || []).forEach(p => { grid.innerHTML += `<div class="col-6 mb-2"><div class="item-plan-pos" onclick='selectPlanVenta(this, ${JSON.stringify(p)})'><b>${p.Nombre}</b><br>$${p.Precio}</div></div>`; });
        $('#modalVenta').modal('show');
    });
}
function selectPlanVenta(el, p) {
    document.querySelectorAll('.item-plan-pos').forEach(x => x.classList.remove('selected'));
    el.classList.add('selected'); planSel = p;
    document.getElementById('v_total').innerText = parseFloat(p.Precio).toFixed(2); recalcVenta();
}
function recalcVenta() {
    if(!planSel) return;
    let d = new Date(document.getElementById('v_fecha_ini').value);
    d.setDate(d.getDate() + parseInt(planSel.Duracion_Dias));
    document.getElementById('v_fecha_fin').innerText = d.toISOString().split('T')[0];
}
document.addEventListener('DOMContentLoaded', () => { actualizarWidgets(); listarAsignadas(); });
</script>