jQuery(document).ready(function () {
 
    
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl, { container: ".elex-multi-vendor-for-woocommerce-wrap" });
    });
// Target the refund amount input field
var refundAmountInput = jQuery('input#refund_amount');

// Disable the input field
refundAmountInput.prop('disabled', true);
    jQuery(".elex-multi-vendor-for-woocommerce-refund-process-btn").prop('disabled', true);

    jQuery(".elex-multi-vendor-for-woocommerce-order-add-filter-open-btn").click(function () {
        var status = jQuery(this).attr("data-attr-filter");
        jQuery("#elex-multi-vendor-for-woocommerce-order-add-filter").addClass("active");
        jQuery("#elex-multi-vendor-for-woocommerce-order-add-filter").find("#elex_mv_filter_status").val(status);
    });
    jQuery(".elex-multi-vendor-for-woocommerce-order-add-filter-close-btn").click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-order-add-filter").removeClass("active");
    });
    jQuery('#elex-multi-vendor-for-woocommerce-order-dertail-expand-collapse-btn').on('click', function() {
        var text = jQuery('#elex-multi-vendor-for-woocommerce-order-dertail-expand-collapse-btn').text();
        if (text === "Expand") {
            jQuery(this).html('Collapse');
        } else {
            jQuery(this).text('Expand');
        }
    });
    
    jQuery(".elex-multi-vendor-for-woocommerce-order-add-export-open-btn").click(function () {
        var status = jQuery(this).attr("data-attr-filter");
        jQuery("#elex-multi-vendor-for-woocommerce-order-add-export").addClass("active");
        jQuery("#elex-multi-vendor-for-woocommerce-order-add-export").find("#elex_mv_order_status").val(status);

    });
    jQuery(".elex-multi-vendor-for-woocommerce-order-add-export-close-btn").click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-order-add-export").removeClass("active");
    });
   
    jQuery(".elex-multi-vendor-for-woocommerce-order-change-status-open-btn").click(function () {
        jQuery("#elex-multi-vendor-for-woocommerce-order-change-status").addClass("active");
        var ChangeStatusForm = jQuery('#elex-multi-vendor-for-woocommerce-order-change-status');
        ChangeStatusForm .find(".elex_mv_current_status").val(jQuery(this).attr('data-attr-status'));
        ChangeStatusForm .find(".elex_mv_current_status").attr("disabled", false) 
        ChangeStatusForm .find(".elex_change_status_order_id").val(jQuery(this).attr('data-attr-id'))

    });

    // change order status
    jQuery('#elex-multi-vendor-for-woocommerce-change-status-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){
                location.reload();
        })
    });


    //Bulk  action
    jQuery(".elex_mv_order_bulk_action").click(function () {
        var checkedIds = jQuery(".elex_mv_order_check:checked").map(function () {
            return this.id;
        }).toArray();
        if( checkedIds.length !== 0){
            jQuery("#elex_mv_order_bulk_action").val(checkedIds);
        }

        var id = checkedIds;
        var status = jQuery(".elex_mv_bulk_status").val();

        jQuery.ajax({
            url: elex_mv_admin_ajaxurl_object.ajax_url,
            type: 'POST',
            data: {
                action: "elex_mv_change_status",
                nonce: elex_mv_admin_ajaxurl_object.nonce,
                order_id:id,
                status:status,
            },
            enctype: 'text/plain',
            success: function () {
                location.reload();
            }
    
        })
     
    });


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

    //search order
    jQuery(".elex_mv_search_order").click(function() {
        search_val = jQuery(".elex_mv_search_order_data").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_order_data").val(search_val);
    });


    jQuery("#elex_mv_search_order_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);
    })
    

    jQuery(".elex-multi-vendor-for-woocommerce-order-detail-refund-btn").click(function() {
        jQuery("#elex-multi-vendor-for-woocommerce-order-detail-refund").addClass("active");
    });

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

    jQuery(document).on( "change keyup", ".refund_line_item_quantity", function(){

        var total_price = 0;
        var total_tax = 0;
        var total_refund_amount=0;
        
        order_id = jQuery(this).data('order_id');
        
        tax_item_id = jQuery(this).data('tax_item_id');

        price_item = jQuery(`[name="line_item_value[` + order_id + `]"]`).val();

        tax_item = jQuery(`[name="line_item_tax[` + order_id + `]"]`).val();

        calc_item_value_to_refund = price_item * jQuery(this).val(); 
        calc_item_tax_to_refund = tax_item * jQuery(this).val(); 

    

        jQuery(`[name="refund_line_item_price[` + order_id + `]"]`).val(calc_item_value_to_refund);
        jQuery(`[name*="refund_line_item_tax[` + order_id + `]"]`).val(calc_item_tax_to_refund);

        jQuery('.refund_line_item_tax').each(function(i, obj) {
            total_tax += isNaN(parseFloat( jQuery(this).val() )) ? 0 : parseFloat( jQuery(this).val() );
        });


        jQuery('.refund_line_item_price').each(function(i, obj) {
            total_price += isNaN(parseFloat( jQuery(this).val() )) ? 0 : parseFloat( jQuery(this).val() );
        });
        total_refund_amount = total_price + total_tax;
        jQuery("[name='total_refund_amount']").val(total_refund_amount);
        jQuery(".elex-multi-vendor-for-woocommerce-refund-process-btn").text("Refund " + total_refund_amount + " Manually");
        jQuery(".elex-multi-vendor-for-woocommerce-order-refund-amount").text(total_refund_amount);

        jQuery(".elex-multi-vendor-for-woocommerce-refund-process-btn").prop('disabled', false);

    })

    jQuery(document).on( "change keyup", ".refund_line_item_price", function(){
    
        var total_price = 0;
        var total_tax = 0;
        var total_refund_amount=0;

        jQuery('.refund_line_item_tax').each(function(i, obj) {
            total_tax += isNaN(parseFloat( jQuery(this).val() )) ? 0 : parseFloat( jQuery(this).val() )  ;
        });
        jQuery('.refund_line_item_price').each(function(i, obj) {
            total_price += isNaN(parseFloat( jQuery(this).val() )) ? 0 : parseFloat( jQuery(this).val() );
        });

        total_refund_amount = total_price + total_tax;

        jQuery("[name='total_refund_amount']").val(total_refund_amount);
        jQuery(".elex-multi-vendor-for-woocommerce-refund-process-btn").text("Refund " + total_refund_amount + " Manually");
        jQuery(".elex-multi-vendor-for-woocommerce-order-refund-amount").text(total_refund_amount);

        jQuery(".elex-multi-vendor-for-woocommerce-refund-process-btn").prop('disabled', false);


    })

    jQuery(document).on( "change keyup", ".refund_line_item_tax", function(){
    
        var total_price = 0;
        var total_tax = 0;
        var total_refund_amount=0;

        jQuery('.refund_line_item_tax').each(function(i, obj) {
            total_tax += isNaN(parseFloat( jQuery(this).val() )) ? 0 : parseFloat( jQuery(this).val() );
        });
        jQuery('.refund_line_item_price').each(function(i, obj) {
            total_price += isNaN(parseFloat( jQuery(this).val() )) ? 0 : parseFloat( jQuery(this).val() );
        });

        total_refund_amount = total_price + total_tax;
        jQuery("[name='total_refund_amount']").val(total_refund_amount);
        jQuery(".elex-multi-vendor-for-woocommerce-refund-process-btn").text("Refund " + total_refund_amount + " Manually");
        jQuery(".elex-multi-vendor-for-woocommerce-order-refund-amount").text(total_refund_amount);
        jQuery(".elex-multi-vendor-for-woocommerce-refund-process-btn").prop('disabled', false);


    })

  
    jQuery(".elex-multi-vendor-for-woocommerce-refund-process-btn, .elex-multi-vendor-for-woocommerce-do-api-refund").click(function(){


        var additem = document.getElementById('elex_mv_refund_item_toast');
        if( jQuery( this ).is( '.elex-multi-vendor-for-woocommerce-do-api-refund' ) ){
            jQuery("#elex_mv_refund_item_toast_confirm").attr('api-refund', true );
        }
        var toast = new bootstrap.Toast(additem);
        toast.show();

    });

 



    jQuery("#elex_mv_refund_item_toast_confirm").click(function(){

        var link = elex_mv_admin_ajaxurl_object.ajax_url;
		var formData;
		link += "?action=elex_mv_refund_line_items";
		var formData = new FormData(document.getElementById('elex_mv_vendor_order_refund_form'));

        if(jQuery(this).attr('api-refund') === "true" ){
            formData.append('api_refund', true);
        }
		formData.append('nonce', elex_mv_coupon_ajaxurl_object.nonce);
        jQuery.ajax({
            url: link,
            type: 'POST',
            data: formData,
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false,
            success: function (result) {
               if(result.success){
                jQuery("#elex_mv_refund_successful_toast_msg").text("Refunded Successfully");
                var additem = document.getElementById('elex_mv_refund_successful_toast');
                var toast = new bootstrap.Toast(additem);
                toast.show();
                    setTimeout(function(){
                     window.location.reload();
                  }, 3000);  
               }else{
                jQuery(".elex_mv_refund_successful_toast_svg").html('');

                jQuery("#elex_mv_refund_successful_toast_msg").text("Refund Unsuccessful");
                var additem = document.getElementById('elex_mv_refund_successful_toast');
                var toast = new bootstrap.Toast(additem);
                toast.show();
                setTimeout(function(){
                    window.location.reload();
                 }, 3000);  
               }

          
            },
            error: function(s,e){

                jQuery(".elex_mv_refund_successful_toast_svg").html('');
               jQuery("#elex_mv_refund_successful_toast_msg").text("Refund Unsuccessful");
               var additem = document.getElementById('elex_mv_refund_successful_toast');
               var toast = new bootstrap.Toast(additem);
               toast.show();
               setTimeout(function(){
                window.location.reload();
             }, 3000);  
            }

        });

    })

});