/** * Product Page Elegant Design * JavaScript للتصميم الأنيق */ (function() { 'use strict'; // ============================================ // Additional Images Navigation // ============================================ function initAdditionalImagesNav() { const container = document.querySelector('.additional-images-row'); const prevBtn = document.querySelector('.additional-images-nav.prev'); const nextBtn = document.querySelector('.additional-images-nav.next'); const items = document.querySelectorAll('.additional-image-item'); if (!container || !prevBtn || !nextBtn) return; const scrollAmount = 100; // مقدار التمرير // التمرير للأمام nextBtn.addEventListener('click', () => { container.scrollBy({ left: -scrollAmount, behavior: 'smooth' }); }); // التمرير للخلف prevBtn.addEventListener('click', () => { container.scrollBy({ left: scrollAmount, behavior: 'smooth' }); }); // تحديث حالة الأزرار function updateNavButtons() { const scrollLeft = container.scrollLeft; const maxScroll = container.scrollWidth - container.clientWidth; // في RTL، scrollLeft يكون سالب const isAtStart = Math.abs(scrollLeft) < 10; const isAtEnd = Math.abs(scrollLeft) >= maxScroll - 10; prevBtn.disabled = isAtEnd; nextBtn.disabled = isAtStart; } container.addEventListener('scroll', updateNavButtons); updateNavButtons(); // النقر على الصورة لتغيير الصورة الرئيسية items.forEach((item, index) => { item.addEventListener('click', function() { // إزالة active من الكل items.forEach(i => i.classList.remove('active')); // إضافة active للصورة المختارة this.classList.add('active'); // تغيير الصورة الرئيسية const mainImage = document.querySelector('.product-main-image img'); const newImageSrc = this.querySelector('img').src; if (mainImage && newImageSrc) { mainImage.style.opacity = '0'; setTimeout(() => { mainImage.src = newImageSrc; mainImage.style.opacity = '1'; }, 200); } }); }); // تفعيل الصورة الأولى if (items.length > 0) { items[0].classList.add('active'); } } // ============================================ // Share Functions // ============================================ function initShareButtons() { const shareButtons = document.querySelectorAll('.share-icon-btn'); shareButtons.forEach(btn => { btn.addEventListener('click', function() { const type = this.dataset.shareType; const productUrl = window.location.href; const productName = document.querySelector('.product-name')?.textContent || document.title; const productImage = document.querySelector('.product-main-image img')?.src || ''; switch(type) { case 'whatsapp': shareWhatsApp(productName, productUrl); break; case 'facebook': shareFacebook(productUrl); break; case 'twitter': shareTwitter(productName, productUrl); break; case 'copy': copyLink(productUrl); break; } }); }); } function shareWhatsApp(text, url) { const message = encodeURIComponent(`${text}\n${url}`); window.open(`https://wa.me/?text=${message}`, '_blank'); } function shareFacebook(url) { window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`, '_blank', 'width=600,height=400'); } function shareTwitter(text, url) { window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`, '_blank', 'width=600,height=400'); } async function copyLink(url) { try { await navigator.clipboard.writeText(url); showToast('✓ تم نسخ الرابط!'); } catch (err) { // Fallback const input = document.createElement('input'); input.value = url; document.body.appendChild(input); input.select(); document.execCommand('copy'); document.body.removeChild(input); showToast('✓ تم نسخ الرابط!'); } } // ============================================ // Action Buttons - الأزرار الأنيقة الجديدة // ============================================ function initActionButtons() { // زر أضف للسلة (Primary) - استخدام ID لتجنب التكرار const addToCartBtn = document.getElementById('addToCartBtn'); if (addToCartBtn && !addToCartBtn.dataset.elegantInitialized) { addToCartBtn.dataset.elegantInitialized = 'true'; // إزالة أي event listeners سابقة const newBtn = addToCartBtn.cloneNode(true); addToCartBtn.parentNode.replaceChild(newBtn, addToCartBtn); newBtn.addEventListener('click', function(e) { e.preventDefault(); e.stopPropagation(); const productId = this.dataset.productId; if (!productId) { if (typeof showToast === 'function') { showToast('⚠ معرف المنتج غير صحيح'); } return; } // منع الضغط المتكرر if (this.disabled) return; // إضافة loading state this.classList.add('loading'); this.disabled = true; const originalHTML = this.innerHTML; // تغيير النص this.innerHTML = ` جاري الإضافة... `; // الحصول على الكمية const qtyInput = document.querySelector('.qty-input'); const quantity = qtyInput ? parseInt(qtyInput.value) : 1; // إضافة للسلة مباشرة fetch('../api/cart/add.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' }, body: `product_id=${productId}&quantity=${quantity}` }) .then(r => r.json()) .then(data => { if (data.success) { // Success state this.classList.remove('loading'); this.classList.add('success'); this.innerHTML = ` تمت الإضافة! `; if (typeof showToast === 'function') { showToast(`✓ تم إضافة ${quantity} قطعة للسلة بنجاح`); } // تحديث badge const badge = document.querySelector('.nav-badge'); if (badge && data.cart_count) { badge.textContent = data.cart_count; badge.style.display = 'flex'; } // العودة للحالة الأصلية setTimeout(() => { this.classList.remove('success'); this.innerHTML = originalHTML; this.disabled = false; }, 2000); } else { this.classList.remove('loading'); this.innerHTML = originalHTML; this.disabled = false; if (typeof showToast === 'function') { showToast('⚠ ' + (data.message || 'حدث خطأ')); } } }) .catch(err => { console.error('Error:', err); this.classList.remove('loading'); this.innerHTML = originalHTML; this.disabled = false; if (typeof showToast === 'function') { showToast('❌ حدث خطأ في الاتصال'); } }); }); } // زر اشتري الآن (Secondary) const buyNowBtn = document.getElementById('buyNowBtn'); if (buyNowBtn && !buyNowBtn.dataset.elegantInitialized) { buyNowBtn.dataset.elegantInitialized = 'true'; // إزالة أي event listeners سابقة const newBtn = buyNowBtn.cloneNode(true); buyNowBtn.parentNode.replaceChild(newBtn, buyNowBtn); newBtn.addEventListener('click', function(e) { e.preventDefault(); e.stopPropagation(); const productId = this.dataset.productId; if (!productId) { if (typeof showToast === 'function') { showToast('⚠ معرف المنتج غير صحيح'); } return; } // منع الضغط المتكرر if (this.disabled) return; // إضافة loading state this.classList.add('loading'); this.disabled = true; // الحصول على الكمية const qtyInput = document.querySelector('.qty-input'); const quantity = qtyInput ? parseInt(qtyInput.value) : 1; // إضافة للسلة والانتقال fetch('../api/cart/add.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' }, body: `product_id=${productId}&quantity=${quantity}` }) .then(r => r.json()) .then(data => { if (data.success) { if (typeof showToast === 'function') { showToast('✓ جاري الانتقال للدفع...'); } setTimeout(() => { window.location.href = 'cart.php'; }, 800); } else { this.classList.remove('loading'); this.disabled = false; if (typeof showToast === 'function') { showToast('⚠ ' + (data.message || 'حدث خطأ')); } } }) .catch(err => { console.error('Error:', err); this.classList.remove('loading'); this.disabled = false; if (typeof showToast === 'function') { showToast('❌ حدث خطأ في الاتصال'); } }); }); } // زر المفضلة (Wishlist) const wishlistBtn = document.getElementById('wishlistBtn'); if (wishlistBtn && !wishlistBtn.dataset.elegantInitialized) { wishlistBtn.dataset.elegantInitialized = 'true'; // إزالة أي event listeners سابقة const newBtn = wishlistBtn.cloneNode(true); wishlistBtn.parentNode.replaceChild(newBtn, wishlistBtn); newBtn.addEventListener('click', function(e) { e.preventDefault(); e.stopPropagation(); const productId = this.dataset.productId; if (!productId) { if (typeof showToast === 'function') { showToast('⚠ معرف المنتج غير صحيح'); } return; } // تبديل الحالة مع animation this.classList.toggle('active'); // إضافة pulse effect this.style.animation = 'pulse 0.3s ease-in-out'; setTimeout(() => { this.style.animation = ''; }, 300); // استدعاء API fetch('../api/wishlist/toggle.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' }, body: `product_id=${productId}` }) .then(r => r.json()) .then(data => { if (data.success) { if (typeof showToast === 'function') { showToast('💜 ' + data.message); } } else { if (typeof showToast === 'function') { showToast('⚠ ' + (data.message || 'حدث خطأ')); } } }) .catch(err => { console.error('Error:', err); if (typeof showToast === 'function') { showToast('❌ حدث خطأ في الاتصال'); } }); }); } } // ============================================ // Pulse Animation // ============================================ const style = document.createElement('style'); style.textContent = ` @keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.1); } } `; document.head.appendChild(style); // ============================================ // Toast Notification // ============================================ function showToast(message, duration = 3000) { let toast = document.getElementById('elegant-toast'); if (!toast) { toast = document.createElement('div'); toast.id = 'elegant-toast'; toast.style.cssText = ` position: fixed; top: 20px; right: 20px; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); color: white; padding: 16px 24px; border-radius: 12px; box-shadow: 0 8px 24px rgba(229, 115, 147, 0.4); z-index: 9999; font-weight: 600; font-size: 16px; opacity: 0; transition: opacity 0.3s; `; document.body.appendChild(toast); } toast.textContent = message; toast.style.opacity = '1'; setTimeout(() => { toast.style.opacity = '0'; }, duration); } // Make showToast global if not already defined if (typeof window.showToast !== 'function') { window.showToast = showToast; } // ============================================ // Initialize // ============================================ function init() { initAdditionalImagesNav(); initShareButtons(); initActionButtons(); console.log('✓ Elegant Design initialized'); } // Run on DOM ready if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();