asdadsasd
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('groupForm');
const peopleFields = document.getElementById('peopleFields');
const numAdults = document.getElementById('numAdults');
const numChildren = document.getElementById('numChildren');
const jsonOutput = document.getElementById('jsonOutput');
// Elimina los campos de familia y representante del HTML
document.getElementById('family').parentElement.style.display = 'none';
document.getElementById('familyRepresentative').parentElement.style.display = 'none';
const IGLESIAS = [
'', 'APR_MURCIA', 'APR_CARTAGENA', 'APR_GRANADA', 'APR_ALICANTE', 'APR_LORCA', 'APR_AGUILAS', 'APR_HUERCAL', 'APR_VERA', 'APR_MOLINA', 'APR_ALCANTARILLA', 'APR_VEGA_BAJA', 'OTRA_IGLESIA'
];
const IGLESIAS_LABELS = {
'': 'Selecciona una opción',
'APR_MURCIA': 'APR MURCIA',
'APR_CARTAGENA': 'APR CARTAGENA',
'APR_GRANADA': 'APR GRANADA',
'APR_ALICANTE': 'APR ALICANTE',
'APR_LORCA': 'APR LORCA',
'APR_AGUILAS': 'APR ÁGUILAS',
'APR_HUERCAL': 'APR HUERCAL',
'APR_VERA': 'APR VERA',
'APR_MOLINA': 'APR MOLINA',
'APR_ALCANTARILLA': 'APR ALCANTARILLA',
'APR_VEGA_BAJA': 'APR VEGA BAJA',
'OTRA_IGLESIA': 'OTRA IGLESIA'
};
const LODGING_DAYS = [
{ value: '2025-08-17', label: 'Domingo 17' },
{ value: '2025-08-18', label: 'Lunes 18' },
{ value: '2025-08-19', label: 'Martes 19' },
{ value: '2025-08-20', label: 'Miércoles 20' },
{ value: '2025-08-21', label: 'Jueves 21' }
];
const TEST_MODE = false; // Pon a true para test, false para producción
let FORM_ID = '';
let productosAlojamiento = [];
// Al cargar, obtener el parámetro 'form' y pedir el formId
(async function() {
const params = new URLSearchParams(window.location.search);
const formName = params.get('form');
if (!formName) {
alert('Falta el parámetro ?form=... en la URL');
return;
}
try {
const res = await fetch(`${API_ENDPOINT}/form/by-name/${formName}`);
if (!res.ok) throw new Error('No se pudo obtener el formId');
const data = await res.json();
FORM_ID = data.formId || data.id || '';
if (!FORM_ID) throw new Error('No se encontró el formId');
// Cargar productos después de obtener el FORM_ID
await fetchProductosAlojamiento();
} catch (err) {
alert('Error al obtener el formId: ' + err.message);
}
})();
function renderPeopleFields() {
// Guardar valores actuales
const prevValues = {};
document.querySelectorAll('.person-section input, .person-section select, .person-section textarea').forEach(el => {
if (el.type === 'checkbox') {
if (!prevValues[el.name]) prevValues[el.name] = [];
if (el.checked) prevValues[el.name].push(el.value);
} else {
prevValues[el.name] = el.value;
}
});
const adults = parseInt(numAdults.value, 10) || 0;
const children = parseInt(numChildren.value, 10) || 0;
let html = '';
for (let i = 0; i < adults; i++) {
html += personFieldsHtml(i, 'adult');
}
for (let i = 0; i < children; i++) {
html += personFieldsHtml(i, 'child');
}
peopleFields.innerHTML = html;
// Restaurar valores
Object.keys(prevValues).forEach(name => {
const els = document.getElementsByName(name);
if (els.length) {
if (els[0].type === 'checkbox') {
els.forEach(cb => { cb.checked = prevValues[name].includes(cb.value); });
} else {
els[0].value = prevValues[name];
}
}
});
addDynamicListeners();
}
function personFieldsHtml(idx, type) {
const label = type === 'adult' ? `Adulto ${idx+1}` : `Niño ${idx+1}`;
const prefix = `${type}_${idx}_`;
// Valores de test
const test = TEST_MODE ? {
name: `TestNombre${idx+1}`,
surname: `TestApellido${idx+1}`,
age: type === 'adult' ? 35 + idx : 10 + idx,
phone: `60000000${idx+1}`,
email: `test${idx+1}@mail.com`,
dni: `0000000${idx+1}A`,
city: `TestCiudad${idx+1}`,
church: IGLESIAS[1],
otherChurch: '',
pastorName: `TestPastor${idx+1}`,
pastorPhone: `69999999${idx+1}`,
busTrip: 'false',
lactoseIntolerant: 'false',
celiac: 'false',
diabetic: 'false',
diseaseOrAllergies: '',
userNotes: `Notas de test para ${label}`
} : {};
return `
`;
}
function addDynamicListeners() {
// Sincronizar nombre y apellidos del primer adulto con los campos de cabecera y el campo family
const firstName = document.querySelector('[name="adult_0_name"]');
const firstSurname = document.querySelector('[name="adult_0_surname"]');
if (firstName && firstSurname) {
const sync = () => {
const full = `${firstName.value} ${firstSurname.value}`.trim();
const familyVal = full.toUpperCase().replace(/\s+/g, '_');
document.getElementById('family').value = familyVal;
document.getElementById('familyRepresentative').value = full;
};
firstName.addEventListener('input', sync);
firstSurname.addEventListener('input', sync);
sync();
}
// Mostrar/ocultar campos según iglesia
document.querySelectorAll('.church-select').forEach(select => {
select.addEventListener('change', function() {
const personSection = select.closest('.person-section');
const otherChurchGroup = personSection.querySelector('.other-church-group');
const pastorRow = personSection.querySelector('.pastor-row');
if (select.value === 'OTRA_IGLESIA') {
otherChurchGroup.style.display = '';
pastorRow.style.display = '';
} else {
otherChurchGroup.style.display = 'none';
pastorRow.style.display = 'none';
}
});
// Trigger al cargar
select.dispatchEvent(new Event('change'));
});
}
numAdults.addEventListener('input', renderPeopleFields);
numChildren.addEventListener('input', renderPeopleFields);
renderPeopleFields();
// Validación extra en el submit: al menos un día seleccionado
form.onsubmit = async function(e) {
e.preventDefault();
if (!FORM_ID) {
Swal.fire({ icon: 'error', title: 'Error', text: 'No se pudo obtener el formId. No se puede enviar el formulario.' });
return;
}
// Validar que cada persona tenga al menos un día seleccionado
const peopleSections = document.querySelectorAll('.person-section');
for (const section of peopleSections) {
const daysChecked = section.querySelectorAll("input[type='checkbox'][name$='lodgingDays']:checked");
if (daysChecked.length === 0) {
Swal.fire({ icon: 'error', title: 'Falta día de alojamiento', text: 'Cada persona debe seleccionar al menos un día de alojamiento.' });
section.scrollIntoView({ behavior: 'smooth', block: 'center' });
return;
}
}
const data = new FormData(form);
const family = data.get('family');
const familyRepresentative = data.get('familyRepresentative');
const adults = parseInt(numAdults.value, 10) || 0;
const children = parseInt(numChildren.value, 10) || 0;
const requests = [];
for (let i = 0; i < adults; i++) {
const obj = collectPersonData(data, i, 'adult', family, familyRepresentative);
obj.userNotes = obj.userNotes || '';
obj.formId = FORM_ID;
requests.push(obj);
}
for (let i = 0; i < children; i++) {
const obj = collectPersonData(data, i, 'child', family, familyRepresentative);
obj.userNotes = obj.userNotes || '';
obj.formId = FORM_ID;
requests.push(obj);
}
// Eliminar la visualización del JSON
jsonOutput.style.display = 'none';
console.log(requests);
// Confirmación antes de enviar
const confirm = await Swal.fire({
icon: 'question',
title: '¿Quieres enviar el formulario?',
showCancelButton: true,
confirmButtonText: 'Sí, enviar',
cancelButtonText: 'Cancelar',
confirmButtonColor: '#045d2d',
cancelButtonColor: '#d33'
});
if (!confirm.isConfirmed) return;
// Enviar al endpoint
try {
const res = await fetch(`${API_ENDPOINT}/form-entries/batch-cabin`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requests)
});
if (res.ok) {
await Swal.fire({ icon: 'success', title: '¡Formulario enviado correctamente!', showConfirmButton: true });
// Resetear el formulario y los campos dinámicos
form.reset();
numAdults.value = 1;
numChildren.value = 0;
renderPeopleFields();
} else {
const err = await res.text();
Swal.fire({ icon: 'error', title: 'Error al enviar', text: err });
}
} catch (err) {
Swal.fire({ icon: 'error', title: 'Error de red', text: err.message });
}
};
function collectPersonData(data, idx, type, family, familyRepresentative) {
const prefix = `${type}_${idx}_`;
// Días de alojamiento: checkboxes
const lodgingDays = [];
document.querySelectorAll(`[name='${prefix}lodgingDays']:checked`).forEach(cb => lodgingDays.push(cb.value));
let daysEvent = '';
if (lodgingDays.length === LODGING_DAYS.length) daysEvent = 'ALL_DAYS';
else daysEvent = 'SINGLE_DAYS';
let cabinGuestType = '';
if (type === 'adult') cabinGuestType = idx === 0 ? 'REPRESENTATIVE' : 'COMPANION';
else cabinGuestType = 'CHILD_CABIN';
// Lógica de productos
const products = [];
// Producto de alojamiento (CABIN)
const productoAlojamiento = productosAlojamiento.find(p => p.code === 'CABIN');
if (productoAlojamiento) {
products.push({
productId: productoAlojamiento.id,
productCode: productoAlojamiento.code,
price: productoAlojamiento.price
});
}
// Agregar producto de bus si se selecciona
const busTrip = data.get(prefix + 'busTrip') === 'true';
if (busTrip) {
const churchValue = data.get(prefix + 'church');
let busProductCode = null;
// Determinar el código del producto de bus según la iglesia
if (['APR_MURCIA', 'APR_CARTAGENA', 'APR_MOLINA', 'APR_ALCANTARILLA', 'APR_VEGA_BAJA', 'APR_ALICANTE'].includes(churchValue)) {
busProductCode = 'BUS_MURCIA';
} else if (['APR_LORCA', 'APR_AGUILAS', 'APR_VERA', 'APR_HUERCAL'].includes(churchValue)) {
busProductCode = 'BUS_LORCA';
}
// Para APR_GRANADA y OTRA_IGLESIA no se añade producto de bus
if (busProductCode) {
const productoBus = productosAlojamiento.find(p => p.code === busProductCode);
if (productoBus) {
products.push({
productId: productoBus.id,
productCode: productoBus.code,
price: productoBus.price
});
}
}
}
return {
formId: '',
name: data.get(prefix + 'name') || '',
surname: data.get(prefix + 'surname') || '',
age: parseInt(data.get(prefix + 'age'), 10) || 0,
phone: data.get(prefix + 'phone') || '',
email: data.get(prefix + 'email') || '',
dni: data.get(prefix + 'dni') || '',
city: data.get(prefix + 'city') || '',
church: data.get(prefix + 'church') || '',
otherChurch: data.get(prefix + 'otherChurch') || '',
pastorName: data.get(prefix + 'pastorName') || '',
pastorPhone: data.get(prefix + 'pastorPhone') || '',
daysEvent,
accommodation: 'CABIN',
busTrip: busTrip,
lactoseIntolerant: data.get(prefix + 'lactoseIntolerant') === 'true',
celiac: data.get(prefix + 'celiac') === 'true',
diabetic: data.get(prefix + 'diabetic') === 'true',
diseaseOrAllergies: data.get(prefix + 'diseaseOrAllergies') || '',
userNotes: data.get(prefix + 'userNotes') || '',
lodgingDays,
products: products,
family,
familyRepresentative: (type === 'adult' && idx === 0),
cabinGuestType
};
}
// Función para cargar productos de alojamiento
async function fetchProductosAlojamiento() {
try {
const res = await fetch(`${API_ENDPOINT}/products/by-form/${FORM_ID}`);
if (!res.ok) throw new Error('No se pudieron cargar los productos');
const productos = await res.json();
productosAlojamiento = productos;
} catch (err) {
console.error('Error al cargar productos:', err);
}
}
// Responsive CSS
const style = document.createElement('style');
style.innerHTML = `
@media (max-width: 700px) {
.container { padding: 10px 2vw; }
.form-row { flex-direction: column; gap: 0; }
.person-section { padding: 12px 4px; }
}
`;
document.head.appendChild(style);
});