// RECREOPAY - LÓGICA DE CLIENTE PWA (ESTUDIANTES Y PADRES) let students = []; let currentStudent = null; let categories = []; let products = []; let activeCategoryId = null; let cart = []; let currentAppMode = 'kids'; // Inicialización al cargar la página document.addEventListener('DOMContentLoaded', async () => { // Registrar Service Worker para PWA si está soportado if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(err => console.log('SW error:', err)); } await loadInitialData(); }); async function loadInitialData() { try { // 1. Cargar estudiantes const resEst = await fetch('/api/estudiantes'); students = await resEst.json(); populateStudentSelector(); // Seleccionar por defecto el primer estudiante (Mateo, 8 años -> Modo Kids) if (students.length > 0) { await selectStudent(students[0].id); } // 2. Cargar productos y categorías const resProd = await fetch('/api/productos'); const dataProd = await resProd.json(); categories = dataProd.categorias; products = dataProd.productos; renderCategories(); renderProducts(); } catch (error) { console.error('Error cargando datos iniciales:', error); } } function populateStudentSelector() { const sel = document.getElementById('studentSelector'); sel.innerHTML = students.map(s => ` `).join(''); } async function onStudentChange(studentId) { await selectStudent(studentId); } async function selectStudent(studentId) { try { const res = await fetch(`/api/estudiantes/${studentId}`); currentStudent = await res.json(); // Adaptar modo automáticamente por edad (7-10 Kids, 11-15 Teens) if (currentStudent.edad <= 10) { setAppMode('kids', false); } else { setAppMode('teens', false); } updateStudentUI(); } catch (e) { console.error('Error seleccionando estudiante:', e); } } function updateStudentUI() { if (!currentStudent) return; // Actualizar avatar, nombre y grado document.getElementById('walletAvatar').src = currentStudent.foto_url || 'https://api.dicebear.com/7.x/bottts/svg?seed=est'; document.getElementById('walletName').textContent = currentStudent.nombre_completo; document.getElementById('walletGrade').textContent = `${currentStudent.grado} • Sección ${currentStudent.seccion} • Cód: ${currentStudent.codigo_estudiante}`; // Saldo en colones document.getElementById('walletBalance').textContent = `₡${currentStudent.saldo_colones.toLocaleString('es-CR')}`; // Límite diario document.getElementById('dailyLimitText').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`; document.getElementById('dailyAvailableText').textContent = `Disponible hoy: ₡${currentStudent.disponible_hoy.toLocaleString('es-CR')}`; // Alergias const allergyBox = document.getElementById('allergyWarning'); if (currentStudent.alergias && currentStudent.alergias !== 'Ninguna' && currentStudent.alergias !== 'Ninguna conocida') { allergyBox.style.display = 'flex'; document.getElementById('allergyText').textContent = currentStudent.alergias; } else { allergyBox.style.display = 'none'; } // QR Modal info document.getElementById('qrDisplayImg').src = `/api/qr-image/${encodeURIComponent(currentStudent.qr_token)}`; document.getElementById('qrTokenDisplay').textContent = currentStudent.qr_token; // Panel de Padres sliders y valores document.getElementById('lblParentDailyLimit').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`; document.getElementById('rangeDailyLimit').value = currentStudent.limite_diario_colones; renderParentHistory(); } function setAppMode(mode, playSound = true) { currentAppMode = mode; document.body.classList.remove('mode-kids', 'mode-teens'); document.getElementById('btnModeKids').classList.remove('active'); document.getElementById('btnModeTeens').classList.remove('active'); if (mode === 'kids') { document.body.classList.add('mode-kids'); document.getElementById('btnModeKids').classList.add('active'); document.getElementById('balanceLabel').textContent = '💰 Mis Colones para el Recreo'; document.getElementById('kidsCoinIcon').style.display = 'inline-block'; document.getElementById('qrBtnText').textContent = 'Tocar para mi QR 📱'; } else { document.body.classList.add('mode-teens'); document.getElementById('btnModeTeens').classList.add('active'); document.getElementById('balanceLabel').textContent = 'SALDO DISPONIBLE'; document.getElementById('kidsCoinIcon').style.display = 'none'; document.getElementById('qrBtnText').textContent = 'QR de Pago'; } if (playSound && window.sounds) { window.sounds.playCoin(); } } // Renderizado de Categorías function renderCategories() { const bar = document.getElementById('categoriesBar'); let html = ` `; for (const cat of categories) { html += ` `; } bar.innerHTML = html; } function selectCategory(catId) { activeCategoryId = catId; renderCategories(); renderProducts(); } // Renderizado de Productos del Menú function renderProducts() { const grid = document.getElementById('productsGrid'); const filterMepOnly = document.getElementById('chkFilterMep').checked; let filtered = products; if (activeCategoryId !== null) { filtered = filtered.filter(p => p.categoria_id === activeCategoryId); } if (filterMepOnly) { filtered = filtered.filter(p => p.cumple_mep === 1); } if (filtered.length === 0) { grid.innerHTML = `

🥪

No hay productos en esta categoría por ahora.

`; return; } grid.innerHTML = filtered.map(prod => `
${prod.icono || '🥪'}
${prod.cumple_mep ? '🌿 MEP Saludable' : ''}

${prod.nombre}

${prod.descripcion || ''}

${prod.alergenos ? `
⚠️ Contiene: ${prod.alergenos}
` : ''}
`).join(''); } // ========================================== // CARRITO Y PRE-ÓRDENES // ========================================== function addToCart(productId) { const prod = products.find(p => p.id === productId); if (!prod) return; const existing = cart.find(item => item.product.id === productId); if (existing) { existing.cantidad++; } else { cart.push({ product: prod, cantidad: 1 }); } if (window.sounds) { window.sounds.playCoin(); } updateCartBar(); } function updateCartBar() { const bar = document.getElementById('floatingCart'); const countBadge = document.getElementById('cartCountBadge'); const totalText = document.getElementById('cartTotalText'); const totalCount = cart.reduce((sum, item) => sum + item.cantidad, 0); const totalColones = cart.reduce((sum, item) => sum + (item.product.precio_colones * item.cantidad), 0); if (totalCount > 0) { bar.style.display = 'flex'; countBadge.textContent = `${totalCount} ${totalCount === 1 ? 'ítem' : 'ítems'}`; totalText.textContent = `₡${totalColones.toLocaleString('es-CR')}`; } else { bar.style.display = 'none'; } } function openCartModal() { renderCartModalItems(); document.getElementById('modalCart').style.display = 'flex'; } function closeCartModal(e) { if (e && e.target !== e.currentTarget) return; document.getElementById('modalCart').style.display = 'none'; } function renderCartModalItems() { const list = document.getElementById('cartItemsList'); const totalEl = document.getElementById('modalCartTotal'); if (cart.length === 0) { list.innerHTML = '

El carrito está vacío

'; totalEl.textContent = '₡0'; return; } let total = 0; list.innerHTML = cart.map((item, idx) => { const subtotal = item.product.precio_colones * item.cantidad; total += subtotal; return `
${item.product.icono} ${item.product.nombre}
₡${item.product.precio_colones.toLocaleString('es-CR')} c/u
${item.cantidad} ₡${subtotal.toLocaleString('es-CR')}
`; }).join(''); totalEl.textContent = `₡${total.toLocaleString('es-CR')}`; } function changeCartQty(index, delta) { cart[index].cantidad += delta; if (cart[index].cantidad <= 0) { cart.splice(index, 1); } renderCartModalItems(); updateCartBar(); } async function submitPreOrder() { if (!currentStudent) return; if (cart.length === 0) return alert('Agrega al menos un producto a tu pre-orden'); const momento = document.getElementById('momentoEntregaSelect').value; const items = cart.map(item => ({ producto_id: item.product.id, cantidad: item.cantidad })); const btn = document.getElementById('btnConfirmarOrden'); btn.disabled = true; btn.textContent = 'Procesando en la soda...'; try { const res = await fetch('/api/ordenes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ estudiante_id: currentStudent.id, tipo_orden: 'preorden', momento_entrega: momento, items }) }); const data = await res.json(); if (!res.ok) { if (window.sounds) window.sounds.playError(); throw new Error(data.error || 'Error procesando pre-orden'); } if (window.sounds) window.sounds.playSuccess(); alert(`🎉 ¡Pre-Orden confirmada con éxito!\nCódigo de entrega: ${data.codigo_orden}\nRebajada de tu monedero: ₡${data.total_colones.toLocaleString('es-CR')}\n\nPodrás retirarla en la fila rápida de la soda durante el recreo presentando tu QR.`); // Limpiar carrito y recargar datos del estudiante cart = []; updateCartBar(); closeCartModal(); await selectStudent(currentStudent.id); } catch (err) { alert(`❌ No se pudo procesar: ${err.message}`); } finally { btn.disabled = false; btn.textContent = '✅ Confirmar y Pagar Pre-Orden'; } } // ========================================== // MODAL QR ESCOLAR // ========================================== function openQrModal() { if (window.sounds) window.sounds.playScanChirp(); document.getElementById('modalQr').style.display = 'flex'; } function closeQrModal(e) { if (e && e.target !== e.currentTarget) return; document.getElementById('modalQr').style.display = 'none'; } // ========================================== // PANEL DE PADRES Y RECARGAS SINPE // ========================================== function toggleParentPanel(show, e) { if (e && e.target !== e.currentTarget) return; document.getElementById('modalPadres').style.display = show ? 'flex' : 'none'; } async function quickSinpeRecharge(monto) { await doSinpeRecharge(monto); } async function customSinpeRecharge() { const val = parseInt(document.getElementById('inputCustomSinpe').value, 10); if (!val || val <= 0) return alert('Ingresa un monto válido en colones'); await doSinpeRecharge(val); document.getElementById('inputCustomSinpe').value = ''; } async function doSinpeRecharge(monto) { if (!currentStudent) return; const comprobante = `SINPE-${Math.floor(100000 + Math.random() * 900000)}`; try { const res = await fetch(`/api/estudiantes/${currentStudent.id}/recarga`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ monto, comprobante, descripcion: `Recarga SINPE Móvil desde portal de padres` }) }); const data = await res.json(); if (!res.ok) throw new Error(data.error); if (window.sounds) window.sounds.playSuccess(); alert(`✅ ¡Recarga SINPE exitosa!\nSe acreditaron ₡${monto.toLocaleString('es-CR')} al monedero de ${currentStudent.nombre_completo}.\nComprobante: ${comprobante}`); await selectStudent(currentStudent.id); } catch (err) { alert(`Error en recarga: ${err.message}`); } } async function onDailyLimitSlider(val) { document.getElementById('lblParentDailyLimit').textContent = `₡${parseInt(val, 10).toLocaleString('es-CR')}`; if (!currentStudent) return; try { await fetch(`/api/estudiantes/${currentStudent.id}/limite`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ limite_diario_colones: parseInt(val, 10) }) }); // Actualizar UI sutilmente currentStudent.limite_diario_colones = parseInt(val, 10); document.getElementById('dailyLimitText').textContent = `₡${currentStudent.limite_diario_colones.toLocaleString('es-CR')}`; } catch (e) {} } function renderParentHistory() { const container = document.getElementById('parentHistoryList'); if (!currentStudent || !currentStudent.transacciones || currentStudent.transacciones.length === 0) { container.innerHTML = '

Sin movimientos recientes

'; return; } container.innerHTML = currentStudent.transacciones.map(t => { const esPositivo = t.monto_colones > 0; const color = esPositivo ? '#166534' : '#0f172a'; const signo = esPositivo ? '+' : ''; const fecha = new Date(t.fecha).toLocaleDateString('es-CR', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); return `
${t.descripcion || t.tipo}
${fecha}
${signo}₡${Math.abs(t.monto_colones).toLocaleString('es-CR')}
`; }).join(''); }