Files
mediglobe/assets/js/cart.js
T
2026-03-02 13:22:47 +05:30

111 lines
2.3 KiB
JavaScript

const Cart = (function () {
const STORAGE_KEY = "cart";
const TAX_RATE = 0.05;
let couponDiscount = 0;
// ─────────────────────────────
// Internal
// ─────────────────────────────
function getCart() {
return JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
}
function saveCart(cart) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(cart));
window.dispatchEvent(new Event("cartUpdated"));
}
function findItem(cart, id) {
return cart.find((item) => item.id === id);
}
// ─────────────────────────────
// Public API
// ─────────────────────────────
function addItem(product, quantity = 1) {
const cart = getCart();
const existing = findItem(cart, product.id);
if (existing) {
existing.quantity += quantity;
} else {
cart.push({
id: product.id,
name: product.basic.name,
price: product.pricing.price,
image: product.media.mainImage,
quantity,
});
}
saveCart(cart);
}
function removeItem(id) {
const cart = getCart().filter((item) => item.id !== id);
saveCart(cart);
}
function updateQuantity(id, quantity) {
const cart = getCart();
const item = findItem(cart, id);
if (!item) return;
item.quantity = Math.max(1, quantity);
saveCart(cart);
}
function clear() {
localStorage.removeItem(STORAGE_KEY);
window.dispatchEvent(new Event("cartUpdated"));
}
function applyCoupon(code) {
if (code === "MEDI10") {
couponDiscount = 0.1;
window.dispatchEvent(new Event("cartUpdated"));
return true;
}
couponDiscount = 0;
window.dispatchEvent(new Event("cartUpdated"));
return false;
}
function getTotals() {
const cart = getCart();
const subtotal = cart.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
const tax = subtotal * TAX_RATE;
const discount = subtotal * couponDiscount;
const total = subtotal - discount;
return {
subtotal,
tax,
discount,
total,
};
}
function getTotalCount() {
return getCart().reduce((sum, item) => sum + item.quantity, 0);
}
return {
getCart,
addItem,
removeItem,
updateQuantity,
clear,
applyCoupon,
getTotals,
getTotalCount,
};
})();