(function ($) {
    $(document).on("click", ".wcmlim_ajax_add_to_cart, .single_add_to_cart_button", function (e) {
        e.preventDefault();
        var $thisbutton = $(this),
            product_qty = $thisbutton.data("quantity") || $('input[name="quantity"]').val() || $('.qty').val() || 1,
            product_id = $thisbutton.data("product_id") ? $thisbutton.data("product_id") : $(this).val(),
            product_sku = $thisbutton.data("product_sku"),
            product_price = $thisbutton.data("product_price"),
            product_location = $thisbutton.data("selected_location"),
            product_location_key = $thisbutton.data("location_key"),
            product_location_qty = $thisbutton.data("location_qty"),
            product_location_termid = $thisbutton.data("location_termid"),
            product_location_sale_price = $thisbutton.data("location_sale_price"),
            product_location_regular_price = $thisbutton.data("location_regular_price");
        
        // Enhanced data collection for single product pages
        // If data attributes are missing, try to get values from form fields
        if (!product_location && $('#select_location').length) {
            var $selected_option = $('#select_location').find('option:selected');
            product_location = $selected_option.text().split(' - ')[0] || $selected_option.text();
            product_location_key = $selected_option.val();
            product_location_qty = $selected_option.attr('data-lc-qty') || 0;
            product_location_termid = $selected_option.attr('data-lc-termid') || $selected_option.val();
            product_location_regular_price = $selected_option.attr('data-lc-regular-price') || $('#lc_regular_price').val();
            product_location_sale_price = $selected_option.attr('data-lc-sale-price') || $('#lc_sale_price').val();
        }
        
        // Handle variable products - get variation ID if present
        var variation_id = '';
        if ($('.variation_id').length && $('.variation_id').val()) {
            variation_id = $('.variation_id').val();
            // For variations, the product ID should be the variation ID, not the parent product
            if (!$thisbutton.data("product_id") && variation_id) {
                // Keep the original product_id as parent_id for reference
                var parent_product_id = product_id;
                product_id = variation_id;
            }
        }
        
        // Get actual quantity from quantity selector
        var $qty_input = $('input[name="quantity"], .qty, input.qty');
        if ($qty_input.length && $qty_input.val()) {
            product_qty = $qty_input.val();
        }
        
        console.log('Add to cart data:', {
            product_id: product_id,
            product_qty: product_qty,
            product_location: product_location,
            product_location_key: product_location_key,
            product_location_qty: product_location_qty,
            product_location_termid: product_location_termid,
            product_location_regular_price: product_location_regular_price,
            product_location_sale_price: product_location_sale_price
        });
        product_backorder = $thisbutton.data("product_backorder");
        is_redirect = $thisbutton.data("isredirect");
        redirect_url = $thisbutton.data("cart-url");
        if (product_location_qty <= 0 && product_backorder !== 1) {
            
            var manage_stock_validation_data = {
                action: "wcmlim_ajax_validation_manage_stock",
                product_id: product_id,
                security: wc_add_to_cart_params.security,
            };


            $.ajax({
                type: "post",
                url: wc_add_to_cart_params.ajax_url,
                data: manage_stock_validation_data,
                beforeSend: function (response) {
                    $thisbutton.removeClass("added").addClass("loading");
                },
                complete: function (response) {
                    $thisbutton.addClass("added").removeClass("loading");
                },
                success: function (response) {
                    if (response == "0") {
                        Swal.fire({ icon: "error", text: "Product doesn't have a stock!" });
                        return !0;
                    }
                },
            });
        }
        // Collect all form data (including product addon fields)
        var formDataArr = $thisbutton.closest('form.cart').serializeArray();
        var data = {}; 
        formDataArr.forEach(function(item) {
            data[item.name] = item.value;
        });
        // Ensure location fields are present and override if needed
        data.action = "wcmlim_ajax_add_to_cart";
        data.product_id = product_id;
        data.product_sku = product_sku;
        data.quantity = product_qty;
        data.product_price = product_price;
        data.product_location = product_location;
        data.product_location_key = product_location_key;
        data.product_location_qty = product_location_qty;
        data.product_location_termid = product_location_termid;
        data.product_location_sale_price = product_location_sale_price;
        data.product_location_regular_price = product_location_regular_price;
        data.variation_id = variation_id || '';
        data.security = wc_add_to_cart_params.security;
        $(document.body).trigger("adding_to_cart", [$thisbutton, data]);
        $.ajax({
            type: "post",
            url: wc_add_to_cart_params.ajax_url,
            data: data,
            beforeSend: function (response) {
                $thisbutton.removeClass("added").addClass("loading");
            },
            complete: function (response) {
                $thisbutton.addClass("added").removeClass("loading");
            },
            success: function (response) {
                 if(response == "3"){
                    console
                    Swal.fire({
                        title: "Not Available!",
                        text: `Please Select ${product_location_qty} any location ${product_location}`,

                        icon: "warning"
                    }).then(() => {
                        window.location.href = window.location.href;
                    });
                    return !1;
                }

                // NEW: Handle purchase_one_location scenarios
                if (typeof response === 'string' && response.startsWith('{')) {
                    try {
                        const responseData = JSON.parse(response);
                        
                        if (responseData.status === 'location_change') {
                            // All products available at new location - offer to change location
                            Swal.fire({
                                title: wc_add_to_cart_params._purchase_change_location_text,
                                text: `Your cart contains items from ${responseData.current_location}. Do you want to change all items to ${responseData.new_location_name}?`,
                                icon: "question",
                                showCancelButton: true,
                                confirmButtonColor: "#3085d6",
                                cancelButtonColor: "#d33",
                                confirmButtonText: "Yes, Change Location!",
                                cancelButtonText: "Cancel"
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    console.log('User confirmed location change');
                                    console.log('Response data:', responseData);
                                    console.log('Product data:', {product_id, product_qty});
                                    
                                    // Update cart location via AJAX
                                    let ajaxurl;
                                    if (typeof multi_inventory !== 'undefined' && multi_inventory.ajaxurl) {
                                        ajaxurl = multi_inventory.ajaxurl;
                                    } else if (typeof wc_add_to_cart_params !== 'undefined' && wc_add_to_cart_params.ajax_url) {
                                        ajaxurl = wc_add_to_cart_params.ajax_url;
                                    } else {
                                        console.error('No AJAX URL found');
                                        Swal.fire({ 
                                            title: "Error!", 
                                            text: "AJAX URL not available. Please refresh the page and try again.", 
                                            icon: "error" 
                                        });
                                        return;
                                    }
                                    
                                    console.log('AJAX URL:', ajaxurl);
                                    
                                    jQuery.ajax({
                                        url: ajaxurl,
                                        type: "post",
                                        data: { 
                                            action: "wcmlim_update_cart_location",
                                            new_location_id: responseData.new_location_id,
                                            product_data: {
                                                product_id: product_id,
                                                quantity: product_qty
                                            }
                                        },
                                        beforeSend: function() {
                                            console.log('Sending AJAX request to update cart location');
                                        },
                                        success(updateResponse) {
                                            console.log('AJAX success response:', updateResponse);
                                            try {
                                                const updateData = JSON.parse(updateResponse);
                                                console.log('Parsed response:', updateData);
                                                if (updateData.status === 'success') {
                                                    Swal.fire({ 
                                                        title: "Location Updated!", 
                                                        text: `Cart location changed to ${updateData.new_location}. Product added successfully!`, 
                                                        icon: "success" 
                                                    }).then(() => {
                                                        window.location.href = window.location.href;
                                                    });
                                                } else {
                                                    console.error('Update failed:', updateData);
                                                    Swal.fire({ 
                                                        title: "Error!", 
                                                        text: updateData.message || "Failed to update cart location.", 
                                                        icon: "error" 
                                                    });
                                                }
                                            } catch (e) {
                                                console.error('Error parsing response:', e, updateResponse);
                                                Swal.fire({ 
                                                    title: "Error!", 
                                                    text: "Invalid response from server.", 
                                                    icon: "error" 
                                                });
                                            }
                                        },
                                        error(xhr, status, error) {
                                            console.error('AJAX error:', {xhr, status, error});
                                            console.error('Response text:', xhr.responseText);
                                            Swal.fire({ 
                                                title: "Error!", 
                                                text: "Failed to update cart location: " + error, 
                                                icon: "error" 
                                            });
                                        }
                                    });
                                } else {
                                    console.log('User cancelled location change');
                                }
                            });
                            return false;
                        }
                        
                        if (responseData.status === 'unavailable_products') {
                            // Some products not available at new location - offer to clear cart
                            let unavailableList = responseData.unavailable_products.map(p => `• ${p.name} (Qty: ${p.quantity})`).join('\n');
                            
                            Swal.fire({
                                title: wc_add_to_cart_params._purchase_change_location_notavailtext,
                                text: `The following products are not available at ${responseData.new_location_name}:\n\n${unavailableList}\n\nDo you want to clear your cart and add the new product?`,
                                icon: "warning",
                                showCancelButton: true,
                                confirmButtonColor: "#d33",
                                cancelButtonColor: "#3085d6",
                                confirmButtonText: "Yes, Clear Cart!",
                                cancelButtonText: "Cancel"
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    // Clear cart and add new product with correct location data
                                    const { ajaxurl } = multi_inventory;
                                    console.log('Clear cart - Location key:', product_location_key, 'Product ID:', product_id);
                                    
                                    jQuery.ajax({
                                        url: ajaxurl,
                                        type: "post",
                                        data: { 
                                            action: "wcmlim_empty_cart_content",
                                            loc_id: product_location_key, // Pass the location key
                                            product_id: product_id // Pass the product ID
                                        },
                                        success(output) {
                                            console.log('Cart cleared successfully, now adding product with location:', product_location);
                                            
                                            // Add the new product after clearing cart, including all addon fields
                                            var $form = $thisbutton.closest('form.cart');
                                            var formDataArr = $form.serializeArray();
                                            var newData = {};
                                            formDataArr.forEach(function(item) {
                                                newData[item.name] = item.value;
                                            });
                                            // Ensure location fields are present and override if needed
                                            newData.action = "wcmlim_ajax_add_to_cart";
                                            newData.product_id = product_id;
                                            newData.product_sku = product_sku;
                                            newData.quantity = product_qty;
                                            newData.product_price = product_price;
                                            newData.product_location = product_location;
                                            newData.product_location_key = product_location_key;
                                            newData.product_location_qty = product_location_qty;
                                            newData.product_location_termid = product_location_termid;
                                            newData.product_location_sale_price = product_location_sale_price;
                                            newData.product_location_regular_price = product_location_regular_price;
                                            newData.variation_id = variation_id || '';
                                            newData.security = wc_add_to_cart_params.security;
                                            $.ajax({
                                                type: "post",
                                                url: wc_add_to_cart_params.ajax_url,
                                                data: newData,
                                                success: function(addResponse) {
                                                    console.log('Product added after clear cart:', addResponse);
                                                    Swal.fire({ 
                                                        title: "Cart Cleared!", 
                                                        text: "Cart cleared and new product added successfully!", 
                                                        icon: "success" 
                                                    }).then(() => {
                                                        window.location.href = window.location.href;
                                                    });
                                                },
                                                error: function(xhr, status, error) {
                                                    console.error('Error adding product after clear cart:', error);
                                                    Swal.fire({ 
                                                        title: "Error!", 
                                                        text: "Cart was cleared but there was an error adding the new product.", 
                                                        icon: "error" 
                                                    });
                                                }
                                            });
                                        },
                                        error: function(xhr, status, error) {
                                            console.error('Error clearing cart:', error);
                                            Swal.fire({ 
                                                title: "Error!", 
                                                text: "There was an error clearing the cart.", 
                                                icon: "error" 
                                            });
                                        }
                                    });
                                }
                            });
                            return false;
                        }
                    } catch (e) {
                        // Not a JSON response, continue with normal processing
                    }
                }
                
                else if (response == 1) {
                    Swal.fire({
                        title: "Cart Validation",
                        text: "You can order from only one location!",
                        icon: "warning",
                        showCancelButton: !0,
                        confirmButtonColor: "#3085d6",
                        cancelButtonColor: "#d33",
                        confirmButtonText: "Yes, Update Cart!",
                    }).then((result) => {
                        if (result.isConfirmed) {
                            const { ajaxurl } = multi_inventory;
                            console.log('Cart validation - clearing cart for location:', product_location_key);
                            
                            jQuery.ajax({
                                url: ajaxurl,
                                type: "post",
                                data: { 
                                    action: "wcmlim_empty_cart_content",
                                    loc_id: product_location_key, // Pass the location key
                                    product_id: product_id // Pass the product ID
                                },
                                success(output) {
                                    console.log('Cart cleared for validation, adding product with location:', product_location);
                                    
                                    // Add the new product after clearing cart (validation), including all addon fields
                                    var $form = $thisbutton.closest('form.cart');
                                    var formDataArr = $form.serializeArray();
                                    var newData = {};
                                    formDataArr.forEach(function(item) {
                                        newData[item.name] = item.value;
                                    });
                                    // Ensure location fields are present and override if needed
                                    newData.action = "wcmlim_ajax_add_to_cart";
                                    newData.product_id = product_id;
                                    newData.product_sku = product_sku;
                                    newData.quantity = product_qty;
                                    newData.product_price = product_price;
                                    newData.product_location = product_location;
                                    newData.product_location_key = product_location_key;
                                    newData.product_location_qty = product_location_qty;
                                    newData.product_location_termid = product_location_termid;
                                    newData.product_location_sale_price = product_location_sale_price;
                                    newData.product_location_regular_price = product_location_regular_price;
                                    newData.variation_id = variation_id || '';
                                    newData.security = wc_add_to_cart_params.security;
                                    $.ajax({
                                        type: "post",
                                        url: wc_add_to_cart_params.ajax_url,
                                        data: newData,
                                        success: function(addResponse) {
                                            console.log('Product added after cart validation:', addResponse);
                                            Swal.fire({
                                                title: "Updated Cart!",
                                                text: "Your cart items has been updated and new product added successfully!",
                                                icon: "success",
                                            }).then(() => {
                                                window.location.href = window.location.href;
                                            });
                                        },
                                        error: function(xhr, status, error) {
                                            console.error('Error adding product after validation:', error);
                                            Swal.fire({ 
                                                title: "Error!", 
                                                text: "Cart was cleared but there was an error adding the new product.", 
                                                icon: "error" 
                                            });
                                        }
                                    });
                                },
                                error: function(xhr, status, error) {
                                    console.error('Error clearing cart for validation:', error);
                                    Swal.fire({ 
                                        title: "Error!", 
                                        text: "There was an error updating the cart.", 
                                        icon: "error" 
                                    });
                                }
                            });
                        }
                    });
                }else if(response == 2){
                    Swal.fire({ title: "Not Available!", text: "Item is not available at this location!", icon: "warning" }).then(() => {
                        window.location.href = window.location.href;
                    });
                }else if(response == 3){
                    Swal.fire({ title: "Not Available!", text: "Please select any location!", icon: "warning" }).then(() => {
                        window.location.href = window.location.href;
                    });
                }

                if (response.error && response.product_url) {
                    window.location = response.product_url;
                    return;
                } else {
                    $(document.body).trigger("added_to_cart", [response.fragments, response.cart_hash, $thisbutton]);
                    if (is_redirect == "yes") {
                        window.location = redirect_url;
                    }
                }
            },
        });
        return !1;
    });
})(jQuery);
