"use strict";

var tableIsLoading = false;

function iwbvelGetProductGalleryImages(productsId) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_gallery_images',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productsId,
        },
        success: function (response) {
            if (response.success && response.images !== '') {
                jQuery('#iwbvel-modal-gallery-items').html(response.images);
            }
        },
        error: function () { }
    })
}

function iwbvelGetProductsChecked() {
    if (iwbvelSelectAllChecked()) {
        return 'all_filtered';
    } else {
        let productIds = [];
        let productsChecked = jQuery("input.iwbvel-check-item:visible:checkbox:checked");
        if (productsChecked.length > 0) {
            productIds = productsChecked.map(function (i) {
                return jQuery(this).val();
            }).get();
        }
        return productIds;
    }
}

function iwbvelGetProductsCheckedWithoutVariations() {
    if (iwbvelSelectAllChecked() || !jQuery("input.iwbvel-check-item:visible:checkbox:checked").length) {
        return 'all_filtered';
    } else {
        let productIds = [];
        let productsChecked = jQuery("input.iwbvel-check-item:visible:checkbox:checked");
        if (productsChecked.length > 0) {
            productIds = productsChecked.map(function (i) {
                if (jQuery(this).attr('data-item-type') !== 'variation') {
                    return jQuery(this).val();
                }
            }).get();
        }
        return productIds;
    }
}

function iwbvelReloadProducts(edited_ids = [], current_page = iwbvelGetCurrentPage()) {
    let data = iwbvelGetCurrentFilterData();
    iwbvelHistoryFilter(null, false);
    iwbvelProductsFilter(data, 'pro_search', edited_ids, current_page);
}

function iwbvelProductsFilter(data, action, edited_ids = [], page = iwbvelGetCurrentPage()) {
    if (action === 'pagination') {
        iwbvelPaginationLoadingStart();
    } else {
        iwbvelLoadingStart();
    }

    if (IWBVEL_DATA.iwbvel_settings.close_popup_after_applying == 'yes') {
        iwbvelCloseFloatSideModal();
    }

    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_products_filter',
            nonce: IWBVEL_DATA.ajax_nonce,
            filter_data: data,
            current_page: page,
            search_action: action,
            option_values: iwbvelGetFilterFormOptionValues()
        },
        success: function (response) {
            jQuery('#iwbvel-filter-form-get-products').prop('disabled', false);
            jQuery('#iwbvel-filter-form-reset').prop('disabled', false);
            goToPageProcessing = false;
            if (response.success) {
                iwbvelLoadingSuccess();
                iwbvelSetProductsList(response, edited_ids)
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            jQuery('#iwbvel-filter-form-get-products').prop('disabled', false);
            jQuery('#iwbvel-filter-form-reset').prop('disabled', false);
            goToPageProcessing = false;
            iwbvelLoadingError();
        }
    });
}

function iwbvelReloadTable(productIds = []) {
    jQuery('#iwbvel-items-table tbody').html('<td colspan="100%" style="text-align: center;"><img style="vertical-align: middle; padding: 5px 0;" width="22" height="22" src="' + IWBVEL_DATA.icons.loading_2 + '"></td>');
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_products_filter',
            nonce: IWBVEL_DATA.ajax_nonce,
            filter_data: iwbvelGetCurrentFilterData(),
            current_page: iwbvelGetCurrentPage(),
        },
        success: function (response) {
            iwbvelSetProductsList(response, productIds);
            iwbvelHistoryFilter(null, false);
        },
        error: function () { }
    });
}

function iwbvelGetFilterFormOptionValues() {
    let optionValues = {};
    if (jQuery('.iwbvel-filter-form-select2-option-values').length) {
        jQuery('.iwbvel-filter-form-select2-option-values option:selected').each(function () {
            if (jQuery(this).attr('value') != '' && jQuery(this).attr('value') != null) {
                let optionName = jQuery(this).closest('.iwbvel-filter-form-select2-option-values').attr('data-option-name');
                if (!optionValues[optionName]) {
                    optionValues[optionName] = {};
                }
                optionValues[optionName][jQuery(this).attr('value')] = jQuery(this).text();
            }
        });
    }
    return optionValues;
}

function iwbvelClearFilterDataWithRedirect() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_clear_filter_data',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            window.location.search = '?page=iwbve';
        },
        error: function () { }
    });
}

function iwbvelSetStatusFilter(statusFilters) {
    jQuery('.iwbvel-top-nav-status-filter').html(statusFilters);

    jQuery('.iwbvel-bulk-edit-status-filter-item').removeClass('active');
    let statusFilter = (jQuery('#iwbvel-filter-form-product-status').val() && jQuery('#iwbvel-filter-form-product-status').val() != '') ? jQuery('#iwbvel-filter-form-product-status').val() : 'all';
    if (jQuery.isArray(statusFilter)) {
        statusFilter.forEach(function (val) {
            jQuery('.iwbvel-bulk-edit-status-filter-item[data-status="' + val + '"]').addClass('active');
        });
    } else {
        let activeItem = jQuery('.iwbvel-bulk-edit-status-filter-item[data-status="' + statusFilter + '"]');
        activeItem.addClass('active');
        jQuery('.iwbvel-status-filter-selected-name').text(' - ' + activeItem.text())
    }
}

function iwbvelSetProductsList(response, edited_ids = []) {
    iwbvelTotalProductCount = response.products_count;
    jQuery('#iwbvel-bulk-edit-select-all-variations').prop('checked', false);
    jQuery('.iwbvel-items-count').html(iwbvelGetTableCount(jQuery('#iwbvel-quick-per-page').val(), iwbvelGetCurrentPage(), response.products_count));
    jQuery('#iwbvel-items-table tbody').html(response.rows).ready(function () {
        if (iwbvelSelectAllChecked()) {
            jQuery('.iwbvel-check-item').prop('checked', true);
        } else {
            if (!edited_ids.length) {
                jQuery('.iwbvel-check-item-main[value="visible"]').prop('checked', false).change();
            }
        }

        if (edited_ids && edited_ids.length > 0) {
            jQuery('tr').removeClass('iwbvel-item-edited');
            edited_ids.forEach(function (productID) {
                jQuery('tr[data-item-id="' + productID + '"]').addClass('iwbvel-item-edited');
                jQuery('input[value="' + productID + '"]').prop('checked', true).change();
            });
            iwbvelShowSelectionTools();
        } else {
            iwbvelHideSelectionTools();
        }
    });
    iwbvelSetStatusFilter(response.status_filters);
    jQuery('.iwbvel-items-pagination').html(response.pagination).ready(function () {
        jQuery('#iwbvel-top-nav-filters-go-to-page').attr('max', jQuery('.iwbvel-top-nav-filters-paginate').attr('data-last-page'));

        if (parseInt(jQuery('.iwbvel-top-nav-filters-paginate').attr('data-last-page')) < 2) {
            jQuery('.iwbvel-table-item-selector-checkbox').addClass('iwbvel-check-item-main');
            jQuery('.iwbvel-table-item-selector').hide();
        } else {
            jQuery('.iwbvel-table-item-selector-checkbox').removeClass('iwbvel-check-item-main');
            jQuery('.iwbvel-table-item-selector').show();
        }
    });

    iwbvelReInitDatePicker();
    iwbvelReInitColorPicker();
    iwbvelSetTipsyTooltip();
}

function iwbvelGetProductData(productID) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_data',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productID
        },
        success: function (response) {
            if (response.success) {
                iwbvelSetProductDataBulkEditForm(response.product_data);
            } else {

            }
        },
        error: function () {

        }
    });
}

function iwbvelSetSelectedProducts(productIds) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_by_ids',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_ids: productIds
        },
        success: function (response) {
            if (response.success && response.products instanceof Object && Object.keys(response.products).length > 0) {
                let productsField = jQuery('#iwbvel-select-products-value');
                if (productsField.length > 0) {
                    jQuery.each(response.products, function (productId, productTitle) {
                        productsField.append("<option value='" + productId + "' selected>" + productTitle + "</option>").prop('selected', true);
                    });
                }
            }
        },
        error: function () {

        }
    });
}

function iwbvelSetProductDataBulkEditForm(productData) {
    let reviews_allowed = (productData.reviews_allowed) ? 'yes' : 'no';
    let sold_individually = (productData.sold_individually) ? 'yes' : 'no';
    let manage_stock = (productData.manage_stock) ? 'yes' : 'no';
    let featured = (productData.featured) ? 'yes' : 'no';
    let virtual = (productData.virtual) ? 'yes' : 'no';
    let downloadable = (productData.downloadable) ? 'yes' : 'no';

    let attributes = jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-form-group[data-type="attribute"]');
    if (attributes.length > 0) {
        let attribute_name = '';
        attributes.each(function () {
            attribute_name = jQuery(this).attr('data-name');
            if (productData.attribute[attribute_name]) {
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-form-group[data-type="attribute"][data-name="' + attribute_name + '"]').find('select[data-field="value"]').val(productData.attribute[attribute_name]).change();
            }
        });
    }

    let custom_fields = jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-form-group[data-type="custom_fields"]');
    if (custom_fields.length > 0) {
        let taxonomy_name = '';
        custom_fields.each(function () {
            taxonomy_name = jQuery(this).attr('data-name');
            if (productData.meta_field[taxonomy_name]) {
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-form-group[data-type="custom_fields"][data-name="' + taxonomy_name + '"]').find('[data-field="value"]').val(productData.meta_field[taxonomy_name][0]).change();
            }
        });
    }

    jQuery('#iwbvel-bulk-edit-form-product-title').val(productData.name);
    jQuery('#iwbvel-bulk-edit-form-product-slug').val(productData.slug);
    jQuery('#iwbvel-bulk-edit-form-product-sku').val(productData.sku);
    jQuery('#iwbvel-bulk-edit-form-product-description').val(productData.post_content);
    jQuery('#iwbvel-bulk-edit-form-product-short-description').val(productData.post_excerpt);
    jQuery('#iwbvel-bulk-edit-form-product-purchase-note').val(productData.purchase_note);
    jQuery('#iwbvel-bulk-edit-form-product-menu-order').val(productData.menu_order);
    jQuery('#iwbvel-bulk-edit-form-product-sold-individually').val(sold_individually).change();
    jQuery('#iwbvel-bulk-edit-form-product-enable-reviews').val(reviews_allowed).change();
    jQuery('#iwbvel-bulk-edit-form-product-product-status').val(productData.status).change();
    jQuery('#iwbvel-bulk-edit-form-product-catalog-visibility').val(productData.catalog_visibility).change();
    jQuery('#iwbvel-bulk-edit-form-product-date-created').val(productData.post_date);
    jQuery('#iwbvel-bulk-edit-form-product-author').val(productData.post_author).change();
    jQuery('#iwbvel-bulk-edit-form-categories').val(productData.product_cat).change();
    jQuery('#iwbvel-bulk-edit-form-tags').val(productData.product_tag).change();
    jQuery('#iwbvel-bulk-edit-form-regular-price').val(productData.regular_price);
    jQuery('#iwbvel-bulk-edit-form-sale-price').val(productData.sale_price);
    jQuery('#iwbvel-bulk-edit-form-sale-date-from').val(productData.date_on_sale_from);
    jQuery('#iwbvel-bulk-edit-form-sale-date-to').val(productData.date_on_sale_to);
    jQuery('#iwbvel-bulk-edit-form-tax-status').val(productData.tax_status).change();
    jQuery('#iwbvel-bulk-edit-form-tax-class').val(productData.tax_class).change();
    jQuery('#iwbvel-bulk-edit-form-shipping-class').val(productData.shipping_class).change();
    jQuery('#iwbvel-bulk-edit-form-width').val(productData.width);
    jQuery('#iwbvel-bulk-edit-form-height').val(productData.height);
    jQuery('#iwbvel-bulk-edit-form-length').val(productData.length);
    jQuery('#iwbvel-bulk-edit-form-weight').val(productData.weight);
    jQuery('#iwbvel-bulk-edit-form-manage-stock').val(manage_stock).change();
    jQuery('#iwbvel-bulk-edit-form-stock-status').val(productData.stock_status).change();
    jQuery('#iwbvel-bulk-edit-form-stock-quantity').val(productData.stock_quantity);
    jQuery('#iwbvel-bulk-edit-form-backorders').val(productData.backorders).change();
    jQuery('#iwbvel-bulk-edit-form-product-type').val(productData.product_type).change();
    jQuery('#iwbvel-bulk-edit-form-featured').val(featured).change();
    jQuery('#iwbvel-bulk-edit-form-virtual').val(virtual).change();
    jQuery('#iwbvel-bulk-edit-form-downloadable').val(downloadable).change();
    jQuery('#iwbvel-bulk-edit-form-download-limit').val(productData.download_limit);
    jQuery('#iwbvel-bulk-edit-form-download-expiry').val(productData.download_expiry).change();
    jQuery('#iwbvel-bulk-edit-form-product-url').val(productData.product_url);
    jQuery('#iwbvel-bulk-edit-form-button-text').val(productData.button_text);
    jQuery('#iwbvel-bulk-edit-form-upsells').val(productData.upsell_ids).change();
    jQuery('#iwbvel-bulk-edit-form-cross-sells').val(productData.cross_sell_ids).change();
}

function iwbvelDeleteProduct(productIDs, deleteType) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_delete_products',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_ids: productIDs,
            delete_type: deleteType,
        },
        success: function (response) {
            if (response.success) {
                if (response.is_processing) {
                    iwbvelIsProcessing();
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                } else {
                    iwbvelReloadProducts();
                    iwbvelHideSelectionTools();
                    iwbvelCheckUndoRedoStatus(response.reverted, response.history_items);
                    jQuery('.iwbvel-history-items tbody').html(response.history_items);
                    jQuery('.iwbvel-history-pagination-container').html(response.history_pagination);
                }
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelRestoreProduct(productIDs) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_untrash_products',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_ids: productIDs,
        },
        success: function (response) {
            if (response.success) {
                if (response.is_processing) {
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                    iwbvelIsProcessing();
                } else {
                    iwbvelReloadProducts();
                    iwbvelHideSelectionTools();
                }
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelEmptyTrash() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_empty_trash',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                if (response.is_processing) {
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                    iwbvelIsProcessing();
                } else {
                    iwbvelReloadProducts();
                    iwbvelHideSelectionTools();
                }
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelDuplicateProduct(productIDs, duplicateNumber) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_duplicate_product',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_ids: productIDs,
            count: duplicateNumber
        },
        success: function (response) {
            jQuery('#iwbvel-bulk-edit-duplicate-start').prop('disabled', false);
            if (response.success) {
                if (response.is_processing) {
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                    iwbvelIsProcessing();
                } else {
                    iwbvelReloadProducts([], iwbvelGetCurrentPage());
                    iwbvelCloseModal();
                    iwbvelHideSelectionTools();
                }
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            jQuery('#iwbvel-bulk-edit-duplicate-start').prop('disabled', false);
            iwbvelLoadingError();
        }
    });
}

function iwbvelCreateNewProduct(count = 1, productData) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_create_new_product',
            nonce: IWBVEL_DATA.ajax_nonce,
            count: count,
            product_data: productData,
        },
        success: function (response) {
            jQuery('#iwbvel-create-new-item').prop('disabled', false);
            if (response.success) {
                if (response.is_processing) {
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                    iwbvelIsProcessing();
                } else {
                    iwbvelReloadProducts([], 1);
                    iwbvelCloseModal();
                }
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            jQuery('#iwbvel-create-new-item').prop('disabled', false);
            iwbvelLoadingError();
        }
    });
}

function iwbvelHideVariationSelectionTools() {
    jQuery('#iwbvel-bulk-edit-select-all-variations-tools').hide();
}

function iwbvelShowVariationSelectionTools() {
    jQuery('#iwbvel-bulk-edit-select-all-variations-tools').show();
}

function iwbvelSaveColumnProfile(presetKey, items, type) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_save_column_profile',
            nonce: IWBVEL_DATA.ajax_nonce,
            preset_key: presetKey,
            items: items,
            type: type
        },
        success: function (response) {
            if (response.success) {
                iwbvelLoadingSuccess();
                location.href = location.href.replace(location.hash, "");
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelLoadFilterProfile(presetKey) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_load_filter_profile',
            nonce: IWBVEL_DATA.ajax_nonce,
            preset_key: presetKey,
        },
        success: function (response) {
            if (response.success) {
                if (response.option_values) {
                    IWBVEL_DATA.filter_option_values = response.option_values;
                }
                iwbvelResetFilterForm();
                iwbvelLoadingSuccess();
                iwbvelSetProductsList(response);
                iwbvelCloseModal();

                setTimeout(function () {
                    setFilterValues(response.filter_data);
                }, 500);
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelDeleteFilterProfile(presetKey) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_delete_filter_profile',
            nonce: IWBVEL_DATA.ajax_nonce,
            preset_key: presetKey,
        },
        success: function (response) {
            if (response.success) {
                iwbvelLoadingSuccess();
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelFilterProfileChangeUseAlways(presetKey) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_filter_profile_change_use_always',
            nonce: IWBVEL_DATA.ajax_nonce,
            preset_key: presetKey,
        },
        success: function (response) {
            if (response.success) {
                jQuery('.iwbvel-bulk-edit-filter-profile-load[value="' + presetKey + '"]').trigger('click');
            } else {
                iwbvelLoadingError()
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelGetCurrentFilterData() {
    return (jQuery('#iwbvel-quick-search-text').val()) ? iwbvelGetQuickSearchData() : iwbvelGetProSearchData()
}

function iwbvelResetQuickSearchForm() {
    jQuery('.iwbvel-top-nav-filters-search input').val('');
    jQuery('.iwbvel-top-nav-filters-search select').prop('selectedIndex', 0);
    jQuery('#iwbvel-quick-search-reset').hide();
    jQuery('.iwbvel-quick-filter a').removeClass('active');
}

function iwbvelResetFilterForm() {
    jQuery('.iwbvel-reset-filter-form').closest('li').hide();

    jQuery('#iwbvel-float-side-modal-filter input').val('').change();
    jQuery('#iwbvel-float-side-modal-filter textarea').val('').change();
    jQuery('#iwbvel-float-side-modal-filter select[data-type="operator"]').prop('selectedIndex', 0);
    jQuery('#iwbvel-float-side-modal-filter select[data-field="value"]').val('').change();
    jQuery('#iwbvel-float-side-modal-filter select[data-field="from"]').val('').change();
    jQuery('#iwbvel-float-side-modal-filter select[data-field="to"]').val('').change();
    jQuery('#iwbvel-float-side-modal-filter .iwbvel-select2').val('').trigger('change');
    jQuery('#iwbvel-float-side-modal-filter .select2-hidden-accessible').val('').trigger('change');
    jQuery('#iwbvel-float-side-modal-filter .iwbvel-select2-item').val('').trigger('change');
    jQuery('.iwbvel-bulk-edit-status-filter-item').removeClass('active');
}

function iwbvelResetFilters() {
    iwbvelResetFilterForm();
    iwbvelResetQuickSearchForm();
    jQuery('.iwbvel-reset-filter-form').closest('li').hide();
    jQuery('.iwbvel-check-item-main').prop('checked', false).change();

    setTimeout(function () {
        if (window.location.search !== '?page=iwbve') {
            iwbvelClearFilterDataWithRedirect()
        } else {
            let data = iwbvelGetCurrentFilterData();
            iwbvelProductsFilter(data, "pro_search");
        }
    }, 250);
}

function iwbvelChangeCountPerPage(countPerPage) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_change_count_per_page',
            nonce: IWBVEL_DATA.ajax_nonce,
            count_per_page: countPerPage,
        },
        success: function (response) {
            if (response.success) {
                iwbvelReloadProducts([], 1);
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelAddProductTaxonomy(taxonomyInfo, taxonomyName, productId) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_add_product_taxonomy',
            nonce: IWBVEL_DATA.ajax_nonce,
            taxonomy_info: taxonomyInfo,
            taxonomy_name: taxonomyName,
        },
        success: function (response) {
            if (response.success) {
                iwbvelGetProductTaxonomyTerms(productId, taxonomyName);
                iwbvelLoadingSuccess();
                iwbvelCloseModal()
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelAddProductAttribute(attributeInfo, attributeName) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_add_product_attribute',
            nonce: IWBVEL_DATA.ajax_nonce,
            attribute_info: attributeInfo,
            attribute_name: attributeName,
        },
        success: function (response) {
            if (response.success) {
                iwbvelGetProductAttributeTerms(attributeInfo.product_id, attributeName);
                iwbvelLoadingSuccess();
                iwbvelCloseModal()
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelAddNewFileItem() {
    jQuery('#iwbvel-modal-select-files-loading').show();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_add_new_file_item',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-modal-select-files .iwbvel-inline-select-files').prepend(response.file_item);
                iwbvelSetTipsyTooltip();
            }
            jQuery('#iwbvel-modal-select-files-loading').hide();
        },
        error: function () {
            jQuery('#iwbvel-modal-select-files-loading').hide();
        }
    });
}

function iwbvelAddCustomFieldFileItem() {
    jQuery('#iwbvel-modal-custom-field-files-loading').show();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_add_custom_field_file_item',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-modal-custom-field-files .iwbvel-inline-custom-field-files').prepend(response.file_item);
                iwbvelSetTipsyTooltip();
            }

            jQuery('#iwbvel-modal-custom-field-files-loading').hide();
        },
        error: function () {
            jQuery('#iwbvel-modal-custom-field-files-loading').hide();
        }
    });
}

function iwbvelBulkEditAddCustomFieldFileItem() {
    jQuery('#iwbvel-bulk-edit-custom-field-files-loading').show();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_bulk_edit_add_custom_field_file_item',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-custom-field-files').prepend(response.file_item);
                iwbvelSetTipsyTooltip();
            }
            jQuery('#iwbvel-bulk-edit-custom-field-files-loading').hide();
        },
        error: function () {
            jQuery('#iwbvel-bulk-edit-custom-field-files-loading').hide();
        }
    });
}

function iwbvelGetProductFiles(productID) {
    jQuery('#iwbvel-modal-select-files-loading').show();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_files',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productID,
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-modal-select-files .iwbvel-inline-select-files').html(response.files);
                iwbvelSetTipsyTooltip();
            } else {
                jQuery('#iwbvel-modal-select-files .iwbvel-inline-select-files').html('');
            }
            jQuery('#iwbvel-modal-select-files-loading').hide();
        },
        error: function () {
            jQuery('#iwbvel-modal-select-files .iwbvel-inline-select-files').html('');
            jQuery('#iwbvel-modal-select-files-loading').hide();
        }
    });
}

function iwbvelGetProductCustomFieldFiles(productID, customFieldName) {
    jQuery('#iwbvel-modal-custom-field-files-loading').show();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_custom_field_files',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productID,
            field_name: customFieldName
        },
        success: function (response) {
            if (response.success) {
                jQuery('.iwbvel-inline-custom-field-files').html(response.files);
            } else {
                jQuery('.iwbvel-inline-custom-field-files').html('');
            }
            jQuery('#iwbvel-modal-custom-field-files-loading').hide();
        },
        error: function () {
            jQuery('.iwbvel-inline-custom-field-files').html('');
            jQuery('#iwbvel-modal-custom-field-files-loading').hide();
        }
    });
}

function changedTabs(item) {
    let change = false;

    let tab = jQuery('nav.iwbvel-tabs-navbar a[data-content="' + item.closest('.iwbvel-tab-content-item').attr('data-content') + '"]');
    item.closest('.iwbvel-tab-content-item').find('[data-field=operator]').each(function () {
        if (jQuery(this).val() === 'text_remove_duplicate') {
            change = true;
            return false;
        }
    });
    item.closest('.iwbvel-tab-content-item').find('[data-field="value"], [data-field="from"], [data-field="to"]').each(function () {
        if (jQuery(this).val() && jQuery(this).val() != '') {
            change = true;
            return false;
        }
    });

    if (change === true) {
        tab.addClass('iwbvel-tab-changed');
    } else {
        tab.removeClass('iwbvel-tab-changed');
    }
}

function iwbvelCheckResetFilterButton() {
    jQuery('.iwbvel-reset-filter-form').closest('li').hide();

    if (jQuery('#iwbvel-bulk-edit-filter-tabs-contents [data-field="value"], #iwbvel-bulk-edit-filter-tabs-contents [data-field="from"], #iwbvel-bulk-edit-filter-tabs-contents [data-field="to"]').length > 0) {
        jQuery('#iwbvel-bulk-edit-filter-tabs-contents [data-field="value"], #iwbvel-bulk-edit-filter-tabs-contents [data-field="from"], #iwbvel-bulk-edit-filter-tabs-contents [data-field="to"]').each(function () {
            if (jQuery(this).val() != '' && jQuery(this).val() != null) {
                jQuery('.iwbvel-reset-filter-form').closest('li').show();
                return true;
            }
        });
    }
}

function iwbvelGetQuickSearchData() {
    return {
        search_type: 'quick_search',
        quick_search_text: jQuery('#iwbvel-quick-search-text').val(),
        quick_search_field: jQuery('#iwbvel-quick-search-field').val(),
        quick_search_operator: jQuery('#iwbvel-quick-search-operator').val(),
    };
}

function iwbvelSortByColumn(columnName, sortType) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_sort_by_column',
            nonce: IWBVEL_DATA.ajax_nonce,
            column_name: columnName,
            sort_type: sortType,
        },
        success: function (response) {
            if (response.success) {
                iwbvelLoadingSuccess();
                iwbvelSetProductsList(response)
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelColumnManagerFieldsGetForEdit(presetKey) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_column_manager_get_fields_for_edit',
            nonce: IWBVEL_DATA.ajax_nonce,
            preset_key: presetKey
        },
        success: function (response) {
            jQuery('#iwbvel-modal-column-manager-edit-preset .iwbvel-box-loading').hide();
            jQuery('.iwbvel-column-manager-added-fields[data-action=edit] .items').html(response.html);
            setTimeout(function () {
                iwbvelSetColorPickerTitle();
            }, 250);
            jQuery('.iwbvel-column-manager-available-fields[data-action=edit] li').each(function () {
                if (jQuery.inArray(jQuery(this).attr('data-name'), response.fields.split(',')) !== -1) {
                    jQuery(this).attr('data-added', 'true').hide();
                } else {
                    jQuery(this).attr('data-added', 'false').show();
                }
            });
            jQuery('.iwbvel-color-picker').wpColorPicker();
        },
    })
}

function iwbvelAddMetaKeysByProductID(productID) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'html',
        data: {
            action: 'iwbvel_add_meta_keys_by_product_id',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productID,
        },
        success: function (response) {
            jQuery('#iwbvel-meta-fields-items').append(response);
            iwbvelLoadingSuccess();
        },
        error: function () {
            iwbvelLoadingError();
        }
    })
}

function iwbvelHistoryUndo() {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_history_undo',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                if (response.is_processing) {
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                    iwbvelIsProcessing();
                } else {
                    iwbvelLoadingSuccess();
                    iwbvelCheckUndoRedoStatus(response.reverted, response.history_items);
                    jQuery('.iwbvel-history-items tbody').html(response.history_items);
                    jQuery('.iwbvel-history-pagination-container').html(response.history_pagination);
                    iwbvelReloadProducts(response.product_ids);
                }
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelHistoryRedo() {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_history_redo',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                if (response.is_processing) {
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                    iwbvelIsProcessing();
                } else {
                    iwbvelLoadingSuccess();
                    iwbvelCheckUndoRedoStatus(response.reverted, response.history_items);
                    jQuery('.iwbvel-history-items tbody').html(response.history_items);
                    jQuery('.iwbvel-history-pagination-container').html(response.history_pagination);
                    iwbvelReloadProducts(response.product_ids);
                }
            }
        },
        error: function () {
            iwbvelLoadingError();
        }
    });
}

function iwbvelHistoryFilter(filters = null, loading = true) {
    if (loading === true) {
        iwbvelLoadingStart();
    }

    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_history_filter',
            nonce: IWBVEL_DATA.ajax_nonce,
            filters: filters,
        },
        success: function (response) {
            if (response.success) {
                if (loading === true) {
                    iwbvelLoadingSuccess();
                }
                iwbvelCheckUndoRedoStatus(response.reverted, response.history_items);
                if (response.history_items) {
                    jQuery('.iwbvel-history-items tbody').html(response.history_items);
                    jQuery('.iwbvel-history-pagination-container').html(response.history_pagination);
                } else {
                    jQuery('.iwbvel-history-items tbody').html("<td colspan='4'><span>" + iwbvelTranslate.notFound + "</span></td>");
                }
            } else {
                if (loading === true) {
                    iwbvelLoadingError();
                }
            }
        },
        error: function () {
            if (loading === true) {
                iwbvelLoadingError();
            }
        }
    });
}

function iwbvelMetaFieldsLoad() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_meta_fields_content',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            jQuery('#iwbvel-meta-fields-loading').hide();
            if (response.success) {
                if (response.meta_fields != '') {
                    jQuery('.iwbvel-meta-fields-empty-text').hide();
                    jQuery('.iwbvel-meta-fields-items').html(response.meta_fields);
                } else {
                    jQuery('.iwbvel-meta-fields-empty-text').show();
                }

                if (response.acf_fields != '' && jQuery('#iwbvel-add-meta-fields-acf').length) {
                    jQuery('#iwbvel-add-meta-fields-acf').html(response.acf_fields);
                }
            }
        },
        error: function () {
            jQuery('#iwbvel-meta-fields-loading').hide();
        }
    });
}

function iwbvelColumnManagerLoad() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_column_manager_content',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                jQuery('[data-target="#iwbvel-float-side-modal-column-manager"]').attr('data-loaded', 'true');
                jQuery('.iwbvel-column-manager-items table tbody').html(response.profiles);
                jQuery('.iwbvel-column-manager-available-fields[data-action="new"] ul').html(response.columns);
                jQuery('.iwbvel-column-manager-available-fields[data-action="edit"] ul').html(response.columns);
            }
        },
        error: function () {
        }
    });
}

function iwbvelFilterProfileLoad() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_filter_profile_content',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                jQuery('[data-target="#iwbvel-float-side-modal-filter-profiles"]').attr('data-loaded', 'true');
                jQuery('.iwbvel-filter-profiles-items table tbody').html(response.profiles);
            }
        },
        error: function () {
        }
    });
}

function iwbvelColumnProfileLoad() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_column_profile_content',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                columnPresetsFields = response.column_presets_fields;
                defaultPresets = response.default_presets;
                jQuery('[data-target="#iwbvel-float-side-modal-column-profiles"]').attr('data-loaded', 'true');
                jQuery('.iwbvel-column-profiles-fields').html(response.columns);
                jQuery('#iwbvel-column-profiles-choose').html(response.profiles).ready(function () {
                    jQuery('#iwbvel-column-profiles-choose').trigger('change');
                });
            }
        },
        error: function () {
        }
    });
}

function iwbvelHistoryChangePage(page = 1, filters = null) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_history_change_page',
            nonce: IWBVEL_DATA.ajax_nonce,
            page: page,
            filters: filters,
        },
        success: function (response) {
            if (response.success) {
                iwbvelLoadingSuccess();
                if (response.history_items) {
                    jQuery('.iwbvel-history-items tbody').html(response.history_items);
                    jQuery('.iwbvel-history-pagination-container').html(response.history_pagination);
                } else {
                    jQuery('.iwbvel-history-items tbody').html("<td colspan='4'><span>" + iwbvelTranslate.notFound + "</span></td>");
                }
                jQuery('.iwbvel-history-pagination-loading').hide();
            } else {
                jQuery('.iwbvel-history-pagination-loading').hide();
            }
        },
        error: function () {
            jQuery('.iwbvel-history-pagination-loading').hide();
        }
    });
}

function iwbvelGetCurrentPage() {
    return jQuery('.iwbvel-items-pagination .iwbvel-top-nav-filters-paginate a.current').attr('data-index');
}

function iwbvelGetDefaultFilterProfileProducts() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_default_filter_profile_products',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                iwbvelFilterFormTabsInit(response.filter_data);
                iwbvelSetProductsList(response);
                iwbvelCheckUndoRedoStatus(response.reverted, response.history);
                setTimeout(function () {
                    let variableId = iwbvelGetUrlParameter('manage_variations');
                    if (variableId) {
                        jQuery('#iwbvel-items-table td[data-item-id="' + variableId + '"] button.iwbvel-variation-item-btn').trigger('click');
                        window.history.pushState('', '', iwbvelRemoveParamFromURL(window.location.href, 'manage_variations'));
                    }
                }, 400);
            }
        },
        error: function () { }
    });
}

function setFilterValues(filterData) {
    if (filterData.show_variations == 'yes') {
        jQuery('.iwbvel-bulk-edit-show-variations-button').addClass('selected');
        jQuery('#iwbvel-bulk-edit-show-variations').prop('checked', true);
    } else {
        jQuery('.iwbvel-bulk-edit-show-variations-button').removeClass('selected');
        jQuery('#iwbvel-bulk-edit-show-variations').prop('checked', false);
    }

    if (filterData.fields && Object.keys(filterData.fields).length) {
        jQuery('.iwbvel-bulk-edit-status-filter-item').removeClass('active');
        jQuery.each(filterData.fields, function (key, object) {
            if (object.value instanceof Object) {
                if (object.operator) {
                    jQuery('#iwbvel-float-side-modal-filter .iwbvel-form-group[data-name="' + object.name + '"]').find('[data-field="operator"]').val(object.operator).change();
                }
                if (object.value.length) {
                    let selectElement = jQuery('#iwbvel-float-side-modal-filter .iwbvel-form-group[data-name="' + object.name + '"]').find('[data-field="value"]');
                    jQuery.each(object.value, function (i, valueItem) {
                        if (IWBVEL_DATA.filter_option_values && IWBVEL_DATA.filter_option_values[object.name] && IWBVEL_DATA.filter_option_values[object.name][valueItem]) {
                            selectElement.append('<option value="' + valueItem + '" selected>' + IWBVEL_DATA.filter_option_values[object.name][valueItem] + '</option>');
                        }
                    });
                    selectElement.change();
                }
                if (object.value.from) {
                    jQuery('#iwbvel-float-side-modal-filter .iwbvel-form-group[data-name="' + object.name + '"]').find('[data-field="from"]').val(object.value.from).change();
                }
                if (object.value.to) {
                    jQuery('#iwbvel-float-side-modal-filter .iwbvel-form-group[data-name="' + object.name + '"]').find('[data-field="to"]').val(object.value.to);
                }
            } else {
                let element = jQuery('#iwbvel-float-side-modal-filter .iwbvel-form-group[data-name="' + object.name + '"]').find('[data-field="value"]');
                if (element.hasClass('iwbvel-filter-form-select2-option-values')) {
                    if (IWBVEL_DATA.filter_option_values && IWBVEL_DATA.filter_option_values[object.name] && IWBVEL_DATA.filter_option_values[object.name][object.value]) {
                        element.html('<option value="' + object.value + '" selected>' + IWBVEL_DATA.filter_option_values[object.name][object.value] + '</option>').change();
                    }
                } else {
                    element.val(object.value).change();
                }
            }
        });
        iwbvelCheckFilterFormChanges();
        iwbvelCheckResetFilterButton();
        // iwbvelFilterFormCheckAttributes();
    }
}

function checkedCurrentCategory(id, categoryIds) {
    categoryIds.forEach(function (value) {
        jQuery(id + ' input[value="' + value + '"]').prop('checked', 'checked');
    });
}

function iwbvelSaveFilterPreset(data, presetName) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_save_filter_preset',
            nonce: IWBVEL_DATA.ajax_nonce,
            filter_data: data,
            preset_name: presetName,
            option_values: iwbvelGetFilterFormOptionValues()
        },
        success: function (response) {
            jQuery('#iwbvel-filter-form-save-preset').prop('disabled', false);
            if (response.success) {
                iwbvelLoadingSuccess();
                jQuery('#iwbvel-float-side-modal-filter-profiles').find('tbody').append(response.new_item);
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            jQuery('#iwbvel-filter-form-save-preset').prop('disabled', false);
            iwbvelLoadingError();
        }
    });
}

function iwbvelResetBulkEditForm() {
    jQuery('#iwbvel-float-side-modal-bulk-edit input').val('').change();
    jQuery('#iwbvel-float-side-modal-bulk-edit input[type="checkbox"]').prop('checked', false).change();
    jQuery('#iwbvel-float-side-modal-bulk-edit select[data-field="value"], #iwbvel-float-side-modal-bulk-edit select[data-field="operator"], #iwbvel-float-side-modal-bulk-edit select[data-field="round"], #iwbvel-float-side-modal-bulk-edit select[data-field="variable"]').prop('selectedIndex', 0).change();
    jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-select2').val('').trigger('change');
    jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-select2-item').val('').trigger('change');
    jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-custom-field-files').html('');
    jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-form-item-image-preview').html('');
    jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-form-item-image-preview').closest('.iwbvel-form-group').find('input[data-field="value"]').val('').change();
    jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-form-item-gallery').html('');
    jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-bulk-edit-form-item-gallery-preview').html('');
    jQuery("nav.iwbvel-tabs-navbar li a").removeClass("iwbvel-tab-changed");
    setTimeout(function () {
        jQuery('#iwbvel-bulk-edit-form-reset').prop('disabled', false);
    }, 1000);
}

function iwbvelGetProSearchData() {
    let data = {
        search_type: 'pro_search',
        show_variations: (jQuery('#iwbvel-bulk-edit-show-variations').prop('checked') === true) ? 'yes' : 'no',
        fields: {}
    };

    jQuery('#iwbvel-float-side-modal-filter .iwbvel-form-group [data-field="value"], #iwbvel-float-side-modal-filter .iwbvel-form-group [data-field="from"]').each(function () {
        if ((jQuery(this).val() != '' && jQuery(this).val() != null) || (jQuery(this).attr('data-field') == 'from')) {
            let fromGroupElement = jQuery(this).closest('.iwbvel-form-group');
            let value;

            if (jQuery(this).attr('data-field') == 'value') {
                value = jQuery(this).val();
            }

            if (jQuery(this).attr('data-field') == 'from') {
                let toField = fromGroupElement.find('[data-field="to"]');
                if (toField.val() != '' || jQuery(this).val() != '') {
                    value = {
                        from: jQuery(this).val(),
                        to: toField.val()
                    };
                }
            }

            if (value) {
                data['fields'][fromGroupElement.attr('data-name')] = {
                    name: fromGroupElement.attr('data-name'),
                    filter_type: fromGroupElement.attr('data-filter-type'),
                    field_type: fromGroupElement.attr('data-field-type'),
                    operator: (fromGroupElement.find('[data-field="operator"]').length) ? fromGroupElement.find('[data-field="operator"]').val() : '',
                    value: value,
                };
            }
        }
    });

    return data;
}

function iwbvelProductEdit(productIds, productData) {
    if (jQuery.isArray(productIds) && productIds.length > 0) {
        if (IWBVEL_DATA.iwbvel_settings.close_popup_after_applying == 'yes') {
            iwbvelCloseFloatSideModal();
        }
        if (IWBVEL_DATA.iwbvel_settings.keep_filled_data_in_bulk_edit_form == 'no') {
            iwbvelResetBulkEditForm();
        }
        iwbvelProductEditAction(productIds, productData);
    } else {
        swal({
            title: 'Are you sure?',
            text: iwbvelTranslate.areYouSureForEditAllFilteredProducts,
            type: "warning",
            showCancelButton: true,
            cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
            confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
            confirmButtonText: iwbvelTranslate.iAmSure,
            closeOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                if (IWBVEL_DATA.iwbvel_settings.close_popup_after_applying == 'yes') {
                    iwbvelCloseFloatSideModal();
                }
                if (IWBVEL_DATA.iwbvel_settings.keep_filled_data_in_bulk_edit_form == 'yes') {
                    iwbvelResetBulkEditForm();
                }
                iwbvelProductEditAction('all_filtered', productData);
            } else {
                jQuery('.iwbvel-bulk-edit-form-do-bulk-edit').prop('disabled', false);
            }
        });
    }
}

function iwbvelProductEditAction(productIds, productData) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_product_edit',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_ids: productIds,
            product_data: productData,
            current_page: iwbvelGetCurrentPage(),
        },
        success: function (response) {
            jQuery('.iwbvel-bulk-edit-form-do-bulk-edit').prop('disabled', false);
            if (response.success) {
                if (response.is_processing === true) {
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                    iwbvelIsProcessing(response.product_ids);
                } else {
                    iwbvelReloadRows(response.products, response.product_statuses);
                    iwbvelSetStatusFilter(response.status_filters);
                    iwbvelCheckUndoRedoStatus(response.reverted, response.history_items);
                    jQuery('.iwbvel-history-items tbody').html(response.history_items);
                    jQuery('.iwbvel-history-pagination-container').html(response.history_pagination);
                    iwbvelReInitDatePicker();
                    iwbvelReInitColorPicker();
                    let iwbvelTextEditors = jQuery('input[name="iwbvel-editors[]"]');
                    if (iwbvelTextEditors.length > 0) {
                        iwbvelTextEditors.each(function () {
                            tinymce.execCommand('mceRemoveEditor', false, jQuery(this).val());
                            tinymce.execCommand('mceAddEditor', false, jQuery(this).val());
                        })
                    }
                    iwbvelLoadingSuccess();
                }
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            jQuery('.iwbvel-bulk-edit-form-do-bulk-edit').prop('disabled', false);
            iwbvelLoadingError();
        }
    });
}

function iwbvelGetBulkEditData() {
    let productIds = iwbvelGetProductsChecked();
    let productData = [];

    jQuery("#iwbvel-float-side-modal-bulk-edit .iwbvel-form-group").each(function () {
        let value;
        if (jQuery(this).find("[data-field=value]").length > 1) {
            value = jQuery(this).find("[data-field=value]").map(function () {
                if (jQuery(this).val() !== '') {
                    return jQuery(this).val();
                }
            }).get();
        } else {
            value = jQuery(this).find("[data-field=value]").val();
        }

        if (typeof jQuery(this).attr('data-name') != 'undefined') {
            if (
                (jQuery.isArray(value) && value.length > 0) ||
                (!jQuery.isArray(value) && value != '' && typeof value != 'undefined') ||
                (jQuery(this).find('select[data-field="used_for_variations"]').length > 0 && jQuery(this).find('select[data-field="used_for_variations"]').val() != '') ||
                (jQuery(this).find('select[data-field="attribute_is_visible"]').length > 0 && jQuery(this).find('select[data-field="attribute_is_visible"]').val() != '') ||
                (jQuery.inArray(jQuery(this).find("[data-field=operator]").val(), ['text_remove_duplicate', 'number_clear', 'text_clear']) !== -1)
            ) {
                let name = jQuery(this).attr('data-name');
                let type = jQuery(this).attr('data-type');

                if (jQuery(this).find("[data-field=operator]").val() == 'text_remove_duplicate') {
                    name = "remove_duplicate";
                    type = 'remove_duplicate';
                    value = 'trash';
                    if (jQuery.isArray(productIds) && productIds.length < 1) {
                        productIds = [0]
                    }
                }

                productData.push({
                    name: name,
                    sub_name: (jQuery(this).attr('data-sub-name')) ? jQuery(this).attr('data-sub-name') : '',
                    type: type,
                    operator: jQuery(this).find("[data-field=operator]").val(),
                    value: value,
                    replace: jQuery(this).find("[data-field=replace]").val(),
                    sensitive: jQuery(this).find("[data-field=sensitive]").val(),
                    round: jQuery(this).find("[data-field=round]").val(),
                    used_for_variations: jQuery(this).find('select[data-field="used_for_variations"]').val(),
                    attribute_is_visible: jQuery(this).find('select[data-field="attribute_is_visible"]').val(),
                    operation: 'bulk_edit'
                });
            }
        }
    });

    if (jQuery('.iwbvel-bulk-edit-custom-field-file-item').length) {
        let customFieldFiles = [];
        let containerElement = jQuery('.iwbvel-bulk-edit-custom-field-file-item').first().closest('.iwbvel-form-group');
        jQuery('.iwbvel-bulk-edit-custom-field-file-item').each(function () {
            let fileElement = jQuery(this);
            customFieldFiles.push({
                name: fileElement.find('input.iwbvel-bulk-edit-file-name').val(),
                url: fileElement.find('input.iwbvel-bulk-edit-file-url').val()
            });
        });

        if (customFieldFiles.length) {
            productData.push({
                name: containerElement.attr('data-name'),
                sub_name: '',
                type: containerElement.attr('data-type'),
                operator: "",
                value: customFieldFiles,
                operation: 'bulk_edit'
            });
        }
    }

    return productData;
}

function iwbvelReloadRows(products, statuses) {
    if (Object.keys(products).length != Object.keys(statuses).length) {
        iwbvelReloadProducts();
    } else {
        let currentStatus = jQuery('#iwbvel-filter-form-product-status').val();
        let oldEdited = jQuery('tr.iwbvel-item-edited');
        oldEdited.removeClass('iwbvel-item-edited');
        if (!iwbvelSelectAllChecked() && !iwbvelSelectVisibleChecked()) {
            oldEdited.find('.iwbvel-check-item').prop('checked', false);
        }
        if (products instanceof Object && Object.keys(products).length) {
            jQuery.each(products, function (key, val) {
                if (key) {
                    if (statuses[key] === currentStatus || (!currentStatus && statuses[key] !== 'trash')) {
                        jQuery('#iwbvel-items-list').find('tr[data-item-id="' + key + '"]').replaceWith(val);
                        jQuery('tr[data-item-id="' + key + '"]').addClass('iwbvel-item-edited').find('.iwbvel-check-item').prop('checked', true);
                    } else {
                        jQuery('#iwbvel-items-list').find('tr[data-item-id="' + key + '"]').remove();
                    }
                } else {
                    if (Object.keys(statuses).length) {
                        jQuery.each(statuses, function (key, val) {
                            if (val == 'trash') {
                                jQuery('#iwbvel-items-list').find('tr[data-item-id="' + key + '"]').remove();
                            }
                        });
                    }
                }
            });
            iwbvelCheckSelectAllStatus();
            iwbvelShowSelectionTools();
        } else {
            iwbvelHideSelectionTools();
        }
    }
}

function iwbvelGetTaxonomyParentSelectBox(taxonomy) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_taxonomy_parent_select_box',
            nonce: IWBVEL_DATA.ajax_nonce,
            taxonomy: taxonomy,
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-new-product-taxonomy-parent').html(response.options);
            }
        },
        error: function () { }
    });
}

function getAttributeValues(name, target) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_attribute_values',
            nonce: IWBVEL_DATA.ajax_nonce,
            attribute_name: name
        },
        success: function (response) {
            if (response.success) {
                jQuery(target).append(response.attribute_item);
                jQuery('.iwbvel-select2-ajax').select2();
            } else {

            }
        },
        error: function () {

        }
    });
}

function iwbvelGetProductBadges(productId) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_badge_ids',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-modal-product-badge-items').val(response.badges).change();
            }
        },
        error: function () { }
    });
}

function iwbvelGetProductIthemelandBadge(productId) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_ithemeland_badge',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId
        },
        success: function (response) {
            if (response.success) {
                if (Object.keys(response.badge_fields).length > 0) {
                    jQuery.each(response.badge_fields, function (key) {
                        switch (key) {
                            case '_unique_label_exclude':
                                jQuery('[name="' + key + '"]').prop('checked', (response.badge_fields[key] === 'yes'));
                                break;
                            case '_unique_label_shape':
                                jQuery('[name="' + key + '"][value="' + response.badge_fields[key] + '"]').trigger('click');
                                break;
                            case '_unique_label_rotation_x':
                            case '_unique_label_rotation_y':
                            case '_unique_label_rotation_z':
                                jQuery('[name="' + key + '"]').val(response.badge_fields[key]).change().closest('span').find('.range-slider__value').text(response.badge_fields[key]);
                                break;
                            case '_unique_label_opacity':
                                jQuery('[name="' + key + '"]').val(response.badge_fields[key]).change().closest('p').find('.range-slider__value').text(response.badge_fields[key]);
                                break;
                            default:
                                jQuery('[name="' + key + '"]').val(response.badge_fields[key]).change();
                        }

                    });
                }
            }
        },
        error: function () { }
    });
}

function iwbvelGetYikesCustomProductTabs(productId) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_yikes_custom_product_tabs',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-modal-yikes-custom-tabs').html(response.tabs_html);
                setTimeout(function () {
                    if (response.text_editor_ids) {
                        jQuery.each(response.text_editor_ids, function (key) {
                            tinymce.remove('#' + response.text_editor_ids[key]);
                            tinymce.execCommand('mceAddEditor', true, response.text_editor_ids[key]);
                        });
                    }
                }, 100);

                setTimeout(function () {
                    jQuery('.iwbvel-yikes-override-tab').trigger('change');
                }, 250);
            }
        },
        error: function () { }
    });
}

function iwbvelAddYikesSavedTab(tabId) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_add_yikes_saved_tab',
            nonce: IWBVEL_DATA.ajax_nonce,
            tab_id: tabId
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-modal-yikes-custom-tabs').append(response.tab_html);
                setTimeout(function () {
                    if (response.text_editor_id) {
                        tinymce.remove('#' + response.text_editor_id);
                        tinymce.execCommand('mceAddEditor', true, response.text_editor_id);
                    }
                }, 100);
                setTimeout(function () {
                    jQuery('.iwbvel-yikes-override-tab').trigger('change');
                }, 250);
            }
        },
        error: function () { }
    });
}

function iwbvelGetItWcRolePrices(productId) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_it_wc_role_prices',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-modal-it-wc-dynamic-pricing').find('input[data-type="value"]').each(function () {
                    if (response.prices[jQuery(this).attr('data-name')]) {
                        let amount = (response.prices[jQuery(this).attr('data-name')].price) ? response.prices[jQuery(this).attr('data-name')].price : response.prices[jQuery(this).attr('data-name')].amount;
                        jQuery(this).val(amount).change();
                    } else {
                        jQuery(this).val('').change();
                    }
                });
            }
        },
        error: function () { }
    });
}

function iwbvelGetItWcDynamicPricingSelectedRoles(productId, field) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_it_wc_dynamic_pricing_selected_roles',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId,
            field: field
        },
        success: function (response) {
            if (response.success) {
                if (jQuery.isArray(response.roles) && response.roles.length > 0) {
                    jQuery('#iwbvel-modal-it-wc-dynamic-pricing-select-roles #iwbvel-user-roles').val(response.roles).change();
                } else {
                    jQuery('#iwbvel-modal-it-wc-dynamic-pricing-select-roles #iwbvel-user-roles').val('').change();
                }
            }
        },
        error: function () { }
    });
}

function iwbvelGetItWcDynamicPricingAllFields(productId) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_it_wc_dynamic_pricing_all_fields',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId,
        },
        success: function (response) {
            if (response.success) {
                let element = jQuery('#iwbvel-modal-it-wc-dynamic-pricing-all-fields');

                if (response.it_product_disable_discount == 'yes') {
                    element.find('input#iwbvel-it-wc-dynamic-pricing-disable-discount').prop('checked', true);
                } else {
                    element.find('input#iwbvel-it-wc-dynamic-pricing-disable-discount').prop('checked', false);
                }

                if (response.it_product_hide_price_unregistered == 'yes') {
                    element.find('input#iwbvel-it-wc-dynamic-pricing-hide-price-unregistered').prop('checked', true);
                } else {
                    element.find('input#iwbvel-it-wc-dynamic-pricing-hide-price-unregistered').prop('checked', false);
                }

                if (response.it_pricing_product_price_user_role) {
                    element.find('select#iwbvel-select-roles-hide-price').val(response.it_pricing_product_price_user_role).change();
                }

                if (response.it_pricing_product_add_to_cart_user_role) {
                    element.find('select#iwbvel-select-roles-hide-add-to-cart').val(response.it_pricing_product_add_to_cart_user_role).change();
                }

                if (response.it_pricing_product_hide_user_role) {
                    element.find('select#iwbvel-select-roles-hide-product').val(response.it_pricing_product_hide_user_role).change();
                }

                if (response.pricing_rules_product.price_rule && (response.pricing_rules_product.price_rule instanceof Object) && Object.keys(response.pricing_rules_product.price_rule).length > 0) {
                    element.find('#iwbvel-it-pricing-roles input[data-type="value"]').each(function () {
                        if (response.pricing_rules_product.price_rule[jQuery(this).attr('data-name')]) {
                            let amount = (response.pricing_rules_product.price_rule[jQuery(this).attr('data-name')].price) ? response.pricing_rules_product.price_rule[jQuery(this).attr('data-name')].price : response.pricing_rules_product.price_rule[jQuery(this).attr('data-name')].amount;
                            jQuery(this).val(amount).change();
                        } else {
                            jQuery(this).val('').change();
                        }
                    });
                }
            }
        },
        error: function () { }
    });
}

function iwbvelFilterFormCheckAttributes() {
    let attributes = jQuery('.iwbvel-tab-content-item[data-content="filter_taxonomies"] .iwbvel-form-group[data-type="attribute"]');
    if (attributes.length > 0) {
        jQuery.each(attributes, function () {
            let valueField = jQuery(this).find('select[data-field="value"]');
            if (jQuery.isArray(valueField.val()) && valueField.val().length > 0) {
                jQuery('#iwbvel-bulk-edit-show-variations').prop('checked', true).change();
            }
        })
    }
}

function iwbvelBulkEditTabsInit() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_bulk_edit_tabs_content',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                jQuery('[data-target="#iwbvel-float-side-modal-bulk-edit"]').attr('data-tabs-loaded', 'true');

                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="general"]').html(response.general);
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="taxonomies"]').html(response.taxonomies);
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="type"]').html(response.type);
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="stock"]').html(response.stock);
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="pricing"]').html(response.pricing);
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="shipping"]').html(response.shipping);
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="compatibles"]').html(response.compatibles);
                jQuery('#iwbvel-float-side-modal-bulk-edit .iwbvel-tab-content-item[data-content="custom_fields"]').html(response.custom_fields).ready(function () {
                    iwbvelSelect2TaxonomiesInit();
                    iwbvelReInitDatePicker();
                    iwbvelSelect2UsersInit();
                    iwbvelSelect2ProductsInit();
                    iwbvelSelect2Init();
                });
            }
        },
        error: function () { }
    });
}

function iwbvelFilterFormTabsInit(filterData = {}) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_filter_form_tabs_content',
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            if (response.success) {
                jQuery('[data-target="#iwbvel-float-side-modal-filter"]').attr('data-tabs-loaded', 'true');
                jQuery('#iwbvel-float-side-modal-filter .iwbvel-tab-content-item[data-content="filter_general"]').html(response.general);
                jQuery('#iwbvel-float-side-modal-filter .iwbvel-tab-content-item[data-content="filter_taxonomies"]').html(response.taxonomies);
                jQuery('#iwbvel-float-side-modal-filter .iwbvel-tab-content-item[data-content="filter_type"]').html(response.type);
                jQuery('#iwbvel-float-side-modal-filter .iwbvel-tab-content-item[data-content="filter_stock"]').html(response.stock);
                jQuery('#iwbvel-float-side-modal-filter .iwbvel-tab-content-item[data-content="filter_pricing"]').html(response.pricing);
                jQuery('#iwbvel-float-side-modal-filter .iwbvel-tab-content-item[data-content="filter_shipping"]').html(response.shipping);
                jQuery('#iwbvel-float-side-modal-filter .iwbvel-tab-content-item[data-content="filter_compatibles"]').html(response.compatibles);
                jQuery('#iwbvel-float-side-modal-filter .iwbvel-tab-content-item[data-content="filter_custom_fields"]').html(response.custom_fields).ready(function () {
                    iwbvelSelect2TaxonomiesInit();
                    iwbvelReInitDatePicker();
                    iwbvelSelect2UsersInit();
                    iwbvelSelect2ProductsInit();
                    iwbvelSelect2Init();
                    setFilterValues(filterData);
                });
            }
        },
        error: function () { }
    });
}


function iwbvelSelect2TaxonomiesInit() {
    if (jQuery(".iwbvel-select2-taxonomies").length) {
        jQuery(".iwbvel-select2-taxonomies").each(function () {
            let taxonomy = jQuery(this).closest('.iwbvel-form-group').attr('data-name');
            let output = (jQuery(this).attr('data-output')) ? jQuery(this).attr('data-output') : 'term_id';
            jQuery(this).select2({
                ajax: {
                    type: "post",
                    delay: 800,
                    url: IWBVEL_DATA.ajax_url,
                    dataType: "json",
                    data: function (params) {
                        return {
                            action: "iwbvel_get_taxonomy_terms",
                            nonce: IWBVEL_DATA.ajax_nonce,
                            taxonomy: taxonomy,
                            output: output,
                            search: params.term,
                        };
                    }
                },
                placeholder: 'Name ...',
                minimumInputLength: 2
            });
        })
    }
}

function iwbvelSelect2UsersInit() {
    let userQuery;
    jQuery(".iwbvel-select2-users").select2({
        ajax: {
            type: "post",
            delay: 800,
            url: IWBVEL_DATA.ajax_url,
            dataType: "json",
            data: function (params) {
                userQuery = {
                    action: "iwbvel_get_users",
                    nonce: IWBVEL_DATA.ajax_nonce,
                    search: params.term
                };
                return userQuery;
            }
        },
        placeholder: 'Username ...',
        minimumInputLength: 3
    });
}

function iwbvelSelect2ProductsInit() {
    let query;
    jQuery(".iwbvel-get-products-ajax").select2({
        ajax: {
            type: "post",
            delay: 800,
            url: IWBVEL_DATA.ajax_url,
            dataType: "json",
            data: function (params) {
                query = {
                    action: "iwbvel_get_products_name",
                    nonce: IWBVEL_DATA.ajax_nonce,
                    search: params.term
                };
                return query;
            }
        },
        placeholder: iwbvelTranslate.enterProductName,
        minimumInputLength: 3
    });
}

function iwbvelLoadMoreVariations(productId, page) {
    let tdElement = jQuery('.iwbvel-products-table-load-more-variations[data-variable-id="' + productId + '"]').closest('td');
    let button = tdElement.find('.iwbvel-products-table-load-more-variations');
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_more_variations',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId,
            page: page,
        },
        success: function (response) {
            tdElement.find('.iwbvel-products-table-load-more-variations-loading').hide();
            if (response.success && response.rows) {
                tdElement.closest('tr').before(response.rows).ready(function () {
                    tdElement.find('.iwbvel-products-table-load-more-variations').attr('data-page', parseInt(page) + 1);
                    if (parseInt(button.attr('data-page')) > parseInt(button.attr('data-max-page'))) {
                        tdElement.closest('tr').remove();
                    }
                });
            }
        },
        error: function () {
            tdElement.find('.iwbvel-products-table-load-more-variations-loading').hide();
        }
    });
}


function iwbvelGetProductAuthor(productId) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_author',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId,
        },
        success: function (response) {
            jQuery('.iwbvel-modal-select-author-loading').hide();
            jQuery('#iwbvel-modal-select-author-input').html('<option value="' + response.author_id + '" selected>' + response.author_name + '</option>');
        },
        error: function () {
            jQuery('.iwbvel-modal-select-author-loading').hide();
        }
    });
}

function iwbvelSelect2Init() {
    if (jQuery.fn.select2) {
        let select2Element = jQuery(".iwbvel-select2");
        if (select2Element.length) {
            select2Element.select2({
                placeholder: "Select ..."
            });
        }
    }
}

function iwbvelGetProductTaxonomyTerms(productId, taxonomy) {
    jQuery('.iwbvel-modal-product-taxonomy-terms-list').html('');
    jQuery('.iwbvel-modal-product-taxonomy-loading').show();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_taxonomy_terms',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId,
            taxonomy: taxonomy
        },
        success: function (response) {
            if (response.success) {
                jQuery('.iwbvel-modal-product-taxonomy-terms-list').html(response.terms).ready(function () {
                    iwbvelFixModalHeight(jQuery('#iwbvel-modal-product-taxonomy'));
                });
            } else {
                jQuery('.iwbvel-modal-product-taxonomy-terms-list').html('');
            }
            jQuery('.iwbvel-modal-product-taxonomy-loading').hide();
        },
        error: function () {
            jQuery('.iwbvel-modal-product-taxonomy-loading').hide();
        }
    });
}

function iwbvelGetAcfTaxonomyTerms(productId, fieldName) {
    jQuery('.iwbvel-modal-acf-taxonomy-multi-select-value').html('');
    jQuery('.iwbvel-modal-acf-taxonomy-loading').show();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_acf_taxonomy_terms',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId,
            field_name: fieldName
        },
        success: function (response) {
            if (response.success) {
                jQuery('.iwbvel-modal-acf-taxonomy-multi-select-value').html(response.terms).change();
            } else {
                jQuery('.iwbvel-modal-acf-taxonomy-multi-select-value').html('');
            }
            jQuery('.iwbvel-modal-acf-taxonomy-loading').hide();
        },
        error: function () {
            jQuery('.iwbvel-modal-acf-taxonomy-loading').hide();
        }
    });
}

function iwbvelGetProductAttributeTerms(productId, attribute) {
    jQuery('.iwbvel-modal-product-attribute-terms-list').html('');
    jQuery('.iwbvel-modal-product-attribute-loading').show();
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_get_product_attribute_terms',
            nonce: IWBVEL_DATA.ajax_nonce,
            product_id: productId,
            attribute: attribute
        },
        success: function (response) {
            if (response.success) {
                jQuery('#iwbvel-modal-product-attribute .iwbvel-product-attribute-checkboxes .is-visible').prop('checked', response.visible).change();
                jQuery('#iwbvel-modal-product-attribute .iwbvel-product-attribute-checkboxes .is-visible-prev').val((response.visible) ? 'yes' : 'no');
                jQuery('#iwbvel-modal-product-attribute .iwbvel-product-attribute-checkboxes .is-variation').prop('checked', response.variation).change();
                jQuery('#iwbvel-modal-product-attribute .iwbvel-product-attribute-checkboxes .is-variation-prev').val((response.variation) ? 'yes' : 'no');

                jQuery('.iwbvel-modal-product-attribute-terms-list').html(response.terms).ready(function () {
                    iwbvelFixModalHeight(jQuery('#iwbvel-modal-product-attribute'));
                });
            } else {
                jQuery('.iwbvel-modal-product-attribute-terms-list').html('');
            }
            jQuery('.iwbvel-modal-product-attribute-loading').hide();
        },
        error: function () {
            jQuery('.iwbvel-modal-product-attribute-loading').hide();
        }
    });
}

function iwbvelIsProcessing(productIds = []) {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_is_processing',
            nonce: IWBVEL_DATA.ajax_nonce
        },
        success: function (response) {
            if (response.crashed === true) {
                iwbvelLoadingProcessingError('Error !');
                iwbvelBackgroundProcessClearCompleteMessage();
                iwbvelHistoryFilter(null, false);
            } else if (response.is_processing === false) {
                iwbvelBackgroundProcessClearCompleteMessage();
                if (jQuery('#iwbvel-float-side-modal-variations-bulk-edit:visible').length) {
                    jQuery('.iwbvel-tab-item[data-content="add-variations"]').trigger('click');
                    let ids = [];
                    jQuery('input.iwbvel-check-item:checkbox:checked').each(function () {
                        if (jQuery(this).attr('data-item-type') !== 'variation') {
                            ids.push(jQuery(this).val())
                        }
                    });
                    iwbvelReloadTable(ids);
                } else {
                    iwbvelReloadTable(productIds);
                }

                setTimeout(function () {
                    iwbvelCloseModal();
                    iwbvelLoadingProcessingSuccess('Your changes have been applied');
                    if (jQuery('#iwbvel-float-side-modal-variations-bulk-edit:visible').length) {
                        jQuery('.iwbvel-variations-reload-table').trigger('click');
                    }
                }, 10);
            } else {
                if (!jQuery('.iwbvel-processing-loading:visible').length) {
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, { total: response.total_tasks, completed: response.completed_tasks }, response.remaining_time);
                } else {
                    if (response.total_tasks && response.completed_tasks) {
                        jQuery('.iwbvel-processing-loading span[data-type="tasks"]').show();
                        jQuery('.iwbvel-processing-loading span[data-type="tasks"]').find('[data-type="total"]').text(response.total_tasks);
                        jQuery('.iwbvel-processing-loading span[data-type="tasks"]').find('[data-type="completed"]').text((response.completed_tasks > 0) ? "+" + response.completed_tasks : response.completed_tasks);
                    }

                    if (response.remaining_time) {
                        jQuery('#iwbvel-processing-loading').find('[data-type="time_remaining"]').find('[data-type="time"]').text(response.remaining_time);
                        jQuery('#iwbvel-processing-loading').find('[data-type="time_remaining"]').show();
                    }
                }

                setTimeout(function () {
                    if (!response.is_force_stopped) {
                        iwbvelIsProcessing(productIds);
                    }
                }, 3000);
            }
        },
        error: function () {
        }
    });
}

function iwbvelBackgroundProcessClearCompleteMessage() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_background_process_clear_complete_message',
            nonce: IWBVEL_DATA.ajax_nonce
        },
        success: function () {
            //
        },
        error: function () {
            //
        }
    });
}

function iwbvelStopProcessCheck() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_is_processing',
            nonce: IWBVEL_DATA.ajax_nonce
        },
        success: function (response) {
            if (response.is_processing === false) {
                iwbvelBackgroundProcessClearCompleteMessage();
                iwbvelReloadTable();
                setTimeout(function () {
                    iwbvelLoadingProcessingSuccess('Stopped');
                    if (response.total_tasks && response.completed_tasks) {
                        jQuery('.iwbvel-processing-loading span[data-type="tasks"]').show();
                        jQuery('.iwbvel-processing-loading span[data-type="tasks"]').find('[data-type="total"]').text(response.total_tasks);
                        jQuery('.iwbvel-processing-loading span[data-type="tasks"]').find('[data-type="completed"]').text(response.completed_tasks);
                    }
                    iwbvelHistoryFilter(null, false);
                }, 500);
            } else {
                setTimeout(function () {
                    iwbvelStopProcessCheck();
                }, 3000);
            }
        },
        error: function () {
        }
    });
}

function iwbvelBackgroundProcessClearTasksCount() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_background_process_clear_tasks_count',
            nonce: IWBVEL_DATA.ajax_nonce
        },
        success: function () {
        },
        error: function () {
        }
    });
}

function iwbvelBackgroundProcessingCheck() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_is_processing',
            nonce: IWBVEL_DATA.ajax_nonce
        },
        success: function (response) {
            if (response.is_processing === true) {
                if (response.is_force_stopped) {
                    iwbvelStopProcessCheck()
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.stopping, false);
                } else {
                    iwbvelIsProcessing();
                    iwbvelLoadingProcessingStart(IWBVEL_DATA.background_process.loading_messages.processing, true, { total: response.total_tasks, completed: response.completed_tasks });
                }
            }
            if (response.complete_message && response.complete_message.message) {
                iwbvelLoadingProcessingComplete(response.complete_message.message, response.complete_message.icon);
                iwbvelBackgroundProcessClearCompleteMessage();
            }
        },
        error: function () {
        }
    });
}

function iwbvelBackgroundProcessForceStop() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: 'post',
        dataType: 'json',
        data: {
            action: 'iwbvel_background_process_force_stop',
            nonce: IWBVEL_DATA.ajax_nonce
        },
        success: function (response) {
            if (response.success === true) {
                iwbvelStopProcessCheck()
            }
        },
        error: function () {
        }
    });
}