document.addEventListener('DOMContentLoaded', function() {
    // Handle add to cart buttons
    const addToCartButtons = document.querySelectorAll('.add-to-cart');
    if (addToCartButtons.length > 0) {
        addToCartButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const productId = this.getAttribute('data-id');
                
                // Add animation effect to the button
                this.classList.add('adding');
                setTimeout(() => {
                    this.classList.remove('adding');
                }, 1000);
                
                addToCart(productId);
            });
        });
    }
    
    // Quantity input handlers in cart
    const quantityInputs = document.querySelectorAll('.quantity-input');
    if (quantityInputs.length > 0) {
        quantityInputs.forEach(input => {
            input.addEventListener('change', function() {
                const productId = this.getAttribute('data-id');
                const quantity = this.value;
                updateCartItem(productId, quantity);
            });
        });
    }
    
    // Remove from cart buttons
    const removeButtons = document.querySelectorAll('.remove-from-cart');
    if (removeButtons.length > 0) {
        removeButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                const productId = this.getAttribute('data-id');
                removeFromCart(productId);
            });
        });
    }
});

// Add product to cart
function addToCart(productId, quantity = 1) {
    // If a quantity input exists, use its value, otherwise default to 1
    const quantityInput = document.getElementById('quantity');
    const finalQuantity = quantityInput ? parseInt(quantityInput.value) || 1 : quantity || 1;
    
    // Get the base URL for cart path
    let cartUrl = 'cart/add.php';
    
    // Check if we're in a subdirectory by looking at current URL
    if (window.location.pathname.includes('/products/') || 
        window.location.pathname.includes('/user/')) {
        cartUrl = '../cart/add.php';
    }
    
    fetch(cartUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `product_id=${productId}&quantity=${finalQuantity}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Show success message
            showNotification('Produk berhasil ditambahkan ke keranjang', 'success');
            
            // Update cart count if available
            if (data.cartCount !== undefined) {
                updateCartCount(data.cartCount);
            } else {
                // Fallback if cartCount not returned
                updateCartCount(1);
            }
            
            // If on product detail page, update the button state
            const addButton = document.querySelector(`.add-to-cart[data-id="${productId}"]`);
            if (addButton) {
                addButton.innerHTML = "<i class='fas fa-check-circle'></i> Berhasil Ditambahkan";
                setTimeout(() => {
                    addButton.innerHTML = '<i class="fas fa-cart-plus"></i> Tambah ke Keranjang';
                }, 2000);
            }
        } else {
            // Show error message
            showNotification(data.message || 'Terjadi kesalahan', 'error');
            
            // If authentication error, redirect to login page after a delay
            if (data.message === 'Silakan login terlebih dahulu') {
                setTimeout(() => {
                    // Get the site URL from the current location
                    let baseUrl = window.location.protocol + '//' + window.location.host;
                    if (window.location.pathname.startsWith('/rakha/')) {
                        baseUrl += '/rakha';
                    }
                    
                    // Redirect to login page with return URL
                    const currentPath = window.location.pathname;
                    window.location.href = `${baseUrl}/user/login.php?redirect=${encodeURIComponent(currentPath)}`;
                }, 2000);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Terjadi kesalahan pada sistem', 'error');
    });
}

// Update cart item
function updateCartItem(productId, quantity) {
    fetch('cart/update.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `product_id=${productId}&quantity=${quantity}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update cart total
            if (data.total) {
                document.getElementById('cart-total').textContent = data.total;
            }
            
            // Update cart count
            if (data.cartCount !== undefined) {
                updateCartCount(data.cartCount);
            }
            
            showNotification('Keranjang diperbarui', 'success');
        } else {
            showNotification(data.message || 'Terjadi kesalahan', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Terjadi kesalahan pada sistem', 'error');
    });
}

// Remove from cart
function removeFromCart(productId) {
    fetch('cart/remove.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `product_id=${productId}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Remove item from DOM with fade out effect
            const cartItem = document.querySelector(`.cart-item[data-id="${productId}"]`);
            if (cartItem) {
                cartItem.style.opacity = '0';
                cartItem.style.transition = 'opacity 0.5s';
                setTimeout(() => {
                    cartItem.remove();
                }, 500);
            }
            
            // Update cart total
            if (data.total) {
                document.getElementById('cart-total').textContent = data.total;
            }
            
            // Update cart count
            if (data.cartCount !== undefined) {
                updateCartCount(data.cartCount);
            }
            
            // Show empty cart message if cart is empty
            if (data.isEmpty) {
                const cartTable = document.querySelector('.cart-table');
                if (cartTable) {
                    const emptyCart = document.createElement('div');
                    emptyCart.className = 'empty-cart';
                    emptyCart.innerHTML = `
                        <div class="empty-cart-icon">
                            <i class="fas fa-shopping-cart"></i>
                        </div>
                        <p>Keranjang belanja kosong</p>
                        <a href="../products/" class="btn">Belanja Sekarang</a>
                    `;
                    
                    // Replace table with empty cart message
                    cartTable.parentNode.replaceChild(emptyCart, cartTable);
                }
            }
            
            showNotification('Produk dihapus dari keranjang', 'success');
        } else {
            showNotification(data.message || 'Terjadi kesalahan', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Terjadi kesalahan pada sistem', 'error');
    });
}

// Update cart count indicator
function updateCartCount(count) {
    // Find cart count element
    let cartCount = document.querySelector('.cart-count');
    
    // If count is 0, hide the indicator
    if (count === 0 && cartCount) {
        cartCount.style.display = 'none';
        return;
    }
    
    // If the element doesn't exist but we have items, create it
    if (!cartCount && count > 0) {
        const cartIcon = document.querySelector('.cart-icon');
        if (cartIcon) {
            cartCount = document.createElement('span');
            cartCount.className = 'cart-count';
            cartIcon.appendChild(cartCount);
        }
    }
    
    // Update the count value if element exists
    if (cartCount) {
        cartCount.textContent = count;
        cartCount.style.display = 'flex';
        
        // Add animation
        cartCount.classList.add('bounce');
        setTimeout(() => {
            cartCount.classList.remove('bounce');
        }, 1000);
    }
}

// Show notification
function showNotification(message, type) {
    // Check if notification container exists, if not create one
    let notificationContainer = document.getElementById('notification-container');
    if (!notificationContainer) {
        notificationContainer = document.createElement('div');
        notificationContainer.id = 'notification-container';
        notificationContainer.style.position = 'fixed';
        notificationContainer.style.top = '20px';
        notificationContainer.style.right = '20px';
        notificationContainer.style.zIndex = '1000';
        document.body.appendChild(notificationContainer);
    }
    
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    
    // Add icon based on type
    let icon = 'check-circle';
    if (type === 'error') {
        icon = 'exclamation-triangle';
    } else if (type === 'warning') {
        icon = 'exclamation-circle';
    } else if (type === 'info') {
        icon = 'info-circle';
    }
    
    notification.innerHTML = `
        <div class="notification-icon">
            <i class="fas fa-${icon}"></i>
        </div>
        <div class="notification-message">${message}</div>
    `;
    
    notification.style.padding = '15px 20px';
    notification.style.margin = '5px 0';
    notification.style.borderRadius = '8px';
    notification.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
    notification.style.display = 'flex';
    notification.style.alignItems = 'center';
    notification.style.opacity = '0';
    notification.style.transform = 'translateX(50px)';
    notification.style.transition = 'opacity 0.3s, transform 0.3s';
    
    if (type === 'success') {
        notification.style.backgroundColor = '#4CAF50';
        notification.style.color = 'white';
        notification.style.borderLeft = '5px solid #2E7D32';
    } else if (type === 'error') {
        notification.style.backgroundColor = '#f44336';
        notification.style.color = 'white';
        notification.style.borderLeft = '5px solid #B71C1C';
        notification.style.fontWeight = '500';
    } else if (type === 'warning') {
        notification.style.backgroundColor = '#FF9800';
        notification.style.color = 'white';
        notification.style.borderLeft = '5px solid #E65100';
    } else {
        notification.style.backgroundColor = '#2196F3';
        notification.style.color = 'white';
        notification.style.borderLeft = '5px solid #0D47A1';
    }
    
    // Add to container
    notificationContainer.appendChild(notification);
    
    // Trigger animation
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateX(0)';
    }, 10);
    
    // Add a close button for errors that stay longer
    if (type === 'error') {
        const closeBtn = document.createElement('span');
        closeBtn.innerHTML = '&times;';
        closeBtn.style.marginLeft = '10px';
        closeBtn.style.cursor = 'pointer';
        closeBtn.style.fontSize = '20px';
        closeBtn.style.fontWeight = 'bold';
        closeBtn.onclick = function() {
            notification.style.opacity = '0';
            notification.style.transform = 'translateX(50px)';
            setTimeout(() => notification.remove(), 300);
        };
        notification.appendChild(closeBtn);
        
        // Error messages stay longer (5 seconds)
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateX(50px)';
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 5000);
    } else {
        // Auto remove other types after 3 seconds
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateX(50px)';
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 3000);
    }
}

// Add animation styles
const style = document.createElement('style');
style.textContent = `
    @keyframes bounce {
        0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
        40% {transform: translateY(-5px);}
        60% {transform: translateY(-3px);}
    }
    
    .bounce {
        animation: bounce 0.8s;
    }
    
    .adding {
        animation: pulse 1s;
    }
    
    @keyframes pulse {
        0% {transform: scale(1);}
        50% {transform: scale(1.05);}
        100% {transform: scale(1);}
    }
    
    .notification-icon {
        margin-right: 10px;
        font-size: 20px;
    }
    
    .notification {
        min-width: 280px;
    }
    
    .empty-cart {
        text-align: center;
        padding: 40px 0;
    }
    
    .empty-cart-icon {
        font-size: 60px;
        color: #ddd;
        margin-bottom: 20px;
    }
`;
document.head.appendChild(style); 