async function postJson(url, body){ const res = await fetch(url, {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)}); const data = await res.json().catch(()=>({ok:false,error:'Respuesta inválida'})); if(!res.ok || !data.ok) throw new Error(data.error || 'Error'); return data; } function v(id){ return document.getElementById(id).value; } function n(id){ const x = document.getElementById(id).value; return x===''? null : Number(x); } function lv(id){ return Number(document.getElementById(id).value); } function syncAnonUI(){ const anon = document.getElementById('anon_mode').checked; const leadFields = document.getElementById('leadFields'); const consent = document.getElementById('consent'); if(anon){ leadFields.style.display = 'none'; consent.checked = false; consent.disabled = true; } else { leadFields.style.display = ''; consent.disabled = false; } } document.getElementById('anon_mode').addEventListener('change', syncAnonUI); syncAnonUI(); document.getElementById('btnSubmit').addEventListener('click', async ()=>{ const msg = document.getElementById('msg'); msg.textContent = ''; try{ const anon = document.getElementById('anon_mode').checked; const consent = (!anon && document.getElementById('consent').checked) ? 1 : 0; if(!anon && consent !== 1){ throw new Error('Para registrar tus datos debes marcar el consentimiento. O activa modo anónimo.'); } const leadPayload = anon ? { anonymous: 1, tipo_negocio: v('tipo_negocio'), consent: 0 } : { nombre: v('nombre'), email: v('email'), whatsapp: v('whatsapp'), negocio: v('negocio'), tipo_negocio: v('tipo_negocio'), consent }; const lead = await postJson('../api/init_lead.php', leadPayload); const inputs = { tipo_negocio: v('tipo_negocio'), ingreso_promedio_mensual: n('ingreso_promedio_mensual'), gasto_mensual_total: n('gasto_mensual_total'), deuda_total: n('deuda_total'), pago_mensual_deuda: n('pago_mensual_deuda'), caja_bancos_actual: n('caja_bancos_actual'), fin_separacion_cuentas_nivel: lv('fin_separacion_cuentas_nivel'), fin_registro_flujo_caja_nivel: lv('fin_registro_flujo_caja_nivel'), fin_presupuesto_vs_real_nivel: lv('fin_presupuesto_vs_real_nivel'), proceso_principal_nombre: v('proceso_principal_nombre'), costo_mensual_proceso_principal: n('costo_mensual_proceso_principal'), porcentaje_ineficiencia: n('porcentaje_ineficiencia'), proc_documentacion_nivel: lv('proc_documentacion_nivel'), proc_medicion_tiempos_nivel: lv('proc_medicion_tiempos_nivel'), proc_costeo_recursos_nivel: lv('proc_costeo_recursos_nivel'), ventas_mensuales_canal_principal: n('ventas_mensuales_canal_principal'), gasto_marketing_mensual: n('gasto_marketing_mensual'), com_registro_ventas_canal_nivel: lv('com_registro_ventas_canal_nivel'), com_margen_por_canal_nivel: lv('com_margen_por_canal_nivel'), com_seguimiento_roi_mkt_nivel: lv('com_seguimiento_roi_mkt_nivel'), numero_personas: Number(v('numero_personas')), nomina_mensual_total: n('nomina_mensual_total'), horas_perdidas_mes_por_desorganizacion: n('horas_perdidas_mes_por_desorganizacion'), org_roles_funciones_nivel: lv('org_roles_funciones_nivel'), org_raci_nivel: lv('org_raci_nivel'), org_reunion_control_nivel: lv('org_reunion_control_nivel'), costo_regularizacion: n('costo_regularizacion'), multa_potencial: n('multa_potencial'), obligaciones_proximas_3_meses: n('obligaciones_proximas_3_meses'), cum_matriz_obligaciones_nivel: lv('cum_matriz_obligaciones_nivel'), cum_evidencias_nivel: lv('cum_evidencias_nivel'), cum_alertas_calendario_nivel: lv('cum_alertas_calendario_nivel'), ctrl_control_mensual_nivel: lv('ctrl_control_mensual_nivel'), }; const mp = document.getElementById('margen_promedio_pct').value; const cu = document.getElementById('costo_unitario').value; const pu = document.getElementById('precio_unitario').value; if(mp !== ''){ inputs.margen_promedio_pct = Number(mp); } else { inputs.costo_unitario = cu===''? null : Number(cu); inputs.precio_unitario = pu===''? null : Number(pu); } await postJson('../api/save_checklist.php', { chat_session_id: lead.chat_session_id, session_token: lead.session_token, diagnosis_id: lead.diagnosis_id, inputs }); await postJson('../api/calc_score.php', { chat_session_id: lead.chat_session_id, session_token: lead.session_token, diagnosis_id: lead.diagnosis_id }); // Generar plan (GPT backend) sin bloquear try { await postJson('../api/generate_plan.php', { diagnosis_id: lead.diagnosis_id }); } catch(e){} localStorage.setItem('sp_eval360_session', JSON.stringify({ chat_session_id: lead.chat_session_id, session_token: lead.session_token, diagnosis_id: lead.diagnosis_id, public_token: lead.public_token })); window.location.href = 'result.php'; } catch(e){ msg.textContent = e.message; } });