// ======================================== // CART PAGE LOGIC // ======================================== let promoApplied = null; document.addEventListener('DOMContentLoaded', () => { renderCartPage(); document.getElementById('promoBtn').addEventListener('click', handlePromo); document.getElementById('promoInput').addEventListener('keydown', e => { if (e.key === 'Enter') handlePromo(); }); document.addEventListener('cartUpdated', renderCartPage); }); function renderCartPage() { const cart = getCart(); const cartContent = document.getElementById('cartContent'); const emptyCart = document.getElementById('emptyCart'); if (cart.length === 0) { cartContent.style.display = 'none'; emptyCart.style.display = 'block'; return; } cartContent.style.display = ''; emptyCart.style.display = 'none'; const itemsContainer = document.getElementById('cartItems'); itemsContainer.innerHTML = ''; cart.forEach(item => { const product = getProductById(item.productId); if (!product) return; const colorName = COLORS_MAP[item.color]?.name || item.color; const el = document.createElement('div'); el.className = 'cart-item'; el.innerHTML = `
${product.name}
${product.name}
O'lcham: ${item.size} | Rang: ${colorName}
${formatPrice(product.price)}
${item.quantity}
${formatPrice(product.price * item.quantity)}
`; itemsContainer.appendChild(el); }); // Event delegation for qty buttons and remove itemsContainer.querySelectorAll('.qty-btn').forEach(btn => { btn.addEventListener('click', () => { const { id, size, color, action } = btn.dataset; const item = cart.find(i => i.productId == id && i.size === size && i.color === color); if (!item) return; const newQty = action === 'plus' ? item.quantity + 1 : item.quantity - 1; updateCartQty(parseInt(id), size, color, newQty); }); }); itemsContainer.querySelectorAll('.cart-item-remove').forEach(btn => { btn.addEventListener('click', () => { const { id, size, color } = btn.dataset; removeFromCart(parseInt(id), size, color); showToast('O\'chirildi', 'Mahsulot savatchadan olib tashlandi', 'info'); }); }); updateSummary(); } function updateSummary() { const totals = getCartTotal(); let promoDiscount = 0; if (promoApplied && promoApplied.type === 'percent') { promoDiscount = Math.round(totals.subtotal * promoApplied.discount / 100); } document.getElementById('sumSubtotal').textContent = formatPrice(totals.subtotal); document.getElementById('sumDiscount').textContent = totals.discount + promoDiscount > 0 ? '-' + formatPrice(totals.discount + promoDiscount) : '0 so\'m'; document.getElementById('sumTotal').textContent = formatPrice(totals.total - promoDiscount); } function handlePromo() { const code = document.getElementById('promoInput').value.trim(); if (!code) return; const result = applyPromo(code); const msg = document.getElementById('promoMsg'); if (result.valid) { promoApplied = result; msg.innerHTML = `✓ ${result.desc} qo'llanildi`; updateSummary(); } else { msg.innerHTML = `✗ ${result.message}`; } }