jQuery(function($){

    function validateForm(input_class) {
        var valid = true;
        input_class.each(function () {
            if ($(this).val() === '') {
                valid = false;
                return false;
            }
        });
        return valid;
    }

    function price_format(nStr) {
        nStr = parseFloat(nStr).toFixed(formipay.decimal_digits) + '';
        var x = nStr.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? formipay.decimal_symbol + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + formipay.thousand_separator + '$2');
        }
        return formipay.currency + ' ' + x1 + x2;
    }

    $('.product-price-row').find('td').html(price_format($('#product_price').val()));
    $('.formipay-payment-option-group:first-child').find('input').trigger('click');

    function calculate_fields() {

        var calc_field = $('.formipay-input-calculable');
        var button_text = $('.formipay-submit-button').data('button-text');

        $('table#formipay-review-order tr:not(.formipay-product-row)').remove();
   
        var price = parseInt($('#product_price').val());

        var total = price;
        var qty = parseInt($('.formipay-qty-input').val());
        var total = price * qty;

        $('tr.formipay-product-row').find('td').html(price_format(total));

        if(calc_field.length > 0){
            $.each(calc_field, function(o, p){
                var field_amount = 0;
                var value_badge = false;
                var badge_label = '';
                var qty_label = '';
                if($(p).hasClass('formipay-select')){
                    value_badge = true;
                    badge_label = $(p).find('option:selected').text();
                    field_amount = $(p).find('option:selected').attr('data-calc-value');
                }else if($(p).attr('type') == 'hidden'){
                    field_amount = $(p).attr('data-calc-value');
                }else{
                    if($(p).is(':checked')){
                        value_badge = true;
                        badge_label = $(p).siblings('span').text();
                        field_amount = $(p).attr('data-calc-value');
                    }
                }
                if(!field_amount){
                    field_amount = 0;
                }
                if($(p).hasClass('formipay-select')){
                    if(formipay.quantity_toggle == 'on' && $(p).find('option:selected').attr('data-qty-multiply') == 'yes'){
                        field_amount = parseFloat(field_amount) * parseInt(qty);
                        if(qty > 1){
                            qty_label = ' ✕ '+qty;
                        }
                    }
                }else{
                    if(formipay.quantity_toggle == 'on' && $(p).attr('data-qty-multiply') == 'yes'){
                        field_amount = parseFloat(field_amount) * parseInt(qty);
                        if(qty > 1){
                            qty_label = ' ✕ '+qty;
                        }
                    }
                }
                

                var label = '<span class="order-item">'+$(p).attr('data-label')+qty_label+'</span>';
                if(value_badge){
                    label += '<span class="formipay-value-badge">'+badge_label+'</span>';
                }

                if(field_amount > 0){
                    $('table#formipay-review-order').find('tbody').append(`
                        <tr class="formipay-item-row">
                            <th>`+label+`</th>
                            <td>`+price_format(field_amount)+`</td>
                        </tr>
                    `);
                }

                total = parseFloat(total) + parseFloat(field_amount);
            });

            $('table#formipay-review-order').find('tbody').append(`
                <tr class="formipay-total-row">
                    <td colspan="2"></td>
                </tr>
            `);

            if($('#formipay-shipping-cost').val() > 0){
                total = total + parseInt($('#formipay-shipping-cost').val());
                $('table#formipay-review-order').find('tbody').append(`
                    <tr class="formipay-shipping-row">
                        <th>Shipping</th>
                        <td>`+price_format($('#formipay-shipping-cost').val())+`</td>
                    </tr>
                `);
            }

            $('table#formipay-review-order').find('tbody').append(`
                <tr class="formipay-grand-total-row">
                    <th>Total</th>
                    <td>`+price_format(total)+`</td>
                </tr>
            `);
        }

        $('.formipay-submit-button').text(button_text+' - '+price_format(total));

    }

    calculate_fields();

    // PAGE BREAK
    var page_break = $('.formipay-page-break');
    if(page_break.length > 0){
        $.each( $('.formipay-field-group:not(.formipay-page-break)'), function(){
            var prev_page_break = $(this).prev('.formipay-page-break');
            $(this).appendTo(prev_page_break);
        } );
        var payment_page_break = $('.formipay-page-break.formipay-page-break-payment');
        $('.result-wrapper').appendTo(payment_page_break);
        $.each( page_break, function(index, page){
            if(index > 0){
                $(page).hide();
            }
            index = index + 1;
            $(page).addClass('formipay-page-'+index);
        });
        $('.formipay-page-break-payment .formipay-submit-button').appendTo('.formipay-bottom-pagination').css({
            'margin-left': 'unset',
            'margin-right': 'unset'
        }).hide();
    }
    var page_break_progress = $('.formipay-progress');
    if(page_break_progress.length > 0){
        // $(page_break_progress[0]).addClass('active');
        $.each(page_break_progress, function(index, page){
            if(index == 0){
                $(page).addClass('active');
            }
            index = index + 1;
            $(page).attr('data-page-number', index);
        });
    }

    $('.formipay-progress').on('click', function(){
        var page_number = $(this).attr('data-page-number');
        var inputs_in_page = $('.formipay-page-break:visible').find('.formipay-input');
        var valid_to_continue = check_page_input_invalid(inputs_in_page);
        
        if(valid_to_continue === false){
            return false;
        }

        if($('.formipay-page-'+page_number).hasClass('formipay-page-break-payment')){
            $('.formipay-page-break-next-button').hide();
            $('.formipay-page-break-next-button').siblings('.formipay-submit-button').show();
        }else{
            $('.formipay-page-break-next-button').show();
            $('.formipay-page-break-next-button').siblings('.formipay-submit-button').hide();
        }

        $('.formipay-progress').removeClass('active');
        $(this).addClass('active');
        $('.formipay-page-break').hide();
        $('.formipay-page-'+page_number).show();
    });

    function check_page_input_invalid(inputs){
        var invalid_input = 0;
        inputs.each(function(index, field) {
            var the_label = $(field).data('label');
            // $(field).removeAttr('style');
            $(field).removeClass('formipay-input-invalid')
            if (!$(field).is(':valid')) {
                // $(field).attr('style', 'border-color: #d93258!important;');
                $(field).addClass('formipay-input-invalid');
                $(field).siblings('.formipay-validate-field').remove();
                if ($(field).attr('type') == 'select' || $(field).attr('type') == 'radio' || $(field).attr('type') == 'checkbox') {
                    if ($(field).attr('type') == 'radio' || $(field).attr('type') == 'checkbox') {
                        if ($('[name="' + $(field).attr('name') + '"]:checked').length == 0) {
                            var notice_message = formipay.notice_empty_select_message;
                            $(field).parent().append('<p class="formipay-validate-field"><i class="bi bi-exclamation-circle"></i> '+notice_message.replace('{{field}}', the_label)+'</p>');
                            invalid_input ++;
                        }
                    } else if ($(field).attr('name').search('agreement') != -1) {
                        var notice_message = formipay.notice_empty_agreement_message;
                        $(field).parent().append('<p class="formipay-validate-field"><i class="bi bi-exclamation-circle"></i> '+notice_message.replace('{{field}}', the_label)+'</p>');
                        invalid_input ++;
                    } else {
                        var notice_message = formipay.notice_empty_select_message;
                        $(field).parent().append('<p class="formipay-validate-field"><i class="bi bi-exclamation-circle"></i> '+notice_message.replace('{{field}}', the_label)+'</p>');
                        invalid_input ++;
                    }
                } else {
                    var notice_message = formipay.notice_empty_text_message;
                    $(field).parent().append('<p class="formipay-validate-field"><i class="bi bi-exclamation-circle"></i> '+notice_message.replace('{{field}}', the_label)+'</p>');
                    invalid_input ++;
                }
            }
        }); 
        if(invalid_input > 0){
            return false;
        }
        return true;
    } 

    $('.formipay-page-break-next-button').on('click', function(e){
        var next_page = $('.formipay-page-break:visible').next('.formipay-page-break');
        var inputs_in_page = $('.formipay-page-break:visible').find('.formipay-input');
        
        var valid_to_continue = check_page_input_invalid(inputs_in_page);
        
        if(valid_to_continue === false){
            return false;
        }

        var active_progress = $('.formipay-progress.active');
        if(next_page.length > 0){
            active_progress.next('.formipay-progress').addClass('active');
            active_progress.removeClass('active');
            if(next_page.hasClass('formipay-page-break-payment')){
                // $(this).prop('disabled', true);
                $(this).hide();
                $(this).siblings('.formipay-submit-button').show();
            }
            $('.formipay-page-break:visible').hide();
            next_page.show();
            e.target.blur()
        }
        $('.formipay-page-break-prev-button').prop('disabled', false);
    });

    $('.formipay-page-break-prev-button').on('click', function(e){
        var prev_page = $('.formipay-page-break:visible').prev('.formipay-page-break');
        var active_progress = $('.formipay-progress.active');
        if(prev_page.length > 0){
            active_progress.prev('.formipay-progress').addClass('active');
            active_progress.removeClass('active');
            if(prev_page.is('.formipay-page-break:nth-child(2)')){
                $(this).prop('disabled', true);
            }
            $('.formipay-page-break-next-button').show();
            $('.formipay-page-break-next-button').siblings('.formipay-submit-button').hide();
            $('.formipay-page-break:visible').hide();
            prev_page.show();
            e.target.blur()
        }
        $('.formipay-page-break-next-button').prop('disabled', false);
    });

    $('.formipay-input, .formipay-qty-input').on('change', function(){
        calculate_fields();
    });

    $(document).on('click', '.formipay-copy-button', function() {
        var $this = $(this);
        var copiedtext = $(this).prev("p").attr("data-copy-value");
        if (navigator.clipboard) {
            navigator.clipboard.writeText(copiedtext)
                .then(() => {
                    $this.html('<i class="bi bi-check-circle-fill"></i> '+$this.attr('data-copied-text'));
                    setTimeout(() => {
                        $this.html('<i class="bi bi-copy"></i> '+$this.attr('data-copy-text'));
                    }, 1200);
                })
                .catch((error) => {
                    $this.html('<i class="bi bi-check-circle-fill"></i> '+$this.attr('data-not-copied-text'));
                    setTimeout(() => {
                        $this.html('<i class="bi bi-copy"></i> '+$this.attr('data-copy-text'));
                    }, 1200);
                });
        } else {
            $this.html('<i class="bi bi-check-circle-fill"></i> '+$this.attr('data-not-copied-text'));
            setTimeout(() => {
                $this.html('<i class="bi bi-copy"></i> '+$this.attr('data-copy-text'));
            }, 1200);
        }

    });

    $('.formipay-submit-button').on('submit click', function(e){
        e.preventDefault();

        $(this).text(formipay.button_processing_text).prop('disabled', true);
        
        var form = $(this).parents('form');
        var form_id = form.data('form-id');
        var inputs = form.find('.formipay-input');
    
        var form_inputs = new FormData();
    
        form_inputs.append('action', 'formipay_submission');
        form_inputs.append('data[qty]', $('.formipay-qty-input').val());
        form_inputs.append('form_id', form_id); 
    
        var $valid = true;  // Initialize as true
    
        inputs.each(function(index, field) {
            var the_key = $(field).attr('name');
            var the_label = $(field).data('label');
    
            // $(field).removeAttr('style');
            $(field).removeClass('formipay-input-invalid');
    
            if (!$(field).is(':valid')) {
                // $(field).attr('style', 'border-color: #d93258!important;');
                $(field).addClass('formipay-input-invalid');
                $(field).siblings('.formipay-validate-field').remove();
    
                if ($(field).attr('type') == 'select' || $(field).attr('type') == 'radio' || $(field).attr('type') == 'checkbox') {
                    if ($(field).attr('type') == 'radio' || $(field).attr('type') == 'checkbox') {
                        if (!$('[name="' + $(field).attr('name') + '"]:checked').length) {
                            var notice_message = formipay.notice_empty_select_message;
                            $(field).parent().append('<p class="formipay-validate-field"><i class="bi bi-exclamation-circle"></i> '+notice_message.replace('{{field}}', the_label)+'</p>');
                            $valid = false;  // Set valid to false
                        }
                    } else if ($(field).attr('name').search('agreement') != -1) {
                        var notice_message = formipay.notice_empty_agreement_message;
                        $(field).parent().append('<p class="formipay-validate-field"><i class="bi bi-exclamation-circle"></i> '+notice_message.replace('{{field}}', the_label)+'</p>');
                        $valid = false;  // Set valid to false
                    } else {
                        var notice_message = formipay.notice_empty_select_message;
                        $(field).parent().append('<p class="formipay-validate-field"><i class="bi bi-exclamation-circle"></i> '+notice_message.replace('{{field}}', the_label)+'</p>');
                        $valid = false;  // Set valid to false
                    }
                } else {
                    var notice_message = formipay.notice_empty_text_message;
                    $(field).parent().append('<p class="formipay-validate-field"><i class="bi bi-exclamation-circle"></i> '+notice_message.replace('{{field}}', the_label)+'</p>');
                    $valid = false;  // Set valid to false
                }
            } else {
                var the_value;
                if ($(field).attr('type') == 'checkbox') {
                    var val = [];
                    form.find('[name=' + the_key + ']:checked').each(function(i, check) {
                        val[i] = $(check).val();
                    });
                    the_value = val;
                } else if ($(field).attr('type') == 'radio') {
                    the_value = $('[name=' + the_key + ']:checked').val();
                } else {
                    the_value = $(field).val();
                }
    
                if ($(field).attr('type') == 'hidden' || $(field).parent().is(':hidden')) {
                    if ($(field).hasClass('formipay-select')) {
                        form_inputs.append('data[' + the_key + '][value]', the_value);
                        form_inputs.append('data[' + the_key + '][label]', $(field).find('option:selected').attr('data-label'));
                    } else {
                        form_inputs.append('data[' + the_key + ']', the_value);
                    }
                } else {
                    $(field).siblings('.formipay-validate-field').remove();
    
                    if ($(field).hasClass('formipay-select')) {
                        form_inputs.append('data[' + the_key + '][value]', the_value);
                        form_inputs.append('data[' + the_key + '][label]', $(field).find('option:selected').attr('data-label'));
                    } else {
                        form_inputs.append('data[' + the_key + ']', the_value);
                    }

                    if(
                        the_key == 'payment' && 
                        typeof trx_fee !== typeof undefined && trx_fee !== false &&
                        trx_fee > 0
                     ) {
                        form_inputs.append('data[trx_fee]', $('[name=' + the_key + ']:checked').attr('data-calc-value'));
                     }
                }
            }
        });
    
        if($valid) {
            $.ajax({
                url: formipay.ajax_url,
                data: form_inputs,
                processData: false,
                contentType: false,
                type: 'POST',
                enctype: 'multipart/form-data',
                beforeSend: function() {
                    form.find('.formipay-validate-field').remove();
                    $('.formipay-input').removeAttr('style');
                    $('[data-form-id=' + form_id + ']').siblings('.submit-response').html('');
                    $('[data-form-id=' + form_id + ']').siblings('.submit-response').hide();
                    $('[data-form-id=' + form_id + ']').siblings('.submit-response').removeClass('formipay-message-success formipay-message-failed');
                },
                success: function(res) {
                    console.log(res);
                    if(res.success) {
                        if(res.data.response_type == 'notice') {
                            $('[data-form-id=' + form_id + ']').find('.submit-response').html('Success! ' + res.data.message);
                            $('[data-form-id=' + form_id + ']').find('.submit-response').addClass('formipay-message-success');
                            $('[data-form-id=' + form_id + ']').find('.submit-response').show();
                            if(res.data.action_type == 'thankyou'){
                                $('[data-form-id=' + form_id + ']').siblings('.formipay-thankyou').html(res.data.thankyou);
                                setTimeout(() => {
                                    $('[data-form-id=' + form_id + ']').find('.formipay-thankyou').show();
                                    $('[data-form-id=' + form_id + ']').remove();
                                    window.location.href = res.data.url;
                                }, 2500);
                            }else{
                                window.location.href = res.data.url;
                            }
                        } else if(res.data.response_type == 'popup') {
                            $('[data-form-id=' + form_id + ']').find('.formipay-thankyou').html(res.data.thankyou);
                            Swal.fire({
                                title: 'Success!',
                                html: res.data.message,
                                icon: 'success'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    if(res.data.action_type == 'thankyou'){
                                        $('[data-form-id=' + form_id + ']').find('.formipay-thankyou').show();
                                        $('[data-form-id=' + form_id + ']').remove();
                                    }else{
                                        window.location.href = res.data.url;
                                    }
                                }
                            });
                        }
                    } else {
                        if(res.data.response_type == 'notice') {
                            $('[data-form-id=' + form_id + ']').find('.submit-response').html('Failed! ' + res.data.message);
                            $('[data-form-id=' + form_id + ']').find('.submit-response').addClass('formipay-message-failed');
                            $('[data-form-id=' + form_id + ']').find('.submit-response').show();
                        } else if(res.data.response_type == 'popup') {
                            Swal.fire({
                                title: 'Failed!',
                                html: res.data.message,
                                icon: 'error'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    window.location.reload();
                                }
                            });
                        }
                    }
                }
            });
        }
    });

    feather.replace();

});