jQuery(document).ready(function () {
    jQuery(".elex-multi-vendor-for-woocommerce-settlement-show-btn").click(function () {

        var id = jQuery(this).attr("data-attr-id");
        jQuery(this).parents(".elex-multi-vendor-for-woocommerce-settlement").find(".elex-multi-vendor-for-woocommerce-settlement-hide-btn").removeClass("d-none");
        jQuery(this).parents(".elex-multi-vendor-for-woocommerce-settlement").find(".elex-multi-vendor-for-woocommerce-settlement-list").removeClass("d-none");
        if (!$.fn.DataTable.isDataTable(jQuery(this).parents(".elex-multi-vendor-for-woocommerce-settlement").find('.elex-multi-vendor-for-woocommerce-settlement-table'))) {
            var table = jQuery(this).parents(".elex-multi-vendor-for-woocommerce-settlement").find('.elex-multi-vendor-for-woocommerce-settlement-table').DataTable(
                {

                    "columns": [
                        { data: "settlement_date", name: "settlement_date", orderSequence: ['desc'] },
                        { data: "settlement_mode", name: "settlement_mode" },
                        { data: "transaction_id", name: "transaction_id" },
                        { data: "vendor_amount", name: "vendor_amount" },
                        { data: "note", name: "note" },
                        // {data:"note",name:"note"}

                    ],
                    "pageLength": 10,
                    "processing": true,
                    "serverSide": true,
                    "ajax": {
                        url: ajaxurl,
                        method: "post",
                        data: function (d) {
                            d.id = id;
                            d.action = "elex_mv_settlement_history_data";
                            d.nonce = elex_mv_admin_ajaxurl_object.nonce;
                        }
                    }
                });
            // Disable "Previous" button on initial page
            if (table.page.info().page === 0) {
                jQuery('.paginate_button.previous').addClass('disabled');
            } else {
                jQuery('.paginate_button.previous').removeClass('disabled');
            }

            // Disable "Next" button on last page
            if (table.page.info().page === (table.page.info().pages - 1)) {
                jQuery('.paginate_button.next').addClass('disabled');
            } else {
                jQuery('.paginate_button.next').removeClass('disabled');
            }

        }
        jQuery(this).addClass("d-none");
    });

    jQuery(".elex-multi-vendor-for-woocommerce-settlement-hide-btn").click(function () {
        jQuery(this).closest(".elex-multi-vendor-for-woocommerce-settlement").find(".elex-multi-vendor-for-woocommerce-settlement-show-btn").removeClass("d-none");
        jQuery(this).closest(".elex-multi-vendor-for-woocommerce-settlement").find(".elex-multi-vendor-for-woocommerce-settlement-list").addClass("d-none");
        jQuery(this).addClass("d-none");
    });

    // payment popup
    jQuery(".elex-multi-vendor-for-woocommerce-payment-popup-open-btn").click(function () {

        jQuery("#elex-multi-vendor-for-woocommerce-payment-popup").addClass("active");
        var paymentform = jQuery('#elex-multi-vendor-for-woocommerce-payment-popup');
        var currency = elex_mv_admin_ajaxurl_object.currency_symbol;


        paymentform.find(".elex-multi-vendor-for-woocommerce-payment-vendor-name").val(jQuery(this).attr('data-attr-vendor'));
        // paymentform.find(".elex-multi-vendor-for-woocommerce-payment-vendor-name").attr("disabled", true) 
        paymentform.find(".elex-multi-vendor-for-woocommerce-payment-commission-amount").val(jQuery(this).attr('data-attr-commission'));
        // paymentform.find(".elex-multi-vendor-for-woocommerce-payment-commission-amount").insertBefore('<p>'+ currency + '</p>');

        // paymentform.find(".elex-multi-vendor-for-woocommerce-payment-commission-amount").attr("disabled", true); 
        paymentform.find(".elex-multi-vendor-for-woocommerce-payment-settle-amount").val(jQuery(this).attr('data-attr-amount').trim());
        jQuery("<div class='fs-5'>" + currency + "</div>").insertBefore(".elex-multi-vendor-for-woocommerce-payment-settle-amount");

        paymentform.find(".elex_mv_payment_vendor_id").val(jQuery(this).attr('data-attr-id'));

    });

    jQuery('.elex-multi-vendor-for-woocommerce-payment-settlement-mode').on('change', function () {

        if (jQuery(this).val() == 'Manual') {
            jQuery('.elex-multi-vendor-for-woocommerce-payment-transaction-id-field').addClass('d-none');
            jQuery('.elex_mv-settle-amount').prop("disabled", false);

        } else if (jQuery(this).val() == 'PayPal') {

            jQuery('.elex-multi-vendor-for-woocommerce-payment-transaction-id-field').removeClass('d-none');
            jQuery('.elex_mv-settle-amount').prop("disabled", true);

        }
    });

    jQuery('.elex_mv-settle-amount').on('click', function () {
        jQuery(this).prop("disabled", true);
        jQuery("#elex-multi-vendor-for-woocommerce-payment-settlement-form").submit();

    });


    jQuery('input.elex-multi-vendor-for-woocommerce-payment-transaction-id-input').on('keyup', function (e) {
        jQuery('.elex_mv-settle-amount').prop("disabled", false);
    });


    jQuery(".elex-multi-vendor-for-woocommerce-payment-popup-close-btn").click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-payment-popup").removeClass("active");
        location.reload();
    });

    jQuery(".elex-multi-vendor-for-woocommerce-export-popup-open-btn").click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-export-popup").addClass("active");
    });

    jQuery(".elex-multi-vendor-for-woocommerce-export-popup-close-btn").click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-export-popup").removeClass("active");
    });

    jQuery('.js-example-basic-multiple').select2({
        theme: "classic",
        width: 'resolve'
    });

    jQuery('#elex-multi-vendor-for-woocommerce-payment-settlement-form').submit(function (e) {
        e.preventDefault();
        const form_data = jQuery(this).serialize();

        jQuery.post(elex_mv_admin_ajaxurl_object.ajax_url, form_data, function (response) {
            if (response.success) {
                location.reload();
            } 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_mv_payment_' + key + '_error').html('<div style="color:red;"  >' + loop_for_html_error(error_obj[key]) + '</div>');
                    }
                }
            }
        })
    });

    jQuery('.vendors_settlement_csv').select2({
        placeholder: "Select Vendor",
        minimumInputLength: 3,
        ajax: {
            url: elex_mv_admin_ajaxurl_object.ajax_url,
            type: 'POST',

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

                };
            }

        }

    });



    // jQuery(".elex_mv_search_vendor_payment").click(function() {
    //     search_val = jQuery(".elex_mv_search_vendor_name").val();
    //     // url_for_search = window.location.href.split('?')[0] + '?search_term=' + search_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_mv_search_vendor_name").val(search_val);
    // });



    jQuery("#elex_mv_search_admin_payments_vendor_name").select2({
        placeholder: "Search Vendor",
        minimumInputLength: 2,
        ajax: {
            url: elex_mv_coupon_ajaxurl_object.ajax_url,
            type: 'GET',

            data: function (params) {
                var query = {
                    vendor_search: params.term,
                    // status:'publish',
                    action: 'elex_mv_api_endpoint_for_vendors',
                    nonce: elex_mv_coupon_ajaxurl_object.nonce,
                }
                return query;
            },
            processResults: function (response) {
                return {
                    results: response.data.map(function (store) {
                        return {
                            text: store.post_title,
                            id: store.post_title,
                        }
                    }),

                };
            }

        }

    });

    jQuery("#elex_mv_search_vendor_payment_btn").click(function () {
        search_val = jQuery("#elex_mv_search_admin_payments_vendor_name").val();
        if (!search_val) {
            return;
        }
        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_mv_search_vendor_payment_cross_btn").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);
    })


    validation_for_payment_forms_func('#elex_mv_payment_settlement_amount', /^[0-9]+$/, '#elex_mv_payment_settlement_amount_error', 'Enter Settlement Amount');

    function validation_for_payment_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('');

            }
        });
    }
});