(function() {
var PIXEL_ID = '1257608439126364';
// Dados do GTM4WP dataLayer (usuarios logados)
function getDataLayerUser() {
if (!window.dataLayer) return null;
for (var i = dataLayer.length - 1; i >= 0; i--) {
var item = dataLayer[i];
if (item && item.customerBillingEmail) {
var d = {};
d.em = item.customerBillingEmail.toLowerCase().trim();
if (!d.em) return null;
if (item.customerBillingPhone) d.ph = item.customerBillingPhone.replace(/D/g,'');
if (item.customerBillingFirstName) d.fn = item.customerBillingFirstName.toLowerCase().trim();
if (item.customerBillingLastName) d.ln = item.customerBillingLastName.toLowerCase().trim();
if (item.customerBillingCity) d.ct = item.customerBillingCity.toLowerCase().replace(/s/g,'');
if (item.customerBillingPostcode) d.zp = item.customerBillingPostcode.trim();
return d;
}
}
return null;
}
// Dados do formulario de checkout (visitantes)
function getFormData() {
function v(id) { var e = document.getElementById(id); return e ? e.value.trim() : ''; }
var em = v('billing_email');
if (!em) return null;
var d = { em: em.toLowerCase() };
var ph = v('billing_phone'); if (ph) d.ph = ph.replace(/D/g,'');
var fn = v('billing_first_name'); if (fn) d.fn = fn.toLowerCase();
var ln = v('billing_last_name'); if (ln) d.ln = ln.toLowerCase();
var ct = v('billing_city'); if (ct) d.ct = ct.toLowerCase().replace(/s/g,'');
var zp = v('billing_postcode'); if (zp) d.zp = zp;
return d;
}
function updatePixel(data) {
if (typeof fbq !== 'undefined' && data && data.em) {
fbq('init', PIXEL_ID, data);
}
}
// 1. Usuarios logados: dados do GTM4WP dataLayer
var dlData = getDataLayerUser();
if (dlData) updatePixel(dlData);
// 2. Pagina obrigado: email exibido no pedido
var tyEmail = document.querySelector('.woocommerce-customer-details--email');
if (tyEmail) updatePixel({ em: tyEmail.textContent.trim().toLowerCase() });
// 3. Checkout: atualiza conforme usuario preenche o formulario
var checkoutEmail = document.getElementById('billing_email');
if (checkoutEmail) {
['billing_email','billing_phone','billing_first_name','billing_last_name','billing_city','billing_postcode'].forEach(function(id) {
var el = document.getElementById(id);
if (el) el.addEventListener('blur', function() { updatePixel(getFormData()); });
});
var form = document.getElementById('checkout');
if (form) form.addEventListener('submit', function() { updatePixel(getFormData()); }, true);
updatePixel(getFormData());
}
})();