
jQuery(document).ready(function () {


    ///Generate coupon popup
    jQuery(document).click(function (e) {
        if (jQuery(e.target).is('.elex-multi-vendor-for-woocommerce-generate-coupon-btn ,.elex-multi-vendor-for-woocommerce-popup-content *'));
        else jQuery("#elex-multi-vendor-for-woocommerce-coupon-setting").removeClass("active");
    });
    jQuery(".elex-multi-vendor-for-woocommerce-generate-coupon-btn").click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-coupon-setting").addClass("active");
    });


    ///Edit coupon popup
    jQuery(document).click(function (e) {
        if (jQuery(e.target).is('.elex-multi-vendor-for-woocommerce-coupon-open-edit-btn ,.elex-multi-vendor-for-woocommerce-popup-content *'));
        else jQuery("#elex-multi-vendor-for-woocommerce-edit-coupon-setting").removeClass("active");
    });
    jQuery(".elex-multi-vendor-for-woocommerce-coupon-open-edit-btn").click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-edit-coupon-setting").addClass("active");
    });
    jQuery('.elex-multi-vendor-for-woocommerce-edit-coupon-popup-close').click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-edit-coupon-setting").removeClass("active");

    });
    // on click outside popup close popup window
    jQuery(".elex-multi-vendor-for-woocommerce-coupon-popup-close").on('click', function () {
        jQuery("#elex-multi-vendor-for-woocommerce-coupon-setting").removeClass("active"); jQuery(document).ready(function () {
            jQuery("#elex-multi-vendor-for-woocommerce-edit-coupon-setting").removeClass("active");
        });
    });

    /// Hide and show excllude category and product
    jQuery(".elex-multi-vendor-for-woocommerce-coupons-product-category").hide();
    jQuery(".elex-multi-vendor-for-woocommerce-coupons-exclude-product").hide();

    jQuery(".elex-multi-vendor-for-woocommerce-coupons-exclude-product-btn").click(function () {
        jQuery(".elex-multi-vendor-for-woocommerce-coupons-exclude-product").show();
        jQuery(this).hide();
    });

    jQuery(".elex-multi-vendor-for-woocommerce-coupons-product-category-btn").click(function () {
        jQuery(".elex-multi-vendor-for-woocommerce-coupons-product-category").show();
        jQuery(this).hide();
    });

    //Search coupon
    jQuery('#elex-search-coupon-vendor-button').click(function () {
        search_val = jQuery("#elex-search-coupon-vendor").val();
        const u = new URL(location);
        let params = new URLSearchParams(u.search);
        if (params.has('search_term')) {
            u.searchParams.set('search_term', search_val)
        } else {
            u.searchParams.append('search_term', search_val)
        }
        window.location.replace(u);
        jQuery("#elex-search-coupon-vendor").val(search_val);

    });

    jQuery("#elex-search-coupon-vendor-button-cross").click(function () {
        const u = new URL(location);
        let params = new URLSearchParams(u.search);

        if (params.has('search_term')) {
            u.searchParams.delete('search_term')
        }
        window.location.replace(u);
    })
    //Delete coupon in bulk 
    jQuery('.elex-delete-coupon-bulk-action').click(function () {

        var checkedIds = jQuery(".elex-delete-bulk-chk:checked").map(function () {
            return this.id;
        }).toArray();

        if (checkedIds.length !== 0) {
            var additem = document.getElementById('elex_delete_coupon')
            jQuery("#elex-multi-vendor-for-woocommerce-delete-coupon-confirm-btn").val(checkedIds);
            var toast = new bootstrap.Toast(additem)
            toast.show();
        }

    });

    ///product search field 
    jQuery('.mv-coupon-product, .mv-coupon-exclude-product').select2({
        minimumInputLength: 3,
        ajax: {
            url: elex_mv_coupon_ajaxurl_object.ajax_url,
            type: 'POST',

            data: function (params) {
                var query = {
                    search: params.term,
                    action: 'elex_mv_coupon_search_products',
                    _ajax_nonce: elex_mv_coupon_ajaxurl_object.nonce,
                }
                return query;
            },
            processResults: function (data) {
                return {
                    results: data.data,

                };
            }

        }

    });

    //category search field 
    jQuery('.mv-coupon-product-category, .mv-coupon-exclude-product-category').select2({
        minimumInputLength: 3,
        ajax: {
            url: elex_mv_coupon_ajaxurl_object.ajax_url,
            type: 'POST',
            data: function (params) {
                var query = {
                    search: params.term,
                    action: 'elex_mv_coupon_search_categories',
                    _ajax_nonce: elex_mv_coupon_ajaxurl_object.nonce,
                }
                return query;
            },
            processResults: function (data) {
                return {
                    results: data.data,
                };
            }

        }

    });

    // vendor field in admin coupon
    jQuery('.elex_mv_vendors_input').select2({
        minimumInputLength: 3,
        ajax: {
            url: elex_mv_coupon_ajaxurl_object.ajax_url,
            type: 'GET',
            data: function (params) {
                var query = {
                    vendor_search: params.term,
                    action: 'elex_mv_api_endpoint_for_vendors',
                    nonce: elex_mv_coupon_ajaxurl_object.nonce,
                }
                return query;
            },
            processResults: function (data) {
                return {
                    results: data.data.map(function (store) {
                        return {
                            text: store.post_title,
                            id: store.ID,
                        }
                    }),
                };
            }

        }
    });

    //Create and save coupon ajax call
    jQuery(document).off('submit.elexcoupon').on('submit.elexcoupon', '#elex-multi-vendor-for-woocommerce-coupon-add-form, #elex-multi-vendor-for-woocommerce-coupon-save-form', function (e) {
        e.preventDefault();
        const form_data = jQuery(this).serialize();
        jQuery.post(elex_mv_coupon_ajaxurl_object.ajax_url, form_data, function (response) {
            if (response.success) {

                var additem = jQuery('.elex_coupon_generate_toast');
                var additemc = jQuery('.elex_coupon_generate_toast_c');

                jQuery("#toast_message_mv").html('Coupon Generated Successfully');
                jQuery("#edit_toast_message_mv").html('Coupon Data Saved Successfully');
                var toast = new bootstrap.Toast(additem);
                var toastc = new bootstrap.Toast(additemc);

                toast.show();
                toastc.show();

                setTimeout(function () {
                    window.location.reload();
                }, 2000);
            } else {
                error_obj = response.data;
                for (const key in error_obj) {

                    function loop_for_html_error(obj) {
                        string = '';
                        for (var i = 0; i < obj.length; i++) {
                            string += ` ${obj[i]}`;
                        }
                        return string;
                    }

                    if (error_obj[key] == null) {
                        continue;
                    } else {
                        jQuery('#elex_' + key + '_field_error').html('<div style="color:red;"  >' + loop_for_html_error(error_obj[key]) + '</div>');
                    }
                }
            }
        })

    });

});


//Edit coupon 
function editFormData(id) {

    jQuery.ajax({
        url: elex_mv_coupon_ajaxurl_object.ajax_url,
        type: 'POST',
        data: {
            action: "elex_mv_coupon_edit",
            _ajax_nonce: elex_mv_coupon_ajaxurl_object.nonce,
            id: id,
        },
        enctype: 'multipart/form-data',
        success: function (result) {
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find('.save_coupon_id').val(id);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-edit-title-field").val(result.data.title);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-description-field").val(result.data.description);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-code-field").val(result.data.code);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-discount-type-field").val(result.data.discount_type);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-valid-from-field").val(result.data.valid_from);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-valid-till-field").val(result.data.valid_till);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-amount-field").val(result.data.coupon_amount);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-min-cart-spending-field").val(result.data.min_cart_spending);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-max-cart-spending-field").val(result.data.max_cart_spending);
            if (result.data.individual_coupon_use) {
                jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-individual-coupon-use-field").attr('checked', true)
            } else {
                jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-individual-coupon-use-field").attr('checked', false)
            }
            if (result.data.exclude_on_sale_item) {
                jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-exclude-sale-item-field").attr('checked', true)
            } else {
                jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-exclude-sale-item-field").attr('checked', false)
            }

            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".mv-coupon-product").html('').val(null).trigger("change");
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".mv-coupon-exclude-product").html('').val(null).trigger("change");
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".mv-coupon-product-category").html('').val(null).trigger("change");
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".mv-coupon-exclude-product-category").html('').val(null).trigger("change");
            jQuery.each(result.data.products, function (index, item) {
                var option = new Option(item.text, item.id, true, true);
                jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".mv-coupon-product").append(option).trigger('change');
            });

            jQuery.each(result.data.exclude_product, function (index, item) {
                var option = new Option(item.text, item.id, true, true);
                jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".mv-coupon-exclude-product").append(option).trigger('change');
            });


            jQuery.each(result.data.product_category, function (index, item) {
                var option = new Option(item.text, item.id, true, true);
                jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".mv-coupon-product-category").append(option).trigger('change');
            });


            jQuery.each(result.data.exclude_product_category, function (index, item) {
                var option = new Option(item.text, item.id, true, true);
                jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".mv-coupon-exclude-product-category").append(option).trigger('change');
            });



            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-allowed-emails-field").val(result.data.allowed_emails);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-usage-limit-per-coupon-field").val(result.data.usage_limit_per_coupon);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-usage-limit-x-items").val(result.data.usage_limit_x_items);
            jQuery('#elex-multi-vendor-for-woocommerce-edit-coupon-setting').find(".elex-coupon-usage-limit-per-user-field").val(result.data.usage_limit_per_user);
        },


    });
}

//Delete coupon
function deleteCouponFunc(id) {
    var additem = document.getElementById('elex_delete_coupon')
    jQuery("#elex-multi-vendor-for-woocommerce-delete-coupon-confirm-btn").val(id);
    var toast = new bootstrap.Toast(additem);
    toast.show();
}

//Show popup for confirmation before delete
function confirmDelete() {
    var id = jQuery("#elex-multi-vendor-for-woocommerce-delete-coupon-confirm-btn").val();
    jQuery.ajax({
        url: elex_mv_coupon_ajaxurl_object.ajax_url,
        type: 'POST',
        data: {
            action: "elex_mv_coupon_delete",
            _ajax_nonce: elex_mv_coupon_ajaxurl_object.nonce,
            id: id,
        },
        enctype: 'text/plain',
        success: function () {
            location.reload();
        }

    })
}


validation_for_forms_func('#elex-coupon-code-field', /^[A-Za-z0-9][ A-Za-z0-9_]{0,29}$/, '#elex_code_field_error', 'Enter Coupon Code');
validation_for_forms_func('#elex-coupon-amount-field', /^[0-9]*$/, '#elex_coupon_amount_field_error', 'Enter Coupon Amount');
validation_for_forms_func('#elex-edit-coupon-code-field', /^[A-Za-z0-9][ A-Za-z0-9_]{0,29}$/, '#elex_edit_code_field_error', 'Enter Coupon Code');
validation_for_forms_func('#elex-edit-coupon-amount-field', /^[0-9]*$/, '#elex_edit_coupon_amount_field_error', 'Enter Coupon Amount');

function validation_for_forms_func(id_for_input_element, regex_for_string, id_for_error_element, error_string) {
    jQuery(id_for_input_element).keyup(function () {
        const regex = regex_for_string;

        if (!regex.test(this.value)) {
            jQuery(id_for_error_element).html(`<div class="text-danger">${error_string}</div>`);
        } else {
            jQuery(id_for_error_element).html('');

        }
    });
}
