// Main JavaScript file for StoreWeb

// Cart functionality using localStorage
let cart = JSON.parse(localStorage.getItem('cart')) || [];

// Update cart count in header
function updateCartCount() {
    const cartCount = document.getElementById('cart-count');
    if (cartCount) {
        const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
        cartCount.textContent = totalItems;
    }
}

// Add item to cart
function addToCart(productId, productName, productPrice, productImage) {
    // Check if item already in cart
    const existingItem = cart.find(item => item.id === productId);
    
    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        cart.push({
            id: productId,
            name: productName,
            price: parseFloat(productPrice),
            image: productImage,
            quantity: 1
        });
    }
    
    // Save to localStorage
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // Update cart count
    updateCartCount();
    
    // Show notification
    showNotification(`${productName} تمت إضافته إلى عربة التسوق!`);
}

// Remove item from cart
function removeFromCart(productId) {
    cart = cart.filter(item => item.id !== productId);
    localStorage.setItem('cart', JSON.stringify(cart));
    updateCartCount();
    renderCart();
    
    // If user is logged in, also remove from database
    if (typeof window.userId !== 'undefined' && window.userId !== null) {
        removeCartDatabase(productId);
    }
}

// Update item quantity in cart
function updateQuantity(productId, quantity) {
    const item = cart.find(item => item.id === productId);
    
    if (item) {
        if (quantity <= 0) {
            removeFromCart(productId);
        } else {
            item.quantity = quantity;
            localStorage.setItem('cart', JSON.stringify(cart));
            updateCartCount();
            renderCart();
            
            // If user is logged in, also update the database
            if (typeof window.userId !== 'undefined' && window.userId !== null) {
                updateCartDatabase(productId, quantity);
            }
        }
    }
}

// Update cart item in database
function updateCartDatabase(productId, quantity) {
    const formData = new FormData();
    formData.append('product_id', productId);
    formData.append('quantity', quantity);
    
    fetch(window.siteUrl + '/cart/update_cart.php', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(data => {
        if (!data.success) {
            console.error('Cart update error:', data.message);
        }
    })
    .catch(error => {
        console.error('Cart update error:', error);
    });
}

// Remove cart item from database
function removeCartDatabase(productId) {
    const formData = new FormData();
    formData.append('product_id', productId);
    
    fetch(window.siteUrl + '/cart/remove_cart.php', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
    })
    .then(response => {
        // Check if response is JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            // If not JSON, try to get text content for debugging
            return response.text().then(text => {
                throw new Error('Response is not JSON. Content-Type: ' + contentType + '. Content: ' + text);
            });
        }
        return response.json();
    })
    .then(data => {
        if (!data.success) {
            console.error('Cart remove error:', data.message);
            showNotification('خطأ في إزالة العنصر من عربة التسوق: ' + data.message);
        } else {
            showNotification('تمت إزالة العنصر من عربة التسوق بنجاح');
        }
    })
    .catch(error => {
        console.error('Cart remove error:', error);
        showNotification('خطأ في إزالة العنصر من عربة التسوق. الرجاء المحاولة مرة أخرى.');
    });
}

// Toggle favorite status
function toggleFavorite(productId, buttonElement) {
    // Check if user is logged in (by checking if we have user data in JS)
    if (typeof window.userId === 'undefined' || window.userId === null) {
        showNotification('الرجاء تسجيل الدخول لإضافة المفضلة');
        // Redirect to login page after a short delay
        setTimeout(() => {
            window.location.href = window.siteUrl + '/auth/login.php';
        }, 1500);
        return;
    }
    
    // Add loading state
    const originalContent = buttonElement.innerHTML;
    buttonElement.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    buttonElement.classList.add('loading');
    buttonElement.disabled = true;
    
    // Send AJAX request
    const formData = new FormData();
    formData.append('product_id', productId);
    
    fetch(window.siteUrl + '/toggle_favorite.php', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin' // Include cookies/session
    })
    .then(response => {
        // Check if response is JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            // If not JSON, try to get text content for debugging
            return response.text().then(text => {
                throw new Error('Response is not JSON. Content-Type: ' + contentType + '. Content: ' + text);
            });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            // Toggle the active class
            buttonElement.classList.toggle('active');
            
            // Update favorite count if available
            if (data.favorite_count !== undefined) {
                const countElement = buttonElement.querySelector('.favorite-count');
                if (countElement) {
                    countElement.textContent = data.favorite_count;
                }
            }
            
            showNotification(data.message);
        } else {
            showNotification(data.message || 'خطأ في تبديل المفضلة');
        }
    })
    .catch(error => {
        console.error('Favorite toggle error:', error);
        // More user-friendly error message with details
        if (error.message && error.message.includes('Response is not JSON')) {
            showNotification('خطأ في الخادم. الرجاء المحاولة لاحقًا.');
        } else {
            showNotification('خطأ في تحديث المفضلة. الرجاء المحاولة مرة أخرى.');
        }
    })
    .finally(() => {
        // Remove loading state
        buttonElement.innerHTML = originalContent;
        buttonElement.classList.remove('loading');
        buttonElement.disabled = false;
    });
}

// Calculate cart total
function calculateCartTotal() {
    return cart.reduce((total, item) => total + (item.price * item.quantity), 0);
}

// Render cart items
function renderCart() {
    const cartTableBody = document.querySelector('.cart-table tbody');
    const cartTotalElement = document.querySelector('.cart-total-amount');
    
    if (!cartTableBody) return;
    
    // Clear current cart
    cartTableBody.innerHTML = '';
    
    // Add items to cart
    cart.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <div class="cart-item-image">
                    ${item.image ? `<img src="${item.image}" alt="${item.name}">` : '<i class="fas fa-image"></i>'}
                </div>
            </td>
            <td>${item.name}</td>
            <td>$${item.price.toFixed(2)}</td>
            <td>
                <div class="quantity-control">
                    <button onclick="updateQuantity(${item.id}, ${item.quantity - 1})">-</button>
                    <input type="number" value="${item.quantity}" min="1" onchange="updateQuantity(${item.id}, this.value)">
                    <button onclick="updateQuantity(${item.id}, ${item.quantity + 1})">+</button>
                </div>
            </td>
            <td>$${(item.price * item.quantity).toFixed(2)}</td>
            <td>
                <button class="btn btn-danger" onclick="removeFromCart(${item.id})">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        cartTableBody.appendChild(row);
    });
    
    // Update total
    if (cartTotalElement) {
        cartTotalElement.textContent = `$${calculateCartTotal().toFixed(2)}`;
    }
}

// Show notification
function showNotification(message) {
    // Remove existing notifications
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(notification => notification.remove());
    
    // Create notification
    const notification = document.createElement('div');
    notification.className = 'notification message success';
    notification.textContent = message;
    
    // Add to body
    document.body.appendChild(notification);
    
    // Remove after 3 seconds
    setTimeout(() => {
        notification.remove();
    }, 3000);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // If we have server cart items, use them
    if (typeof window.serverCartItems !== 'undefined' && window.serverCartItems.length > 0) {
        // Convert server cart items to local format
        cart = window.serverCartItems.map(item => ({
            id: item.product_id,
            name: item.name,
            price: parseFloat(item.price),
            image: item.image ? (window.siteUrl + '/' + item.image) : '',
            quantity: parseInt(item.quantity)
        }));
        
        // Save to localStorage
        localStorage.setItem('cart', JSON.stringify(cart));
    }
    
    updateCartCount();
    
    // Render cart if on cart page
    if (document.querySelector('.cart-table')) {
        renderCart();
    }
    
    // Handle add to cart buttons
    const addToCartButtons = document.querySelectorAll('.btn-add-to-cart');
    addToCartButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productCard = this.closest('.product-card');
            if (productCard) {
                const productId = productCard.dataset.productId;
                const productName = productCard.querySelector('h3').textContent;
                const productPrice = productCard.querySelector('.product-price').textContent.replace('$', '');
                const productImage = productCard.querySelector('img')?.src || '';
                
                addToCart(parseInt(productId), productName, productPrice, productImage);
            }
        });
    });
    
    // Handle favorite buttons
    const favoriteButtons = document.querySelectorAll('.favorite-btn');
    favoriteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const productId = this.dataset.productId;
            toggleFavorite(productId, this);
        });
    });
    
    // Handle quantity inputs in product detail
    const quantityInput = document.querySelector('.quantity-input input');
    const minusButton = document.querySelector('.quantity-input .minus');
    const plusButton = document.querySelector('.quantity-input .plus');
    
    if (quantityInput && minusButton && plusButton) {
        minusButton.addEventListener('click', function() {
            let value = parseInt(quantityInput.value) || 1;
            if (value > 1) {
                quantityInput.value = value - 1;
            }
        });
        
        plusButton.addEventListener('click', function() {
            let value = parseInt(quantityInput.value) || 1;
            quantityInput.value = value + 1;
        });
    }
});

// Product detail quantity controls
function updateProductQuantity(change) {
    const input = document.querySelector('.quantity-input input');
    if (input) {
        let value = parseInt(input.value) || 1;
        value += change;
        if (value < 1) value = 1;
        input.value = value;
    }
}

// Product Popup Notification System
document.addEventListener('DOMContentLoaded', function() {
    // Check if user just logged in and show welcome popup
    if (typeof window.showWelcomePopup !== 'undefined' && window.showWelcomePopup) {
        // Show welcome popup after a short delay
        setTimeout(() => {
            showRandomProductPopup(true); // true indicates it's a welcome popup
        }, 2000);
    }
    
    // Check if user is on a product-related page
    if (window.location.pathname.includes('/products/') || 
        window.location.pathname === '/' || 
        window.location.pathname.includes('/index.php')) {
        
        // Initialize popup system for random promotions (but not on homepage where we already show welcome popup)
        if (!(window.location.pathname === '/' || window.location.pathname.includes('/index.php'))) {
            initProductPopup();
        }
    }
});

function initProductPopup() {
    // Show popup at random intervals (between 30 seconds and 2 minutes)
    const randomInterval = Math.floor(Math.random() * 90000) + 30000; // 30-120 seconds
    
    setTimeout(() => {
        showRandomProductPopup();
        // Schedule next popup
        initProductPopup();
    }, randomInterval);
}

function showRandomProductPopup(isWelcome = false) {
    // Fetch a random product
    fetch(window.siteUrl + '/get_random_product.php')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.product) {
                createProductPopup(data.product, isWelcome);
            }
        })
        .catch(error => {
            console.error('Error fetching random product:', error);
        });
}

function createProductPopup(product, isWelcome = false) {
    // Check if popup already exists
    if (document.querySelector('.product-popup')) {
        return;
    }
    
    // Create popup element
    const popup = document.createElement('div');
    popup.className = 'product-popup';
    
    // Set content based on whether it's a welcome popup or not
    if (isWelcome) {
        popup.innerHTML = `
            <div class="product-popup-header">
                <h3>عرض خاص!</h3>
                <button class="product-popup-close">&times;</button>
            </div>
            <div class="product-popup-content">
                <div class="product-popup-image">
                    ${product.image ? 
                        `<img src="${product.image}" alt="${product.name}">` : 
                        `<i class="fas fa-image"></i>`}
                </div>
                <div class="product-popup-details">
                    <h4>${product.name}</h4>
                    <div class="product-popup-category">${product.category}</div>
                    <div class="product-popup-price">$${parseFloat(product.price).toFixed(2)}</div>
                    <div class="product-popup-description">اطلع على هذا المنتج الرائع خصيصًا لك!</div>
                    <div class="product-popup-actions">
                        <a href="${window.siteUrl}/products/view.php?id=${product.id}" class="product-popup-btn product-popup-view">عرض التفاصيل</a>
                        <button class="product-popup-btn product-popup-add-cart" data-product-id="${product.id}" data-product-name="${product.name}" data-product-price="${product.price}" data-product-image="${product.image || ''}">إضافة إلى العربة</button>
                    </div>
                </div>
            </div>
        `;
    } else {
        popup.innerHTML = `
            <div class="product-popup-header">
                <h3>عرض خاص!</h3>
                <button class="product-popup-close">&times;</button>
            </div>
            <div class="product-popup-content">
                <div class="product-popup-image">
                    ${product.image ? 
                        `<img src="${product.image}" alt="${product.name}">` : 
                        `<i class="fas fa-image"></i>`}
                </div>
                <div class="product-popup-details">
                    <h4>${product.name}</h4>
                    <div class="product-popup-category">${product.category}</div>
                    <div class="product-popup-price">$${parseFloat(product.price).toFixed(2)}</div>
                    <div class="product-popup-description">لا تفوت هذا العرض الخاص!</div>
                    <div class="product-popup-actions">
                        <a href="${window.siteUrl}/products/view.php?id=${product.id}" class="product-popup-btn product-popup-view">عرض</a>
                        <button class="product-popup-btn product-popup-add-cart" data-product-id="${product.id}" data-product-name="${product.name}" data-product-price="${product.price}" data-product-image="${product.image || ''}">إضافة إلى العربة</button>
                    </div>
                </div>
            </div>
        `;
    }
    
    // Add to body
    document.body.appendChild(popup);
    
    // Show popup with animation
    setTimeout(() => {
        popup.classList.add('show');
    }, 100);
    
    // Add event listeners
    const closeBtn = popup.querySelector('.product-popup-close');
    closeBtn.addEventListener('click', () => {
        popup.classList.remove('show');
        setTimeout(() => {
            popup.remove();
        }, 600); // Match the CSS transition duration
    });
    
    // Add to cart button
    const addToCartBtn = popup.querySelector('.product-popup-add-cart');
    addToCartBtn.addEventListener('click', function() {
        const productId = this.dataset.productId;
        const productName = this.dataset.productName;
        const productPrice = this.dataset.productPrice;
        const productImage = this.dataset.productImage;
        
        addToCart(parseInt(productId), productName, productPrice, productImage);
        
        // Show confirmation and close popup
        showNotification(`${productName} تمت إضافته إلى عربة التسوق!`);
        popup.classList.remove('show');
        setTimeout(() => {
            popup.remove();
        }, 600); // Match the CSS transition duration
    });
    
    // Auto close after 5 seconds (as per requirements)
    setTimeout(() => {
        if (popup.parentNode) {
            popup.classList.remove('show');
            setTimeout(() => {
                if (popup.parentNode) { // Check if still in DOM
                    popup.remove();
                }
            }, 600); // Match the CSS transition duration
        }
    }, 5000);
}