(function(){ function getCsrfToken() { return document.querySelector('meta[name="csrf-token"]')?.content || null; } // Fetch live price async function fetchLivePrice(sku, placeholderEl) { try { placeholderEl.innerHTML = 'Loading '; const res = await fetch('/ajax/live-pricing', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': getCsrfToken() }, credentials: 'include', body: JSON.stringify({ products: [{ sku: sku, qty: 1, pack: "1", pack_uom: "1", template_item: "", vendor_code: "" }] }) }); if (!res.ok) throw new Error("Price fetch failed"); const data = await res.json(); if (data?.status === "success" && data.data?.[0]?.price != null) { placeholderEl.textContent = "£" + Number(data.data[0].price).toFixed(2); } else { placeholderEl.textContent = "Call for price"; } } catch (err) { console.error("fetchLivePrice error:", err); placeholderEl.textContent = "Call for price"; } } // Add-to-cart logic async function addToCart(button) { const csrfToken = getCsrfToken(); if (!csrfToken) { console.error("CSRF token not found"); return; } const product = { item_id: parseInt(button.dataset.itemId, 10), item_sku: button.dataset.itemSku, item_catalog_id: parseInt(button.dataset.itemCatalogId, 10), item_catalog_item_id: parseInt(button.dataset.itemCatalogItemId, 10), item_supplier_id: parseInt(button.dataset.itemSupplierId, 10), }; const payload = new URLSearchParams(); payload.set("product", JSON.stringify(product)); payload.set("qty", "1"); const originalText = button.textContent; button.textContent = "Adding…"; button.disabled = true; try { const res = await fetch("/cart/addcart", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "X-CSRF-TOKEN": csrfToken, "X-Requested-With": "XMLHttpRequest" }, body: payload.toString(), credentials: "include" }); if (res.ok) { sessionStorage.setItem("cartAddedMessage", "success"); button.textContent = "Added ✓"; // ✅ Only reload if NOT on the /cart page if (location.pathname.replace(/\/+$/, '') !== '/cart') { setTimeout(() => window.location.reload(), 400); } } else { console.error("Add to basket failed:", await res.text()); button.textContent = "Error ✗"; setTimeout(() => { button.textContent = originalText; button.disabled = false; }, 2000); } } catch (err) { console.error("Request error:", err); button.textContent = "Error ✗"; setTimeout(() => { button.textContent = originalText; button.disabled = false; }, 2000); } } // Attach button logic document.querySelectorAll(".paratus-add-to-cart-btn").forEach(btn => { btn.addEventListener("click", () => addToCart(btn)); const pricePlaceholder = btn.closest(".promo-margin")?.querySelector(".price-placeholder"); if (pricePlaceholder) { fetchLivePrice(btn.dataset.itemSku, pricePlaceholder); } }); // Success message after reload window.addEventListener("DOMContentLoaded", () => { const msg = sessionStorage.getItem("cartAddedMessage"); if (msg === "success") { const notice = document.createElement("div"); notice.innerHTML = ` This offer has been added to your cart! `; document.querySelectorAll(".paratus-add-to-cart-btn").forEach(btn => { btn.insertAdjacentElement("afterend", notice.cloneNode(true)); }); sessionStorage.removeItem("cartAddedMessage"); } }); })();