document.addEventListener("DOMContentLoaded", () => { fetchCart(); const myOffcanvas = document.getElementById('side-cart'); myOffcanvas.addEventListener('hidden.bs.offcanvas', () => { $('.item-inside-cart').html(''); $('.loading-cart').removeClass('d-none'); $('.footer-side-cart').addClass('d-none'); }); myOffcanvas.addEventListener('show.bs.offcanvas', () => { $('.loading-cart').addClass('d-none'); fetchCart(); }); }); function productCartAddToCart(elm, product_id) { const $elm = $(elm); $('.loading-cart').removeClass('d-none'); const originalHtml = $elm.html(); $elm.html(`
Loading...
`); addToCart(product_id, 1, async () => { $elm.html(originalHtml); await fetchCart(); new bootstrap.Offcanvas(document.getElementById('side-cart')).show(); }); } function addToCart(product_id, quantity, onCompleted) { zid.store.cart.addProduct({ productId: product_id, quantity }).then(response => { if (response.status === 'success') { showCartPopupAfterAdd(); setCartTotalAndBadge(response.data.cart); onCompleted?.(); } }); } function setCartTotalAndBadge(cart) { setCartBadge(cart.products_count); const cartTotal = getCartTotal(cart); if (cartTotal) setCartIconTotal(cartTotal); } function setCartIconTotal(total) { $('.cart-price').html(total).removeClass('d-none'); } function setCartBadge(badge) { $('.cart-badge').html(badge); } function displayActivePaymentSessionBar(cart) { $('.payment-session-bar').toggleClass('d-none', !cart.is_reserved); } function getCartTotal(cart) { const totalItem = cart?.totals?.find(total => total.code === 'total'); return totalItem?.value_string || null; } function createCartProduct(product) { const oldPrice = product.price_before_string ? `${product.price_string}${product.price_before_string}` : `${product.price_string}`; const imageUrl = product.images[0].origin; return `
  • ${product.name}

    ${product.name}

    ${oldPrice}
  • `; } function createCartProductBundle(item) { return [...item.product_x, ...item.product_y].map(createCartProduct).join(''); } function fetchCart() { $('.loading-cart').removeClass('d-none'); $('.cart-rules').addClass('d-none'); $('#additional-cart').html(''); $('.side-cart-items').removeClass('d-none'); const emptyText = $('#side-cart').data('empty'); zid.store.cart.fetch().then(response => { if (response.status !== "success") return alert('Error Cart'); const cart = response.data.cart; let itemsHtml = ''; let totalsHtml = ''; $('.cart-count').html(cart.products_count); if (cart.products_count > 0) { cart.products.forEach(product => { itemsHtml += product.bundle_name ? createCartProductBundle(product) : createCartProduct(product); }); // cart.totals.forEach(total => { // totalsHtml += ` //
  • // ${total.title} // ${total.value_string} //
  • `; // }); // حساب إجمالي الخصم للمنتجات // حساب إجمالي الخصم للمنتجات let discountTotal = 0; cart.products.forEach(product => { if (product.price_before && product.price_before > product.price) { discountTotal += (product.price_before - product.price) * product.quantity; } }); // البحث عن خصم الكوبون أو الخصومات الأخرى let couponDiscount = 0; cart.totals.forEach(total => { if ( total.code === 'coupon' || total.code === 'discount' || total.title.toLowerCase().includes('خصم') || total.title.toLowerCase().includes('discount') ) { // إزالة أي رموز غير رقمية لتحويل القيمة لرقم let cleanValue = parseFloat(total.value_string.replace(/[^\d.-]/g, '')); couponDiscount += Math.abs(cleanValue); } }); // إجمالي كل الخصومات let totalDiscounts = discountTotal + couponDiscount; // بناء عناصر الإجماليات cart.totals.forEach(total => { if (total.code === 'total' && totalDiscounts > 0) { let currency = cart.currency?.cart_currency?.symbol || ''; totalsHtml += `
  • ${rtl_mode ? 'إجمالي الخصومات' : 'Total Discounts'} -${totalDiscounts.toFixed(2)} ${currency}
  • `; } totalsHtml += `
  • ${total.title} ${total.value_string}
  • `; }); $('#cart-side-totals').html(totalsHtml); $('.side-cart-items').html(itemsHtml); $('.footer-side-cart').removeClass('d-none'); } else { $('#additional-cart').html(`

    ${emptyText}

    `); $('#cart-side-totals, .side-cart-items').html(''); $('.footer-side-cart').addClass('d-none'); $('.cart-rules').addClass('d-none'); } setCartTotalAndBadge(cart); if (cart.products_count > 0) { let foundFreeShipping = false; if (response.data?.cart?.discount_rules?.length) { let currency = response.data.cart.currency?.cart_currency?.symbol || ''; response.data.cart.discount_rules.forEach(function(rule) { if ( rule.code === "free_shipping" && rule.enabled && response.data.cart.fee_shipping_discount_rules ) { foundFreeShipping = true; $('.cart-rules').removeClass('d-none'); templateRules(rule, response, currency, response.data.cart.fee_shipping_discount_rules); } }); } if (!foundFreeShipping) { $('.cart-rules').addClass('d-none'); } } displayActivePaymentSessionBar(cart); }).finally(() => { $('.loading-cart').addClass('d-none'); }); } const rtl_mode = $("body").hasClass("rtl"); function templateRules(rule, response, currency, fee_shipping_discount_rules) { let min_value = rule.conditions[0].value[0]; let remain_raw = min_value - response.data.cart.products_subtotal; let remain_value = remain_raw > 0 ? (Number.isInteger(remain_raw) ? remain_raw : remain_raw.toFixed(2)) : 0; let percentage = Math.ceil( fee_shipping_discount_rules.conditions_subtotal.status.code !== 'applied' ? 100 - ((remain_value * 100) / min_value) : 100 ); if (fee_shipping_discount_rules.conditions_subtotal.status.code !== 'applied') { $(".cart-rules").removeClass('d-none'); $(".cart-rules").html(`
    ${rtl_mode ? "أضف مشتريات بقيمة" : "Add products worth"} ${remain_value} ${currency} ${rtl_mode ? "للحصول على شحن مجاني 🚚" : "to get Free Shipping 🚚"}
    `); } else { $(".cart-rules").html(`
    ${rtl_mode ? "🎉 حصلت على شحن مجاني!" : "🎉 Shipping is Free Now!"}
    `); } } function removeItem(key, item) { $(`.side-cart-items li#product_${key} .remove`).html(''); zid.store.cart.removeProduct(key).then(response => { if (response.status === 'success') fetchCart(); }); } $(document).on('click', '.btn-number', function () { const type = $(this).attr('data-type'); const fieldName = $(this).attr('data-field'); const input = $(`input[name='${fieldName}']`); let currentVal = parseInt(input.val()); if (!isNaN(currentVal)) { if (type === 'plus' && currentVal < parseInt(input.attr('max'))) { input.val(currentVal + 1).change(); } else if (type === 'minus' && currentVal > parseInt(input.attr('min'))) { input.val(currentVal - 1).change(); } } }); function updateMiniCartProduct(productId, quantity) { const cartItems = $('.side-cart-items'); cartItems.fadeTo('slow', 0.3); zid.store.cart.updateProduct(productId, quantity).then(response => { cartItems.fadeTo('slow', 1); if (response.status === 'success') { fetchCart(); } else { $.toast({ text: response.data.message, showHideTransition: 'fade', allowToastClose: true, hideAfter: 2000, position: 'top-right', textAlign: 'center', bgColor: '#d90000', textColor: '#fff', }); } }); }