`;
container.insertAdjacentHTML('beforeend', html);
}
function removeRow(id) {
const rows = document.querySelectorAll('.item-row');
if(rows.length > 1) {
document.getElementById(`row-${id}`).remove();
render();
}
}
function toggleShipping() {
const select = document.getElementById('shippingType');
const input = document.getElementById('shippingCost');
input.style.display = select.value === 'paid' ? 'block' : 'none';
if(select.value === '0') input.value = 0;
render();
}
function render() {
// Datos básicos
const name = document.getElementById('clientName').value || "Consumidor Final";
const phone = document.getElementById('clientPhone').value || "--";
const method = document.getElementById('paymentMethod').value;
document.getElementById('p-client').innerText = name;
document.getElementById('p-phone').innerText = phone;
document.getElementById('p-method').innerText = method;
// Items y Cálculos
let subtotal = 0;
const itemsHtml = [];
const names = document.querySelectorAll('.i-name');
const prices = document.querySelectorAll('.i-price');
names.forEach((el, i) => {
const val = parseFloat(prices[i].value) || 0;
if(el.value || val > 0) {
subtotal += val;
itemsHtml.push(`
| ${el.value || 'Art.'} | L. ${val.toLocaleString()} |
`);
}
});
const shipping = parseFloat(document.getElementById('shippingCost').value) || 0;
const total = subtotal + shipping;
document.getElementById('p-items').innerHTML = itemsHtml.join('');
document.getElementById('p-subtotal').innerText = `L. ${subtotal.toLocaleString()}`;
document.getElementById('p-shipping').innerText = shipping > 0 ? `L. ${shipping.toLocaleString()}` : "Gratis";
document.getElementById('p-total').innerText = `L. ${total.toLocaleString()}`;
// WhatsApp link
const waBtn = document.getElementById('waBtn');
if(phone.length >= 8) {
const cleanPhone = phone.replace(/\D/g,'');
waBtn.href = `https://wa.me/504${cleanPhone}?text=Hola ${name}, adjunto recibo de su compra en Muebles Toledos.`;
waBtn.style.display = 'inline-flex';
} else {
waBtn.style.display = 'none';
}
}
async function downloadInvoice() {
const btn = document.querySelector('.btn-primary');
btn.innerText = "Procesando...";
const capture = document.getElementById('invoice-capture');
const canvas = await html2canvas(capture, { scale: 3, backgroundColor: '#ffffff' });
const link = document.createElement('a');
link.download = `Recibo_${document.getElementById('clientName').value || 'Cliente'}.png`;
link.href = canvas.toDataURL("image/png");
link.click();
btn.innerHTML = '
DESCARGAR IMAGEN';
}
// Fila inicial
addItemRow();