jQuery(function ($) {

    var popup = false;
    $('.add-receiver').on('click', function (e) {
        e.preventDefault();
        var modal = wp.template('yith-payouts-receiver-modal-content');


        modal = $(modal({user_id: ''}));

        popup = yith.ui.modal(
            {
                'width': 450,
                'title': payouts_admin.receiver_popup.new_title,
                'content': modal,
                'footer': payouts_admin.receiver_popup.footer,
                'scrollContent': true,
                'classes': {
                    'footer': 'yith-payouts-save-receiver',
                },
                allowClosingWithEsc: true,
                closeWhenClickingOnOverlay: true

            });
        $(document.body).trigger('wc-enhanced-select-init');
        $(document.body).trigger('yith-framework-enhanced-select-init');
        $(document).trigger('yith_fields_init');
    });
    $(document).on('click', '.customer-navigation a', function (e) {
        e.preventDefault();
        var trigger = $(this),
            wrap = trigger.closest('.receiver-customer-wrapper'),
            dest = wrap.find(trigger.attr('href'));

        trigger.addClass('current').siblings().removeClass('current');
        dest.fadeIn().siblings(':not( .customer-navigation, #payment-info )').hide();
    });
    $(document).on('click', '.set-password', function (e) {
        e.preventDefault();
        $(this).hide().next().fadeIn();
    });
    $(document).on('click', '.yith-payout-edit-receiver', function (e) {
        e.preventDefault();
        var user = $(this).data('user'),
            modal = wp.template('yith-payouts-receiver-modal-content');

        user = user.split(',');
        var data = {
            index: user[0],

            paypal_email: user[2],
            commission_rate: user[3]
        };

        modal = $(modal(data));
        modal.find('#yith_payouts_search_user').append('<option value="' + user[1] + '" selected="selected">' + user[4] + '</option>').trigger('change');
        popup = yith.ui.modal(
            {
                'width': 500,
                'title': payouts_admin.receiver_popup.edit_title,
                'content': modal,
                'footer': payouts_admin.receiver_popup.footer,
                'scrollContent': true,
                'classes': {
                    'footer': 'yith-payouts-save-receiver',
                },
                allowClosingWithEsc: true,
                closeWhenClickingOnOverlay: true
            });
        $(document.body).trigger('wc-enhanced-select-init');
        $(document.body).trigger('yith-framework-enhanced-select-init');
        $(document).trigger('yith_fields_init');
    });
    $(document).on('click', '.receiver-modal-submit', function (e) {
        e.preventDefault();
        var paypal_email = $('#customer_paypal_email'),
            commission_rate = $('#customer_commission_rate'),
            data = {
                paypal_email: paypal_email.val(),
                commission_rate: commission_rate.val()
            };

        if ($('#create-customer').is(':visible')) {
            data.user_id = -1;
            data.new_customer_first_name = $('#new_customer_first_name').val();
            data.new_customer_last_name = $('#new_customer_last_name').val();
            data.new_customer_username = $('#new_customer_username').val();
            data.new_customer_email = $('#new_customer_email').val();
            if ($('#create-customer').find('.password-field-wrap').is(':visible')) {
                data.new_customer_password = $('#new_customer_generate_password').val();
            }
        } else {
            data.user_id = $('#yith_payouts_search_user').val();
        }
        data.action = payouts_admin.actions.save_receiver;
        data.security = payouts_admin.nonces.save_receiver;

        $.ajax({

            type: 'POST',
            url: payouts_admin.admin_url,
            data: data,
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    location.reload();
                } else {
                    var message = response.data.message,
                        field_id = response.data.field,
                        field = $('#' + field_id);
                    field.addClass('field-error');
                    if (!field.parent().find('span.error-message').length) {
                        field.parent().append('<span class="error-message"></span>');
                    }
                    field.parent().find('span.error-message').html(message);
                }
            }
        });
    });
    $('.add-payouts').on('click', function (e) {
        e.preventDefault();

        var modal_content = payouts_admin.generator_modal.content;
        modal_content = $(modal_content).clone();

        popup = yith.ui.modal(
            {
                'width': 600,
                'title': payouts_admin.generator_modal.title,
                'content': modal_content,
                'scrollContent': true,

            });
    });

    $(document).on('click', '#payout_upload_button', function (e) {
        e.preventDefault();
        $('#yith-upload').click();
    });

    $(document).on('change', '#yith-upload', function (e) {
        var fileName = this.files[0].name,
            fileNameCont = $('#payout_filename_contanier');
        fileNameCont.find('.filename').text(fileName);
        fileNameCont.css({display:'flex'});
        $('#payout_upload_button').hide();
        $('.yith-payouts-generator-modal').find('.move-step').removeClass('disabled');
    });
    $(document).on('click', '.payout_remove_file',function (e){
       e.preventDefault();
       var   fileNameCont = $('#payout_filename_contanier');

        fileNameCont.find('.filename').text('');
        fileNameCont.css({display:'none'});
        $('#payout_upload_button').show();
        $('.yith-payouts-generator-modal').find('.move-step').addClass('disabled');
    });
    $( document ).on( 'submit', '#yith-payouts-generator', function( e ){
        e.preventDefault();

        var originalFormData = new FormData(document.getElementById("yith-payouts-generator")),
            file = originalFormData.get('file'),
            delimiter = originalFormData.get('payout_csv_delimiter'),
            formDataToSend = new FormData();


        formDataToSend.set('file', file);
        formDataToSend.set('delimiter', delimiter);
        formDataToSend.set( 'action', payouts_admin.actions.generate_payouts );
        formDataToSend.set( 'security', payouts_admin.nonces.generate_payouts );
        if ( file && file.size ) {

            $("#yith-payouts-generator").block({
                message: null,
                overlayCSS: {
                    background: '#fff',
                    opacity: 0.6
                }
            });
            $.ajax( {
                type       : "POST",
                data       : formDataToSend,
                cache      : false,
                contentType: false,
                processData: false,
                url        : payouts_admin.admin_url,
                success    : function ( response ) {
                    $("#yith-payouts-generator").unblock();
                    popup.close();
                    location.reload();
                }
            } );
        }
    });

    var message = $('#yith-payouts-success-message'),
        error  = $('#yith-payouts-error-message');

    if( message.length){
        message.addClass('yith-plugin-fw-animate__appear-from-top').show();
    }
    if( error.length){
        error.addClass('yith-plugin-fw-animate__appear-from-top').show();
    }
    if( $(document).find('.yith-payouts-list-table').length ){
        $('input, textarea, select').on('click', function () {
            window.onbeforeunload = '';
        });
    }
});