/**=======================================
     * LOAD ITEMS BACK
==========================================*/
    $(document).ready(function() {
        $('.accordion-button').on('click', function() {
            var activeTabId = $(this).attr('data-bs-target');
            localStorage.setItem('activeAccordionTab', activeTabId);
        });

        // Retrieve and activate the stored active accordion tab on page load
        var activeAccordionTab = localStorage.getItem('activeAccordionTab');
        if (activeAccordionTab) {
            $(activeAccordionTab).collapse('show');
        }
    });

//$(document).ready(function() {
    // Function to handle quantity control buttons
    $('.quantity-decrease').click(function() {
        var input = $(this).siblings('.quantity-input');
        var quantity = parseInt(input.val());
        if (quantity > 1) {
            input.val(quantity - 1);
        }
    });

    $('.quantity-increase').click(function() {
        var input = $(this).siblings('.quantity-input');
        var quantity = parseInt(input.val());
        input.val(quantity + 1);
    });
    
    $('.cart-items').on('click', '.quantity-decrease', function() {
        var input = $(this).siblings('.quantity-input');
        var quantity = parseInt(input.val());
        if (quantity > 1) {
            input.val(quantity - 1);
            var index = $(this).closest('.cart-item').index();
            cartItems[index].quantity = quantity - 1;
            cartItems[index].totalPrice = cartItems[index].price * (quantity - 1); // Update the total price
            updateCartCount(cartItems);
            //updateCartTotalPrice(cartItems);
            updateCartTotal(cartItems);
            updateCartItemsInLocalStorage(cartItems);
            displayCartItemsInSidebar(cartItems);
            displayCartItemsInCartPage(cartItems);
            displayCartItemsOnCheckOutPage(cartItems);
        }
    });
    
    $('.cart-items').on('click', '.quantity-increase', function() {
        var input = $(this).siblings('.quantity-input');
        var quantity = parseInt(input.val());
        var index = $(this).closest('.cart-item').index();
    
        //console.log("Index:", index); // Log the index to the console
        //console.log("Quantity:", quantity); // Log the quantity to the console
        
        if (index >= 0 && cartItems[index]) {
            input.val(quantity + 1);
            cartItems[index].quantity = quantity + 1;
            cartItems[index].totalPrice = cartItems[index].price * (quantity + 1);
            updateCartCount(cartItems);
            updateCartTotal(cartItems);
            updateCartItemsInLocalStorage(cartItems);
            displayCartItemsInSidebar(cartItems);
            displayCartItemsInCartPage(cartItems);
            displayCartItemsOnCheckOutPage(cartItems);
        } else {
            console.error("Item not found at index", index);
        }
    });
    
    
    
//});

    // Attach a click event listener to the cart button
    $('.d-flex[data-bs-toggle="offcanvas"]').click(function() {
        // Check if there are items in the cart
        var offcanvas = $('#offcanvasRight'); // Get the offcanvas element
        var cartItems = getCartItemsFromLocalStorage();
        if (cartItems.length > 0) {
            // If there are items, trigger the offcanvas
            $('#offcanvasRight').offcanvas('show');
        } else {
            // If the cart is empty, you can display a message or take other actions
            alert('Your cart is empty. Add something to your cart before proceeding.');
            $('#offcanvasRight').offcanvas('show');
            offcanvas.removeClass('show'); // Remove the "show" class
            offcanvas.css('visibility', 'hidden'); // Set visibility to hidden
        }
    });

    // Function to get cart items from local storage
    function getCartItemsFromLocalStorage() {
        return JSON.parse(localStorage.getItem('cart')) || [];
    }

    // Function to update cart items in local storage
    function updateCartItemsInLocalStorage(cartItems) {
        localStorage.setItem('cart', JSON.stringify(cartItems));
    }

    // Function to update the cart count in local storage
    function updateCartCountInLocalStorage(count) {
        localStorage.setItem('cart_count', count);
    }

    // Function to display cart items in the cart sidebar
    function displayCartItemsInSidebar(cartItems) {

            // Display cart items in the sidebar
            $('.cart-sidebar').html('');
            for (var i = 0; i < cartItems.length; i++) {
                var cartItem = cartItems[i];
                var itemHtml = '<div class="row cart-item mb-3">';
                itemHtml += '<div class="col-2"><img src="' + cartItem.photo + '" alt="' + cartItem.name + '" class="rounded-circle" width="50px" height="50px"></div>';
                itemHtml += '<div class="col-5 product-name align-self-center">' + cartItem.name + '</div>';
                itemHtml += '<div class="col-1 quantity align-self-center">' + cartItem.quantity + '</div>';
                itemHtml += '<div class="col-3 product-price align-self-center"><span style="font-size:10px">UGX</span> <strong>' + (cartItem.price * cartItem.quantity).toFixed(2) + '</strong></div>';
                itemHtml += '<div class="col-1 align-self-center"><button class="btn btn-danger btn-sm p-1 delete-btn" data-index="' + i + '"><small><i class="bi bi-trash text-white"></i></small></button></div>';
                itemHtml += '</div>';
                $('.cart-sidebar').append(itemHtml);
            }
    }

    // Function to display cart items in the cart sidebar
    function displayCartItemsOnCheckOutPage(cartItems) {
        // Display cart items in the sidebar
        $('.cart-checkout').html('');
        for (var i = 0; i < cartItems.length; i++) {
            var cartItem = cartItems[i];
            var itemHtml = '<div class="row cart-item mb-3">';
            itemHtml += '<div class="col-2"><img src="' + cartItem.photo + '" alt="' + cartItem.name + '" class="rounded-circle" width="50px" height="50px"></div>';
            itemHtml += '<div class="col-5 product-name align-self-center">' + cartItem.name + '</div>';
            itemHtml += '<div class="col-1 quantity align-self-center">' + cartItem.quantity + '</div>';
            itemHtml += '<div class="col-4 product-price align-self-center"><span style="font-size:10px">UGX</span> <strong>' + (cartItem.price * cartItem.quantity).toFixed(2) + '</strong></div>';
            itemHtml += '</div>';
            $('.cart-checkout').append(itemHtml);
        }
    }

    //Function to Display Items in Shoppint Cart
    function displayCartItemsInCartPage(cartItems)
    {
        
        // Display cart items in the sidebar
        $('.cart-items').html('');
        for (var i = 0; i < cartItems.length; i++) {
            var cartItem = cartItems[i];
            var itemHtml = '<div class="row cart-item mb-3">';
            itemHtml += '<div class="col-2"><img src="' + cartItem.photo + '" alt="' + cartItem.name + '" class="rounded-circle" width="50px" height="50px"></div>';
            itemHtml += '<div class="col-4 product-name align-self-center">' + cartItem.name + '</div>';
            itemHtml += '<div class="col-3 btn-group quantity align-self-center">';
            itemHtml += '<button type="button" class="btn btn-primary border-0 quantity-decrease">-</button>';
            itemHtml += '<input type="number" name="quantity" class="form-control quantity-input w-100" style="width: 50px" value="' + cartItem.quantity + '">';
            itemHtml += '<button  type="button" class="btn btn-primary border-0  quantity-increase">+</button>';
            itemHtml += '</div>';
            itemHtml += '<div class="col-2 product-price align-self-center"><span style="font-size:10px">UGX</span> <strong>' + (cartItem.price * cartItem.quantity).toFixed(2) + '</strong></div>';
            itemHtml += '<div class="col-1 align-self-center"><button class="btn btn-danger btn-sm p-1 delete-btn" data-index="' + i + '"><small><i class="bi bi-trash text-white"></i></small></button></div>';
            itemHtml += '</div>';
            $('.cart-items').append(itemHtml);
        }

        
    }

    // Function to calculate price per product basing on quantity total
    function calculateTotalPriceForProduct(cartItem) {
        // Calculate the total price for the product
        var totalPrice = parseFloat(cartItem.price) * cartItem.quantity;
        return totalPrice.toFixed(2);
    }

    // Function to calculate and update the cart total
    function updateCartTotal(cartItems) {
        var total = 0;
        for (var i = 0; i < cartItems.length; i++) {
            total += parseFloat(cartItems[i].price) * cartItems[i].quantity;
        }
        $('.cart-total').text(total.toFixed(2));
    }

    // Function to calculate and update the cart total price in the header
    function updateCartTotalPrice(cartItems) {
        var totalPrice = 0;
        for (var i = 0; i < cartItems.length; i++) {
            totalPrice += parseFloat(cartItems[i].price) * cartItems[i].quantity;
        }
        $('.cart-total').text(totalPrice.toFixed(2));
    }

    // Function to update the cart count in the header and local storage
    function updateCartCount(cartItems) {
        var newCartCount = cartItems.reduce((acc, item) => acc + item.quantity, 0);
        $('.cart-count').text(newCartCount);
        updateCartCountInLocalStorage(newCartCount);
    }

    // Display existing cart items on page load
    var cartItems = getCartItemsFromLocalStorage();
    displayCartItemsInSidebar(cartItems);
    displayCartItemsInCartPage(cartItems);
    displayCartItemsOnCheckOutPage(cartItems);
    updateCartTotal(cartItems);
    updateCartCount(cartItems); // Update the cart count on page load

    // Handle the "Add to Cart" button click
    $('.btn-cart').click(function() {
        var productId = $(this).data('product-id');
        var quantity = parseInt($(this).closest('.d-flex').find('.quantity-input').val());
        addToCart(productId, quantity);
    });

    // Function to add the product to the cart
    function addToCart(productId, quantity) {
        $.ajax({
            url: base_url + '/add/cart',
            method: 'POST',
            data: { product_id: productId },
            success: function(response) {
                // Get the current cart items from local storage
                var cartItems = getCartItemsFromLocalStorage();

                // Find the product details using the response from the server
                var product = response.product;

                // Get the product price and discount price
                var price = parseFloat(product.discount_price) || parseFloat(product.price);

                // Check if the product is already in the cart
                var existingCartItem = cartItems.find(item => item.product_id === product.id);
                if (existingCartItem) {
                    // If the product already exists in the cart, update the quantity
                    existingCartItem.quantity += quantity;
                } else {
                    // If the product is not in the cart, add it with the quantity
                    cartItems.push({
                        product_id: product.id,
                        name: product.name,
                        price: price,
                        photo: product.photo,
                        quantity: quantity,
                        totalPrice: price * quantity
                    });
                }
                toastr.success('<small><strong>' +product.name+ '</strong></small> added to cart');
                // Update the cart items in local storage
                updateCartItemsInLocalStorage(cartItems);

                // Update the cart count in the header and in local storage
                updateCartCount(cartItems);

                // Update the cart sidebar and total
                displayCartItemsInSidebar(cartItems);
                displayCartItemsInCartPage(cartItems);
                displayCartItemsOnCheckOutPage(cartItems);
                updateCartTotal(cartItems);
                //updateCartTotalPrice(cartItems); // Update the cart total price in the header
            }
        });
    }

    
    // Handle delete button click in the cart sidebar
    $(document).on('click', '.delete-btn', function() {
        var index = $(this).data('index');

        // Get the current cart items from local storage
        var cartItems = getCartItemsFromLocalStorage();

        // Remove the item at the specified index
        cartItems.splice(index, 1);

        // Update the cart items in local storage
        updateCartItemsInLocalStorage(cartItems);

        // Update the cart count in the header and in local storage
        updateCartCount(cartItems);

        // Update the cart sidebar and total
        displayCartItemsInSidebar(cartItems);
        displayCartItemsInCartPage(cartItems);
        updateCartTotal(cartItems);
        toastr.error('Product removed from cart');
    });

    // Handle Proceed Checkout button click
    $('.proceed-checkout').click(function() {
        // Close the Cart Details accordion
        $('#collapseOne').collapse('hide');
        // Open the User Details accordion
        $('#collapseTwo').collapse('show');
    });

  
   function save_checkout() 
   {
        // Retrieve the products in order
        var cartItems = getCartItemsFromLocalStorage();
        var cartDetails = JSON.stringify(cartItems);
        $('#cart-details-input').val(cartDetails);

        
        // Check if the cart is empty
        if (cartItems.length === 0) {
            $('.btn').text('Please add products');
            $('.btn').attr("disabled", "disabled");
            toastr.error('Cart is empty. Add something!');
            return; // Exit the function if the cart is empty
        }

        // Retrieve the total amount
        var totalAmount = parseFloat($('.cart-total').text());
        $('#total-amount-input').val(totalAmount);

        
        // Handle User Details form submission
        var form = $('#checkout-form')[0];
        $.ajax({
            type: "POST",
            url: base_url +"shop/save/order",
            dataType: "JSON",
            data: new FormData(form),
            processData: false,
            contentType: false,
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            beforeSend: function(){
                $('.btn').attr("disabled","disabled");
                $('.btn').removeClass('btn-primary').addClass('btn-secondary');
                $('.btn').text('Please wait...');
            },
            success: function(data)
            {
                if(data.success == true)
                {
                    toastr.success(data.msg);
                    setTimeout(function(){
                        localStorage.setItem('cart', JSON.stringify([])); // Reset the cart to an empty array
                        location.href = base_url +"shop/order-summary/"+data.orderNo;
                    },800);
                    
                }else{
                    toastr.error(data.msg);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error("AJAX Error:", errorThrown);
                // You can handle the error here
            }
        });

}

//Add Product in USER wishlist
function add_wishlist(id, name) {
    
    $.ajax({
        type: "POST",
        url: base_url + "shop/save/wishlist/"+id,
        dataType: "JSON",
        data: { id: id }, // Send the 'id' as part of the data object
        beforeSend: function () {
            $('.btn').attr("disabled", "disabled");
        },
        success: function (data) {
            if (data.success == true) {
                toastr.warning(name +' product added to wishlist');
            }
        }
    });
}

//User Delete from Wishlist
function delete_wishlist(id, name) {
    var confirmation = confirm('Are you sure you want to delete ' + name + ' from your wishlist?');
    if (confirmation) {
        window.location.href = base_url + 'shop/delete/wishlist/' + id;
    }
}


//});