Registrierung

Regisztrálj most, hogy hozzászólhass a bejegyzésekhez, saját emlékeket tölts fel vagy emlékoldalt hozz létre.
ODER
Registrierung checkout let lastCartQty = null; let lastCartUnitPriceText = null; // Store complete product information to persist across pages let currentProduct = { id: null, name: null, price: null, // Store as numeric value (e.g., 15, not "15 Ft") image: null, color: null }; // Expose variables globally for access by other scripts (e.g., card form fallback) window.currentProduct = currentProduct; window.lastCartQty = lastCartQty; // Helper function to format price for display function formatPrice(numericPrice) { if (!numericPrice) return ''; var num = parseFloat(numericPrice); if (isNaN(num)) return numericPrice; // Return as-is if not a number return num + ' Ft'; } window.formatPrice = formatPrice; // Expose formatPrice function globally const popupOverlay = document.getElementById('shop-popup-overlay'); const popupBody = document.getElementById('shop-popup-body'); const closeButton = document.querySelector('.shop-popup-close'); // ===== STRIPE PAYMENT INTEGRATION ===== let stripe = null; let cardNumberElement = null; let cardExpiryElement = null; let cardCvcElement = null; let stripeInitialized = false; function initializeStripe() { console.log('🔄 Main JS: Initializing Stripe with separate elements...'); // Check if Stripe is already initialized and working if (stripeInitialized && window.stripe && document.querySelector('#card-number-element iframe')) { console.log('✅ Stripe already initialized and mounted'); return; } try { // Initialize Stripe with public key if (!window.stripe) { window.stripe = Stripe('pk_live_51RuoWpJUu8SJ5OqPlmaijasjJwRej6o0rk6NY4Fj1tjTM7ckN9xtYjwKmlR9vj67wThGGI5AJhWpTPptAmoHupOC00gAyXWkUQ'); window.appStripe = window.stripe; // Ensure global reference console.log('✅ Stripe instance created'); } // Check if we're on the card form page const cardFormContainer = document.querySelector('.card-form-popup-container'); if (!cardFormContainer) { console.log('ℹ️ Not on card form page, skipping card elements initialization'); return; } // Verify container elements exist const cardNumberDiv = document.getElementById('card-number-element'); const cardExpiryDiv = document.getElementById('card-expiry-element'); const cardCvcDiv = document.getElementById('card-cvc-element'); if (!cardNumberDiv || !cardExpiryDiv || !cardCvcDiv) { console.error('❌ Card element containers not found:', { cardNumber: !!cardNumberDiv, cardExpiry: !!cardExpiryDiv, cardCvc: !!cardCvcDiv }); // Retry initialization after a short delay to ensure DOM is ready setTimeout(initializeStripe, 100); return; } // Initialize card elements initializeCardElements(); } catch (error) { console.error('❌ Stripe initialization failed:', error); showStripeError('Failed to initialize payment system. Please try again.'); } } function initializeCardElements() { console.log('💳 Main JS: Initializing separate card elements...'); // Verify containers const cardNumberDiv = document.getElementById('card-number-element'); const cardExpiryDiv = document.getElementById('card-expiry-element'); const cardCvcDiv = document.getElementById('card-cvc-element'); if (!cardNumberDiv || !cardExpiryDiv || !cardCvcDiv) { console.error('❌ Card element containers not found'); showStripeError('Card input fields are missing. Please reload the page.'); return; } try { // Clean up existing elements cleanupCardElements(); const elements = window.stripe.elements(); const elementStyles = { base: { fontSize: '16px', color: '#32325d', fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', '::placeholder': { color: '#aab7c4' }, ':focus': { borderColor: '#007bff' } } }; // Create and mount individual card elements window.cardNumberElement = elements.create('cardNumber', { style: elementStyles, placeholder: '1234 1234 1234 1234' }); window.cardExpiryElement = elements.create('cardExpiry', { style: elementStyles, placeholder: 'MM/YY' }); window.cardCvcElement = elements.create('cardCvc', { style: elementStyles, placeholder: '123' }); // Mount elements window.cardNumberElement.mount('#card-number-element'); window.cardExpiryElement.mount('#card-expiry-element'); window.cardCvcElement.mount('#card-cvc-element'); // Add event listeners for validation setupElementEventListeners(); stripeInitialized = true; console.log('✅ All card elements initialized and mounted'); // Verify mounting setTimeout(() => { if (!document.querySelector('#card-number-element iframe')) { console.error('❌ Card number element not mounted'); showStripeError('Payment fields failed to load. Please try again.'); } }, 500); } catch (error) { console.error('❌ Card elements initialization failed:', error); // showStripeError('Failed to load payment fields. Please reload the page.'); } } function setupElementEventListeners() { const errorElement = document.getElementById('card-errors'); // Listen for changes on all elements [cardNumberElement, cardExpiryElement, cardCvcElement].forEach(element => { element.on('change', function(event) { if (event.error) { showStripeError(event.error.message); } else { hideStripeError(); } // Additional validation for specific elements if (event.elementType === 'cardNumber') { handleCardNumberChange(event); } }); }); } function handleCardNumberChange(event) { // You can add card brand detection here if needed if (event.brand) { console.log('Card brand detected:', event.brand); // You can update UI based on card brand if needed } } function showStripeError(message) { const errorElement = document.getElementById('card-errors'); if (errorElement) { errorElement.textContent = message; errorElement.style.display = 'block'; } } function hideStripeError() { const errorElement = document.getElementById('card-errors'); if (errorElement) { errorElement.style.display = 'none'; errorElement.textContent = ''; } } function cleanupCardElements() { console.log('🧹 Cleaning up card elements...'); const elements = [window.cardNumberElement, window.cardExpiryElement, window.cardCvcElement]; elements.forEach(element => { if (element && typeof element.destroy === 'function') { try { element.destroy(); } catch (e) { console.warn('⚠️ Error destroying element:', e); } } }); // Clear global references window.cardNumberElement = null; window.cardExpiryElement = null; window.cardCvcElement = null; stripeInitialized = false; // Clear container contents ['card-number-element', 'card-expiry-element', 'card-cvc-element'].forEach(id => { const container = document.getElementById(id); if (container) { container.innerHTML = ''; } }); console.log('✅ Card elements cleaned up'); } // Enhanced payment system readiness check function checkPaymentSystemReady() { const stripeReady = typeof window.appStripe !== 'undefined'; const cardElementReady = ( typeof window.cardNumberElement !== 'undefined' && typeof window.cardExpiryElement !== 'undefined' && typeof window.cardCvcElement !== 'undefined' && window.cardNumberElement._componentName === 'cardNumber' && window.cardExpiryElement._componentName === 'cardExpiry' && window.cardCvcElement._componentName === 'cardCvc' ); console.log('🔍 Payment system check:', { stripeReady: stripeReady, cardElementReady: cardElementReady }); return stripeReady && cardElementReady; } // Enhanced card save handler async function handleCardSave() { console.log('💳 Handling card save with separate elements...'); const cardholderName = document.getElementById('cardholder-name'); const saveButton = document.getElementById('save-card-button'); // Validate inputs if (!cardholderName || !cardholderName.value.trim()) { showStripeError('Please enter the cardholder name'); return false; } if (!window.cardNumberElement || !window.cardExpiryElement || !window.cardCvcElement) { showStripeError('Card input fields not properly initialized'); console.error('❌ Card elements missing:', { cardNumber: !!window.cardNumberElement, cardExpiry: !!window.cardExpiryElement, cardCvc: !!window.cardCvcElement }); return false; } // Show loading state if (saveButton) { saveButton.innerHTML = ' Feldolgozás...'; saveButton.disabled = true; } try { console.log('🔄 Creating payment method...'); const stripeInstance = window.stripe || window.appStripe; if (!stripeInstance) { throw new Error('Stripe instance not initialized'); } // Create payment method const { paymentMethod, error } = await stripeInstance.createPaymentMethod({ type: 'card', card: window.cardNumberElement, billing_details: { name: cardholderName.value.trim() } }); if (error) { throw new Error(error.message); } console.log('✅ Payment method created:', paymentMethod.id); // Send to server const response = await fetch('/hu-en/products/payment/popup-save-card', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, body: JSON.stringify({ payment_method_id: paymentMethod.id, cardholder_name: cardholderName.value.trim(), card_info: { brand: paymentMethod.card.brand, last4: paymentMethod.card.last4, exp_month: paymentMethod.card.exp_month, exp_year: paymentMethod.card.exp_year } }) }); console.log('📡 Server response status:', response.status); const result = await response.json(); // Parse JSON directly if (result.success) { console.log('✅ Card saved successfully:', result); alert('✅ Card saved successfully!'); sessionStorage.setItem('savedCard', JSON.stringify({ id: result.card?.id, brand: result.card?.brand, last4: result.card?.last4, exp_month: result.card?.exp_month, exp_year: result.card?.exp_year, cardholder_name: cardholderName.value.trim() })); // Navigate back to checkout after successful save if (window.PopupNav && window.PopupNav.canBack()) { window.PopupNav.back(); } else { window.returnToCheckout(); } } else { throw new Error(result.error || 'Card save failed'); } } catch (error) { console.error('❌ Error saving card:', error); showStripeError(error.message || 'Failed to save card. Please try again.'); } finally { // Reset button state if (saveButton) { saveButton.innerHTML = 'Kártya mentése'; saveButton.disabled = false; } } return false; } // Initialize Stripe when DOM is ready console.log('🏠 DOM Content Loaded - Initializing Stripe'); initializeStripe(); // ===== END STRIPE PAYMENT INTEGRATION ===== // Delegated: color option selection inside product cards + swap image document.addEventListener('click', function(e) { var optionEl = e.target.closest('.color-option'); if (!optionEl) return; var group = optionEl.parentElement; if (!group || !group.classList.contains('color-options')) return; // Avoid triggering parent card click / default behaviors e.preventDefault(); e.stopPropagation(); // Toggle selection within this group only var siblings = group.querySelectorAll('.color-option'); siblings.forEach(function(sib) { sib.classList.remove('selected'); }); optionEl.classList.add('selected'); var newSrc = optionEl.getAttribute('data-image-src'); // Check if we're in PRODUCT LIST var productItem = optionEl.closest('.popup-product-item'); if (productItem) { var img = productItem.querySelector('.product-image'); if (img && newSrc && img.getAttribute('src') !== newSrc) { img.setAttribute('src', newSrc); } } // Check if we're in PRODUCT DETAIL PAGE var productDetail = optionEl.closest('.product-details-container'); if (productDetail) { var mainImg = document.querySelector('.main-product-image'); if (mainImg && newSrc) { mainImg.setAttribute('src', newSrc); console.log('🖼️ Updated product detail image'); } } }); // Safety: stop propagation when clicking anywhere inside the color-options group (including gaps) document.addEventListener('click', function(e) { var groupClick = e.target.closest('.color-options'); if (!groupClick) return; e.preventDefault(); e.stopPropagation(); }); // Add event delegation for card save button document.addEventListener('click', function(e) { // Handle card save button if (e.target.closest('.save-card-btn')) { e.preventDefault(); // Check if payment system is ready if (!checkPaymentSystemReady()) { showError('Payment system not ready. Please wait for initialization.'); console.error('Payment system not ready when button clicked'); return; } handleCardSave(); return; } }); function showError(error) { const errorDiv = document.getElementById('card-errors'); if (errorDiv) { errorDiv.style.display = 'block'; errorDiv.textContent = error.message || 'An error occurred'; } console.error('Stripe Error:', error); } function showSuccess(message) { console.log('✅ SUCCESS:', message); showError(message, 'success'); } // Function to open popup function openPopup() { if (isPopupOpen) return; // Check if profile was just set by candle button (within last 500ms) let shouldKeepProfile = false; try { const timestamp = sessionStorage.getItem('profileSetTimestamp'); if (timestamp) { const elapsed = Date.now() - parseInt(timestamp); shouldKeepProfile = elapsed < 500; // Keep profile if set within last 500ms if (shouldKeepProfile) { console.log('🕯️ Keeping profile from candle button (set ' + elapsed + 'ms ago)'); } } } catch (_) {} // Clear profile selection ONLY if not from candle button if (!shouldKeepProfile) { try { sessionStorage.removeItem('selectedProfile'); console.log('🗑️ Cleared profile selection on shop open'); } catch (_) {} // Clear shopDataPopup global object if (typeof shopDataPopup !== 'undefined') { shopDataPopup.selectedProfileId = null; shopDataPopup.recipientName = null; shopDataPopup.profileImage = null; shopDataPopup.meta = null; console.log('🗑️ Cleared shopDataPopup on shop open'); } } isPopupOpen = true; popupOverlay.style.display = 'flex'; document.body.style.overflow = 'hidden'; // iOS specific: Prevent body scroll and fix viewport document.body.style.position = 'fixed'; document.body.style.width = '100%'; document.body.style.height = '100%'; // Recalculate viewport height when popup opens (important for iOS) setTimeout(function() { const vh = window.innerHeight * 0.01; document.documentElement.style.setProperty('--popup-vh', `${vh}px`); document.documentElement.style.setProperty('--window-inner-height', `${window.innerHeight}px`); }, 50); fetch('/nk-de/products/product/popup', { headers: { 'X-Requested-With': 'XMLHttpRequest' } }) .then(response => { console.log('Response status:', response.status, response.statusText); if (!response.ok) { // Try to get the error response text return response.text().then(errorText => { throw new Error(`HTTP ${response.status}: ${errorText.substring(0, 200)}`); }); } return response.text(); }) .then(html => { console.log('Success - HTML length:', html.length); // Use PopupNav.resetWith for initial popup load (product list) if (window.PopupNav) { window.PopupNav.resetWith(html, function(currentView) { console.log('🔧 Popup.php: Running post-load initialization'); // Check if profile is selected and set visibility immediately // First check shopDataPopup (set by candle button), then sessionStorage var hasProfile = shopDataPopup && shopDataPopup.selectedProfileId; var hasSelectedProfile = sessionStorage.getItem('selectedProfile'); if (hasProfile || hasSelectedProfile) { try { var data = hasProfile ? shopDataPopup : JSON.parse(hasSelectedProfile); // Update shopDataPopup if we got data from sessionStorage if (!hasProfile && hasSelectedProfile) { shopDataPopup.selectedProfileId = data.id; shopDataPopup.recipientName = data.name; shopDataPopup.profileImage = data.image; shopDataPopup.meta = data.meta; } var searchBar = currentView.querySelector('#searchBarContainer'); var profileCard = currentView.querySelector('#profileCard'); if (searchBar) searchBar.style.display = 'none'; if (profileCard) { var nameEl = profileCard.querySelector('.profile-name'); var dateEl = profileCard.querySelector('.profile-date'); var imageEl = profileCard.querySelector('.profile-image'); if (nameEl) nameEl.textContent = shopDataPopup.recipientName || data.name || ''; if (dateEl) dateEl.textContent = shopDataPopup.meta || data.meta || ''; // Set image - this was missing! if (imageEl) { var imageUrl = shopDataPopup.profileImage || data.image || ''; console.log('🖼️ _popup_shop.php: Image element found:', imageEl); console.log('🖼️ _popup_shop.php: Image URL to set:', imageUrl); if (imageUrl) { imageEl.src = imageUrl; imageEl.alt = shopDataPopup.recipientName || data.name || 'Profile'; // Force reload by adding timestamp imageEl.onload = function() { console.log('✅ Image loaded successfully:', imageUrl); }; imageEl.onerror = function() { console.error('❌ Image failed to load:', imageUrl); imageEl.src = '/img/cover-user-new.png'; }; console.log('🖼️ _popup_shop.php: Image src set to:', imageEl.src); } else { imageEl.src = '/img/cover-user-new.png'; imageEl.alt = 'Profile'; console.log('🖼️ _popup_shop.php: Using default image'); } } else { console.error('❌ Image element not found!'); } profileCard.style.display = 'flex'; } // Also call applySelectedProfileToDetail to ensure everything is set if (typeof applySelectedProfileToDetail === 'function') { setTimeout(applySelectedProfileToDetail, 50); } console.log('✅ Popup.php: Profile card shown with image:', shopDataPopup.profileImage || data.image); } catch (e) { console.warn('Failed to apply profile on popup.php load:', e); } } }); } else { popupBody.innerHTML = html; } // Reset search initializer state for fresh DOM window.popupSearchInitialized = false; // Apply profile data after content loads (for initial popup load) if (typeof applySelectedProfileToDetail === 'function') { setTimeout(function() { applySelectedProfileToDetail(); console.log('🔄 Applied profile after popup content load'); }, 100); } if (typeof window.setupCategoryButtons === 'function') { window.setupCategoryButtons(); } // Setup search functionality if (typeof window.setupPopupSearch === 'function') { // Get current view for initial popup load var currentView = popupBody.querySelector('.popup-view:not(.hidden)') || popupBody; window.setupPopupSearch(currentView); } // Auto-select first color option for each product if (typeof window.autoSelectFirstColorOption === 'function') { setTimeout(function() { window.autoSelectFirstColorOption(); }, 100); } }) .catch(error => { console.error('Popup Error Details:', error); popupBody.innerHTML = `
Server Error

Could not load products. Please try again.

Error: ${error.message}
`; }); } // Function to close popup window.closePopup = function() { if (!isPopupOpen) return; isPopupOpen = false; popupOverlay.style.display = 'none'; document.body.style.overflow = ''; // Restore scrolling // iOS specific: Restore body styles document.body.style.position = ''; document.body.style.width = ''; document.body.style.height = ''; // Clear PopupNav stack when closing popup if (window.PopupNav && typeof window.PopupNav.clear === 'function') { window.PopupNav.clear(); } // Reset category ID to 0 when popup is closed sessionStorage.setItem("category_id", JSON.stringify({ selected_category_id: 0 })); // Reset cart quantity to 1 when popup is closed try { sessionStorage.setItem("cartQuantity", "1"); } catch (_) {} // ✅ Clear profile selection when shop closes try { sessionStorage.removeItem("selectedProfile"); console.log('🗑️ Cleared profile selection on shop close'); } catch (_) {} // Clear shopDataPopup global object if (typeof shopDataPopup !== 'undefined') { shopDataPopup.selectedProfileId = null; shopDataPopup.recipientName = null; shopDataPopup.profileImage = null; shopDataPopup.meta = null; console.log('🗑️ Cleared shopDataPopup on shop close'); } // Dispatch custom shop closed event for candles refresh console.log('🏪 Shop popup closed - dispatching shopClosed event'); const shopClosedEvent = new CustomEvent('shopClosed', { bubbles: true, detail: { timestamp: Date.now() } }); document.dispatchEvent(shopClosedEvent); } // ✅ Clear profile selection on page refresh/unload window.addEventListener('beforeunload', function() { try { sessionStorage.removeItem('selectedProfile'); console.log('🔄 Cleared profile selection on page refresh/close'); } catch (_) {} // Clear shopDataPopup global object if (typeof shopDataPopup !== 'undefined') { shopDataPopup.selectedProfileId = null; shopDataPopup.recipientName = null; shopDataPopup.profileImage = null; shopDataPopup.meta = null; } }); // Event listeners for open buttons document.addEventListener('click', function(e) { if (e.target.closest('.open-shop-popup') || e.target.closest('.shop')) { e.preventDefault(); openPopup(); } }); // Close buttons (handle both layout and dynamically loaded ones) if (closeButton) { closeButton.addEventListener('click', closePopup); } document.addEventListener('click', function(e) { if (e.target.closest('.shop-popup-close')) { e.preventDefault(); closePopup(); } }); // Close on overlay click if (popupOverlay) { popupOverlay.addEventListener('click', function(e) { if (e.target === popupOverlay) { closePopup(); } }); } // Close on Escape key document.addEventListener('keydown', function(e) { if (e.key === 'Escape' && isPopupOpen) { closePopup(); } }); // Prevent event propagation issues document.addEventListener('click', function(e) { if (isPopupOpen && e.target.closest('.shop-popup-content')) { e.stopPropagation(); } }); function initDetailColorSelection() { console.log('🎨 Setting up detail page color selection...'); // Color selection is handled via global event delegation // No additional setup needed } function setupQuantityDropdown() { console.log('🎯 Setting up quantity dropdown with FIXED behavior...'); const quantityToggle = document.getElementById('quantityToggle'); const quantityDropdown = document.getElementById('quantityDropdown'); const quantityOptions = document.querySelectorAll('.quantity-option'); const quantityText = document.querySelector('.quantity-text'); const priceAmount = document.getElementById('priceAmount'); console.log('Dropdown elements found:', { toggle: quantityToggle, dropdown: quantityDropdown, options: quantityOptions.length, text: quantityText }); if (!quantityToggle || !quantityDropdown || !quantityText) { console.log('❌ Quantity dropdown elements not found, skipping setup'); return; } // Get unit price const unitPrice = priceAmount ? parseFloat(priceAmount.getAttribute('data-unit-price')) || 0 : 0; console.log('💰 Unit price:', unitPrice); // Initialize - DON'T reset to 1, keep current value let currentQuantity = parseInt(quantityText.textContent) || 1; quantityDropdown.classList.remove('show'); // Remove any existing selected states quantityOptions.forEach(opt => { opt.classList.remove('selected'); }); // Set initial selected state based on current quantity quantityOptions.forEach(opt => { if (parseInt(opt.getAttribute('data-value')) === currentQuantity) { opt.classList.add('selected'); } }); // Function to update prices function updatePrices(quantity) { const totalProductPrice = unitPrice * quantity; console.log('🔄 Updating prices:', { quantity: quantity, unitPrice: unitPrice, totalProductPrice: totalProductPrice }); // Update product price display if (priceAmount) { const formattedPrice = formatPrice(totalProductPrice); priceAmount.textContent = formattedPrice; // Add animation priceAmount.classList.add('price-update'); setTimeout(() => { priceAmount.classList.remove('price-update'); }, 500); console.log('✅ Product price updated to:', formattedPrice); } // Store quantity for persistence const productContainer = document.querySelector('.product-details-container, [data-product-id]'); const productId = productContainer ? productContainer.getAttribute('data-product-id') : ''; if (productId) { sessionStorage.setItem(`product_${productId}_selected_quantity`, quantity.toString()); } } // Price formatting function function formatPrice(price) { return new Intl.NumberFormat('hu-HU', { minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(price) + ' Ft'; } // Toggle dropdown - DON'T reset quantity quantityToggle.addEventListener('click', function(event) { event.stopPropagation(); event.preventDefault(); console.log('📱 Dropdown toggled, current quantity:', currentQuantity); // Just toggle visibility, don't change quantity quantityDropdown.classList.toggle('show'); quantityToggle.classList.toggle('active'); }); // Handle quantity selection quantityOptions.forEach(option => { option.addEventListener('click', function(event) { event.stopPropagation(); const newQuantity = parseInt(this.getAttribute('data-value')); console.log('🔢 Quantity selected:', newQuantity); // Update current quantity currentQuantity = newQuantity; // Update displayed text quantityText.textContent = newQuantity; // Update selected state - remove from all, add to clicked quantityOptions.forEach(opt => { opt.classList.remove('selected'); }); this.classList.add('selected'); // Close dropdown quantityDropdown.classList.remove('show'); quantityToggle.classList.remove('active'); // Update prices based on new quantity updatePrices(newQuantity); console.log('✅ Quantity updated to:', newQuantity); }); }); // Close dropdown on outside click - DON'T reset quantity document.addEventListener('click', function(event) { if (!quantityToggle.contains(event.target) && !quantityDropdown.contains(event.target)) { console.log('📤 Dropdown closed (outside click), keeping quantity:', currentQuantity); quantityDropdown.classList.remove('show'); quantityToggle.classList.remove('active'); // DON'T reset the quantity text - keep the selected value } }); // Prevent dropdown close when clicking inside dropdown quantityDropdown.addEventListener('click', function(e) { e.stopPropagation(); }); // Restore saved quantity on page load const productContainer = document.querySelector('.product-details-container, [data-product-id]'); const productId = productContainer ? productContainer.getAttribute('data-product-id') : ''; const savedQuantity = productId ? sessionStorage.getItem(`product_${productId}_selected_quantity`) : null; if (savedQuantity) { const quantity = parseInt(savedQuantity); if (quantity > 0 && quantity <= 5) { console.log('🔄 Restoring saved quantity:', quantity); currentQuantity = quantity; quantityText.textContent = quantity; // Update selected option in dropdown quantityOptions.forEach(opt => { if (parseInt(opt.getAttribute('data-value')) === quantity) { opt.classList.add('selected'); } }); // Update prices for restored quantity updatePrices(quantity); } } else { // Initialize with current quantity (not necessarily 1) updatePrices(currentQuantity); } console.log('✅ Fixed quantity dropdown initialized with quantity:', currentQuantity); } // Personalize button function (keep this for the HTML onclick) function showPopupMemorialCustomization(productId) { console.log('showPopupMemorialCustomization called with productId:', productId); // Use popup flow if (window.parent && window.parent !== window && typeof window.parent.showPopupMemorialCustomization === 'function') { window.parent.showPopupMemorialCustomization(productId); } else { console.log('Parent function not available, using direct navigation'); // Fallback: navigate directly const memorialUrl = '/nk-de/products/product/popup-memorial-customization?id=' + productId; window.location.href = memorialUrl; } } function setupCartInteractions() { // Initialize cart total updateCartTotal(); var popupBodyEl = document.getElementById('shop-popup-body'); var isCheckoutPage = popupBodyEl && popupBodyEl.querySelector('.add-card-option') !== null; if (isCheckoutPage) { console.log('On checkout page, skipping back button binding in setupCartInteractions'); return; } // Remove item buttons var removeItemBtns = document.querySelectorAll('.remove-item-btn'); removeItemBtns.forEach(function(btn) { btn.addEventListener('click', function() { if (confirm('Are you sure you want to remove this item?')) { this.closest('.cart-item').remove(); updateCartTotal(); } }); }); } function updateCartTotal() { console.log('🔄 Updating cart total...'); // Read quantity from the visible quantity span var quantityDisplay = document.querySelector('.quantity-display'); var quantity = quantityDisplay ? parseInt(quantityDisplay.textContent, 10) || 1 : 1; // Parse unit price from the cart product price element var unitPriceEl = document.querySelector('.cart-product-price'); var unitPrice = 0; if (unitPriceEl) { var raw = unitPriceEl.textContent || ''; // Handle formats like "39,96 Ft" or "39.96 Ft" var cleaned = raw.replace(/[^0-9,.]/g, ''); var normalized = cleaned.replace(',', '.'); unitPrice = parseFloat(normalized) || parseFloat(unitPriceEl.getAttribute('data-unit-price')) || currentProduct.price || 20000; } else { // Fallback to currentProduct.price or default unitPrice = currentProduct.price || 20000; console.warn('⚠️ Unit price element not found, using fallback:', unitPrice); } // Calculate total var total = quantity * unitPrice; // Update the total display in the summary section (Összesen) var summaryAmount = document.querySelector('.summary-amount'); if (summaryAmount) { summaryAmount.textContent = new Intl.NumberFormat('hu-HU', { minimumFractionDigits: 0 }).format(total) + ' Ft'; } // Update the main cart total at the top var mainTotal = document.querySelector('.product-title-price-card .price-amount'); if (mainTotal) { mainTotal.textContent = new Intl.NumberFormat('hu-HU', { minimumFractionDigits: 0 }).format(total) + ' Ft'; } // Update totalAmount for checkout var totalAmountEl = document.getElementById('totalAmount'); if (totalAmountEl) { totalAmountEl.textContent = new Intl.NumberFormat('hu-HU', { minimumFractionDigits: 0 }).format(total) + ' Ft'; totalAmountEl.setAttribute('data-raw-amount', total); } console.log('✅ Cart total updated:', { quantity, unitPrice, total }); } // Global function to return to checkout from success/failed payment window.updateCartTotal = updateCartTotal; // Expose globally document.addEventListener('click', function(e) { var closeBtn = e.target.closest('.shop-popup-close'); if (closeBtn) { try { sessionStorage.removeItem('selectedProfile'); } catch (_) {} } }); // Ensure going back from product detail to products list shows ONLY the search bar // Remove any selected profile right before navigating back document.addEventListener('click', function(e) { var backBtn = e.target.closest('.back-to-products-btn'); if (backBtn) { try { sessionStorage.removeItem('selectedProfile'); } catch (_) {} } }); });