function addToCart(sid) {
    var fd = new FormData();
    fd.append('action', 'add');
    fd.append('service_id', sid);
    fd.append('quantity', 1);
    
    fetch('/allura/php/cart_handler.php', {method: 'POST', body: fd})
    .then(r => r.json())
    .then(d => {
        if (d.success) {
            showSuccess(d.message);
            updateCartDisplay();
            setTimeout(updateCartShoeImages, 100);
        } else showError(d.message);
    })
    .catch(e => showError('Error adding to cart'));
}

function removeFromCart(sid) {
    showRemoveNotification(sid);
}

function confirmRemoveItem(sid) {
    removeItemFromDisplay(sid);
    var fd = new FormData();
    fd.append('action', 'remove');
    fd.append('service_id', sid);
    fetch('/allura/php/cart_handler.php', {method: 'POST', body: fd})
    .then(r => r.json())
    .then(d => {
        if (d.success) {
            showSuccess('Removed');
            updateCartDisplay();
        } else location.reload();
    })
    .catch(e => location.reload());
    closeRemoveNotification();
}

function removeItemFromDisplay(serviceId) {
    var cartItems = document.querySelectorAll('.cart-item-card');
    for (var i = 0; i < cartItems.length; i++) {
        var item = cartItems[i];
        var removeButton = item.querySelector('button[onclick*="removeFromCart(' + serviceId + ')"]');
        if (removeButton) {
            item.style.opacity = '0.5';
            item.style.transform = 'scale(0.95)';
            item.style.transition = 'all 0.3s ease';
            
            setTimeout(function() {
                item.remove();
                var newCount = getCartItemsCount();
                updateCartCounter(newCount);
                updateCartTotals();
                checkEmptyCart();
            }, 300);
            break;
        }
    }
}

function checkEmptyCart() {
    var remainingItems = document.querySelectorAll('.cart-item-card');
    if (remainingItems.length === 0) {
        var cartContainer = document.querySelector('.cart-container');
        if (cartContainer) {
            cartContainer.innerHTML = `
                <div class="cart-header">
                    <h2>My Cart</h2>
                </div>
                <p>Your cart is empty. <a href="/allura/service.php">Continue shopping</a></p>
            `;
        }
        updateCartCounter(0);
    }
}

function updateCartCounter(count) {
    var cartCountElement = document.querySelector('.cart-count');
    if (cartCountElement) {
        if (count > 0) {
            cartCountElement.textContent = count;
            cartCountElement.style.display = 'inline';
        } else {
            cartCountElement.style.display = 'none';
        }
    }
}

function getCartItemsCount() {
    var cartItems = document.querySelectorAll('.cart-item-card');
    return cartItems.length;
}

function updateQuantity(serviceId, change) {
    updateQuantityDisplay(serviceId, change);
    
    var formData = new FormData();
    formData.append('action', 'update');
    formData.append('service_id', serviceId);
    formData.append('change', change);

    fetch('/allura/php/cart_handler.php', {
        method: 'POST',
        body: formData
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        if (data.success) {
            updateCartDisplay();
            setTimeout(updateCartShoeImages, 100);
        } else {
            showError(data.message);
            location.reload();
        }
    })
    .catch(function(error) {
        console.error('Error:', error);
        showError('Error updating cart');
        location.reload();
    });
}

function updateQuantityDisplay(serviceId, change) {
    var qtySpans = document.querySelectorAll('.quantity-display');
    for (var i = 0; i < qtySpans.length; i++) {
        var span = qtySpans[i];
        var parent = span.closest('.quantity-control');
        if (parent) {
            var btns = parent.querySelectorAll('button');
            for (var j = 0; j < btns.length; j++) {
                var btn = btns[j];
                var onclick = btn.getAttribute('onclick');
                if (onclick && onclick.includes('updateQuantity(' + serviceId + ',')) {
                    var currentQty = parseInt(span.textContent);
                    var newQty = currentQty + change;
                    if (newQty < 1) newQty = 1;
                    span.textContent = newQty;
                    
                    updateItemPrice(span, newQty);
                    
                    var newCount = getCartItemsCount();
                    updateCartCounter(newCount);
                    break;
                }
            }
        }
    }
}

function updateItemPrice(qtySpan, newQty) {
    var card = qtySpan.closest('.cart-item-card');
    if (card) {
        var baseEl = card.querySelector('.base-priceCART');
        var totalEl = card.querySelector('.item-price');
        
        if (baseEl && totalEl) {
            var baseTxt = baseEl.textContent;
            var basePrice = parseFloat(baseTxt.replace(/[^\d.]/g, ''));
            
            var optsPrice = calculateOptionsPrice(card);
            var newTotal = (basePrice + optsPrice) * newQty;
            totalEl.textContent = 'SAR ' + newTotal.toFixed(2);
            
            updateCartTotals();
        }
    }
}

function calculateOptionsPrice(card) {
    var optsPrice = 0;
    var optsDiv = card.querySelector('.selected-options');
    
    if (optsDiv) {
        var spans = optsDiv.querySelectorAll('span');
        for (var i = 0; i < spans.length; i++) {
            var txt = spans[i].textContent;
            
            var priceMatch = txt.match(/\(\+SAR\s*([\d.]+)\)/);
            if (priceMatch) {
                var price = parseFloat(priceMatch[1]);
                if (!isNaN(price)) {
                    optsPrice += price;
                }
            }
            
            var discMatch = txt.match(/\((?:SAR\s*-|-)SAR?\s*([\d.]+)\)/);
            if (discMatch) {
                var disc = parseFloat(discMatch[1]);
                if (!isNaN(disc)) {
                    optsPrice -= disc;
                }
            }
        }
    }
    
    return optsPrice;
}

function updateCartTotals() {
    var total = 0;
    var prices = document.querySelectorAll('.item-price');
    
    for (var i = 0; i < prices.length; i++) {
        var txt = prices[i].textContent;
        var price = parseFloat(txt.replace(/[^\d.]/g, ''));
        if (!isNaN(price)) {
            total += price;
        }
    }
    
    var discountAmount = 0;
    var discountInfo = document.querySelector('.discount-info');
    if (discountInfo) {
        var discountText = discountInfo.querySelector('p:last-child');
        if (discountText) {
            var discMatch = discountText.textContent.match(/SAR\s*([\d.]+)/);
            if (discMatch) {
                discountAmount = parseFloat(discMatch[1]);
            }
        }
    }
    
    var discountedTotal = total - discountAmount;
    var tax = discountedTotal * 0.08;
    var finalTotal = discountedTotal + tax;
    
    var summaryRows = document.querySelectorAll('.cart-summary .summary-row');
    if (summaryRows.length >= 3) {
        var subtotalSpan = summaryRows[0].querySelector('span:nth-child(2)');
        if (subtotalSpan) {
            subtotalSpan.textContent = 'SAR ' + total.toFixed(2);
        }
        
        var taxRowIndex = discountAmount > 0 ? 2 : 1;
        var totalRowIndex = discountAmount > 0 ? 3 : 2;
        
        if (summaryRows[taxRowIndex]) {
            var taxSpan = summaryRows[taxRowIndex].querySelector('span:nth-child(2)');
            if (taxSpan) {
                taxSpan.textContent = 'SAR ' + tax.toFixed(2);
            }
        }
        
        if (summaryRows[totalRowIndex]) {
            var totalSpan = summaryRows[totalRowIndex].querySelector('span:nth-child(2)');
            if (totalSpan) {
                totalSpan.textContent = 'SAR ' + finalTotal.toFixed(2);
            }
        }
    }
}

function updateCartDisplay() {
    return fetch('/allura/php/cart_handler.php?action=get_details')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const enhancedCartItems = document.querySelector('.enhanced-cart-items');
                const summary = document.querySelector('.cart-summary');
                const cartContainer = document.querySelector('.cart-container');
                
                if (cartContainer && enhancedCartItems && summary) {
                    if (data.cartDetails.length === 0) {
                        cartContainer.innerHTML = `
                            <div class="cart-header">
                                <h2>My Cart</h2>
                                <p>Welcome, ${data.userName}</p>
                            </div>
                            <p>Your cart is empty. <a href="service.php">Continue shopping</a></p>
                        `;
                    } else {
                        const statusBadge = document.querySelector('.status-badge');
                        if (statusBadge && data.customerType) {
                            const statusLabels = {
                                'new': '🎉 New Customer',
                                'normal': '👤 Regular Customer',
                                'regular': '⭐ Valued Customer',
                                'subscribed': '💎 Subscribed Member'
                            };
                            const statusColors = {
                                'new': '#17a2b8',
                                'regular': '#ffc107',
                                'subscribed': '#6f42c1',
                                'normal': '#6c757d'
                            };
                            statusBadge.textContent = statusLabels[data.customerType] || 'Customer';
                            statusBadge.style.background = statusColors[data.customerType] || '#6c757d';
                        }
                        
                        let offerInfoDiv = document.querySelector('.customer-offer-info');
                        if (data.discountAmount > 0) {
                            const customerTypeEnglish = {
                                'new': 'new',
                                'normal': 'regular',
                                'regular': 'valued',
                                'subscribed': 'subscribed'
                            };
                            
                            const offerInfoHtml = `
                                <div class="customer-offer-info" style="background: linear-gradient(135deg, #e6f7fb 0%, #c1e1f1 100%); color: #333; padding: 1rem; border-radius: 10px; margin-bottom: 1.5rem; border: 2px solid #00aaff; box-shadow: 0 4px 15px rgba(0,170,255,0.2);">
                                    <div style="display: flex; align-items: center; margin-bottom: 0.5rem;">
                                        <span style="font-size: 1.5rem; margin-right: 0.5rem;">🎉</span>
                                        <h4 style="margin: 0; font-size: 1.1rem; color: #00aaff; font-weight: bold;">Special Offer for You!</h4>
                                    </div>
                                    <p style="margin: 0; font-size: 0.9rem; color: #333;">
                                        As a ${customerTypeEnglish[data.customerType] || 'regular'} customer, you get discount: <strong style='color: #00aaff;'>${data.discountTitle}</strong>
                                    </p>
                                </div>
                            `;
                            
                            if (offerInfoDiv) {
                                offerInfoDiv.outerHTML = offerInfoHtml;
                            } else {
                                const cartHeader = document.querySelector('.cart-header');
                                if (cartHeader) {
                                    cartHeader.insertAdjacentHTML('afterend', offerInfoHtml);
                                }
                            }
                        } else if (offerInfoDiv) {
                            offerInfoDiv.remove();
                        }
                        let cartHtml = '';
                        data.cartDetails.forEach(item => {
                            let tierInfoHtml = '';
                            if (item.is_tiered && item.tier_info) {
                                tierInfoHtml = `
                                    <div class="tiered-pricing-info" style="background: #f0f8ff; padding: 0.75rem; border-radius: 8px; margin-bottom: 0.5rem; border-left: 4px solid #00aaff;">
                                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
                                            <span style="font-weight: 600; color: #00aaff;">Price</span>
                                            <span style="font-size: 0.85rem; color: #666;">Tier: ${item.tier_info.current_tier}</span>
                                        </div>
                                        <div style="font-size: 0.9rem; color: #333;">
                                            Current Price: <strong>SAR ${parseFloat(item.tier_info.current_price).toFixed(2)}</strong> per piece
                                            ${item.tier_info.savings > 0 ? `
                                            <span style="color: #28a745; margin-left: 0.5rem;">
                                                (Save SAR ${parseFloat(item.tier_info.savings).toFixed(2)})
                                            </span>
                                            ` : ''}
                                        </div>
                                        ${item.tier_info.next_tier_at ? `
                                        <div style="font-size: 0.85rem; color: #666; margin-top: 0.25rem;">
                                            Next discount at ${item.tier_info.next_tier_at} pieces: SAR ${parseFloat(item.tier_info.next_tier_price).toFixed(2)} each
                                        </div>
                                        ` : ''}
                                    </div>
                                `;
                            } else {
                                tierInfoHtml = `<span class="base-priceCART">Base Price: SAR ${parseFloat(item.price).toFixed(2)}</span>`;
                            }
                            
                            cartHtml += `
                                <div class="cart-item-card">
                                    <div class="item-image">
                                        <img src="${item.image || 'img/default-service.png'}" 
                                             alt="${item.name}"
                                             onerror="this.src='img/default-service.png'">
                                    </div>
                                    
                                    <div class="item-content">
                                        <div class="item-header">
                                            <h4>
                                                <a href="service.php?service_id=${item.service_id}" 
                                                   style="color: #007cba; text-decoration: none; transition: color 0.3s ease;"
                                                   onmouseover="this.style.color='#005a8b'"
                                                   onmouseout="this.style.color='#007cba'">
                                                    ${item.name}
                                                </a>
                                            </h4>
                                            <span class="item-price">SAR ${parseFloat(item.total_price).toFixed(2)}</span>
                                        </div>
                                        
                                        <div class="item-details">
                                            <div class="item-info">
                                                ${tierInfoHtml}
                                                
                                                ${item.options_price > 0 ? `
                                                <span class="options-priceCART" style="color: #00aaff; font-size: 0.9rem;">
                                                    + Options: SAR ${parseFloat(item.options_price).toFixed(2)}
                                                </span>
                                                ` : ''}
                                                
                                                ${item.options_text ? `
                                                <div class="selected-options" style="margin: 0.5rem 0; padding: 0.5rem; background: #f8f9fa; border-radius: 5px; border-left: 3px solid #007cba;">
                                                    <strong style="color: #007cba;">Selected Options:</strong><br>
                                                    ${item.options_text.split(', ').map(option => 
                                                        `<span style="display: inline-block; margin: 2px 5px 2px 0; padding: 2px 8px; background: #e9ecef; border-radius: 12px; font-size: 0.85rem;">${option}</span>`
                                                    ).join('')}
                                                </div>
                                                ` : ''}
                                                
                                                <div class="quantity-section">
                                                    <span class="quantity-label">Quantity:</span>
                                                    <div class="quantity-control">
                                                        <button class="quantity-btn" onclick="updateQuantity(${item.service_id}, -1)">-</button>
                                                        <span class="quantity-display">${item.quantity}</span>
                                                        <button class="quantity-btn" onclick="updateQuantity(${item.service_id}, 1)">+</button>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="item-actions">
                                                <button class="remove-btn" onclick="removeFromCart(${item.service_id})">
                                                    <i class="fas fa-trash"></i> Remove
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                        enhancedCartItems.innerHTML = cartHtml;
                        
                        // تحديث صور الأحذية بعد إعادة بناء العناصر
                        setTimeout(updateCartShoeImages, 50);
                        
                        let discountInfoDiv = document.querySelector('.discount-info');
                        if (data.discountAmount > 0) {
                            const discountInfoHtml = `
                                <div class="discount-info" style="background: #f0f8ff; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; border-left: 4px solid #00aaff; box-shadow: 0 2px 8px rgba(0,170,255,0.2);">
                                    <h4 style="color: #00aaff; margin: 0 0 0.5rem 0; font-size: 1rem;">🎉 Discount Applied!</h4>
                                    <p style="margin: 0; color: #333;"><strong style="color: #00aaff;">${data.discountTitle}</strong></p>
                                    <p style="margin: 0.25rem 0 0 0; color: #00aaff; font-weight: 600;">You save: SAR ${parseFloat(data.discountAmount).toFixed(2)}</p>
                                </div>
                            `;
                            
                            if (discountInfoDiv) {
                                discountInfoDiv.outerHTML = discountInfoHtml;
                            } else {
                                summary.insertAdjacentHTML('beforebegin', discountInfoHtml);
                            }
                        } else if (discountInfoDiv) {
                            discountInfoDiv.remove();
                        }
                        
                        summary.innerHTML = `
                            <div class="summary-row">
                                <span>Subtotal:</span>
                                <span>SAR ${parseFloat(data.totalAmount).toFixed(2)}</span>
                            </div>
                            ${data.discountAmount > 0 ? `
                            <div class="summary-row" style="color: #00aaff;">
                                <span>Discount (${data.discountTitle}):</span>
                                <span>-SAR ${parseFloat(data.discountAmount).toFixed(2)}</span>
                            </div>
                            ` : ''}
                            <div class="summary-row">
                                <span>Tax (8%):</span>
                                <span>SAR ${parseFloat(data.taxAmount).toFixed(2)}</span>
                            </div>
                            <div class="summary-row total-row">
                                <span>Total:</span>
                                <span>SAR ${parseFloat(data.grandTotal).toFixed(2)}</span>
                            </div>
                            <div class="cart-actions">
                                <a href="/allura/service.php" class="btn">Continue Shopping</a>
                                <a href="/allura/checkout.php" class="btn">Proceed to Checkout</a>
                            </div>
                        `;
                    }
                }
                
                updateCartCount(data.cartDetails);
            } else {
                throw new Error(data.message || 'Failed to update cart display');
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
            throw error; 
        });
}

function updateCartCount(cartDetails) {
    var cartCountElement = document.querySelector('.cart-count');
    if (cartCountElement) {
        var totalItems = cartDetails.length;
        if (totalItems > 0) {
            cartCountElement.textContent = totalItems;
            cartCountElement.style.display = 'inline';
        } else {
            cartCountElement.style.display = 'none';
        }
    } else {
        var cartLink = document.querySelector('a[href="/allura/cart.php"]');
        if (cartLink) {
            var cartCountSpan = document.createElement('span');
            cartCountSpan.className = 'cart-count';
            var totalServices = cartDetails.length;
            cartCountSpan.textContent = totalServices;
            cartCountSpan.style.display = totalServices > 0 ? 'inline' : 'none';
            cartLink.appendChild(cartCountSpan);
        }
    }
}

function showRemoveNotification(serviceId) {
    const existingNotifications = document.querySelectorAll('.remove-notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });

    const notification = document.createElement('div');
    notification.className = 'remove-notification';
    
    notification.innerHTML = `
        <div class="remove-notification-content">
            <div class="remove-notification-icon">🗑️</div>
            <div class="remove-notification-text">
                <h4>Remove Item?</h4>
                <p>Are you sure you want to remove this item from your cart?</p>
            </div>
            <div class="remove-notification-actions">
                <button class="remove-btn-yes" onclick="confirmRemoveItem(${serviceId})">Yes, Remove</button>
                <button class="remove-btn-no" onclick="closeRemoveNotification()">Cancel</button>
            </div>
        </div>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification && notification.parentElement) {
            notification.remove();
        }
    }, 6000);
}

function closeRemoveNotification() {
    const notification = document.querySelector('.remove-notification');
    if (notification) {
        notification.remove();
    }
}

function updateCartShoeImages() {
    const shoeImages = {
        'heels': 'img/Heels.png',
        'sports': 'img/Sports.png',
        'formal': 'img/Formal.png',
        'casual': 'img/Casual.png'
    };
    
    const cartItems = document.querySelectorAll('.cart-item-card');
    
    cartItems.forEach(item => {
        const itemImage = item.querySelector('.item-image img');
        const selectedOptions = item.querySelector('.selected-options');
        
        if (itemImage && selectedOptions) {
            const optionsText = selectedOptions.textContent;
            
            let shoeType = null;
            if (optionsText.includes('Heels')) {
                shoeType = 'heels';
            } else if (optionsText.includes('Sports')) {
                shoeType = 'sports';
            } else if (optionsText.includes('Formal')) {
                shoeType = 'formal';
            } else if (optionsText.includes('Casual')) {
                shoeType = 'casual';
            }
            
            if (shoeType && shoeImages[shoeType]) {
                itemImage.src = shoeImages[shoeType];
            }
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    var qtySpans = document.querySelectorAll('.quantity-display');
    for (var i = 0; i < qtySpans.length; i++) {
        var span = qtySpans[i];
        var qty = parseInt(span.textContent);
        if (!isNaN(qty)) {
            updateItemPrice(span, qty);
        }
    }
    
    updateCartShoeImages();
});
