jQuery(function() {
    let w2pshop_product_data_tabs = jQuery('#w2pshop_product_data_tabs');
    let w2pshop_private_users_element = jQuery('select#w2pshop_private_users');

    w2pshop_product_data_tabs.tabs();
    w2pshop_product_data_tabs.removeClass('ui-widget ui-widget-content');
    w2pshop_private_users_element.css('width', '350px').selectWoo({
        maximumSelectionSize: 25,
    });

    w2pshop_private_users_element.on('select2:open', function (e) {
        setTimeout(function() {
            let input = jQuery('.select2-container--open .select2-search--dropdown .select2-search__field');
            if (input.length === 0) {
                input = jQuery('.select2-container--open .select2-search--inline .select2-search__field');
            }

            input.on('input', function() {
                W2PShopCommon.send_ajax_request(w2pshopPanelData.ajaxurl,
                    {
                        action: 'w2pshop_get_customer_list',
                        search_str: jQuery(this).val(),
                        security: w2pshopPanelData.nonce
                    },
                    {},
                    function (response) {
                        jQuery('select#w2pshop_private_users option:not(:selected)').remove();
                        jQuery.each( response, function( key, value ) {
                            let newOption = new Option(value.user_email, value.ID, false, false);
                            if (jQuery('select#w2pshop_private_users option[value="' + value.ID + '"]').length <= 0) {
                                jQuery('select#w2pshop_private_users').append(newOption).change();
                            }
                        });
                    }
                );
            });
        }, 0);
    });
});