// source --> https://r-tech.co.il/wp-content/plugins/meshulam-payment-gateway-1/assets/js/meshulam_payment.js?ver=9.1 
var $ = jQuery.noConflict();

$(document).ready(function(){
    if($('p.woocommerce-notice.woocommerce-notice--error.woocommerce-thankyou-order-failed').length > 0){
        $('.entry-title').css('display','none');
    }
});

$(document).ready(function(){
	if($('#meshulam_recurring').is(':checked')){
		$('.meshulam-installment-tab_options').show();
	}
	else{
		$('.meshulam-installment-tab_options').hide();
	}
    $('#meshulam_recurring').change(function(){
		if($(this).is(':checked')){
			$('.meshulam-installment-tab_options').show();
		}else{
            $('#_meshulam_checkbox_field').prop('checked', false);
            $('#_meshulam_pay_field').val('');
			$('.meshulam-installment-tab_options').hide();
		}
	})
});
// source --> https://r-tech.co.il/wp-content/plugins/meshulam-payment-gateway-1/assets/js/meshulam_payment_popup.js?ver=9.1 
var $ = jQuery.noConflict();

var order_id = '';

jQuery(function ($) {

    if (typeof wc_checkout_params === 'undefined')
        return false;

    $(document.body).on("click", ".close_popup_meshulam", function (evt) {
        $('.popup_overlay_meshulam').remove();
    });

    $(document.body).on("click", "#place_order", function (evt) {
        var payment_method = jQuery('form[name="checkout"] input[name="payment_method"]:checked').val();
        var Form = $(this).parents('form.checkout');
        $(".woocommerce-error").remove();

        if (payment_method == 'bitpay-payment' || payment_method == 'meshulam-payment' || payment_method == 'apple-payment' || payment_method == 'cal-payment' || payment_method == 'googlepay-payment') {
            evt.preventDefault();
            $('.main_meshulam_loader').show();
            $.ajax({
                type: 'POST',
                url: '?wc-ajax=checkout',
                dataType: 'json',
                data: Form.serializeArray(),
                success: function (response) {
                    // console.log(response);

                    $('.checkout-inline-error-message').remove();
                    $('.woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message, .woocommerce-info, .is-error, .is-success').remove();
                    detachUnloadEventsOnSubmit();

                    if (response.result == 'failure') {
                        $('.main_meshulam_loader').hide();
                        $('.woocommerce-notices-wrapper:first').prepend(response.messages);
                        if (response.messages) {
                            var $msgs = $(response.messages).removeAttr('role').attr('tabindex', '-1');
                            var $msgsWithLink = wrapMessagesInsideLink($msgs);
                            var $msgsWrapper = $('<div role="alert"></div>').append($msgsWithLink);
                            submit_error($msgsWrapper.prop('outerHTML'));
                            show_inline_errors($msgs);
                        } else {
                            submit_error('<div class="woocommerce-error">' + wc_checkout_params.i18n_checkout_error + '</div>');
                        }
                    }

                    if (response.result == 'success') {
                        var red_url = response.redirect;
                        order_id = response.order_id;
                        var action = 'meshulam_popup_payment_iframe';
                        $.ajax({
                            type: 'POST',
                            url: grow_params.ajax_url,
                            dataType: 'html',
                            data: { order_id: order_id, action: action },
                            success: function (result) {
                                $('.main_meshulam_loader').hide();
                                if (result == 'false') {
                                    window.location.href = red_url;
                                }
                                if (payment_method == 'apple-payment') {
                                    window.location.href = result;
                                    return;
                                }
                                $('body').append(result);
                                $(".close_popup_meshulam").fadeIn(6000);
                            },
                            error: function (error) {
                                $('.main_meshulam_loader').hide();
                                console.log(error); // For testing (to be removed)
                            }
                        });
                    }

                },
                error: function (error) {
                    $('.main_meshulam_loader').hide();
                    console.log(error); // For testing (to be removed)
                }
            });
        }

        if (payment_method == 'grow-wallet-payment') {
            evt.preventDefault();
            $('.main_meshulam_loader').show();
            $.ajax({
                type: 'POST',
                url: '?wc-ajax=checkout',
                dataType: 'json',
                data: Form.serializeArray(),
                success: function (response) {
                    // console.log(response);

                    $('.checkout-inline-error-message').remove();
                    $('.woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message, .woocommerce-info, .is-error, .is-success').remove();
                    detachUnloadEventsOnSubmit();

                    if (response.result == 'failure') {
                        $('.main_meshulam_loader').hide();
                        $('.woocommerce-notices-wrapper:first').prepend(response.messages);
                        if (response.messages) {
                            var $msgs = $(response.messages).removeAttr('role').attr('tabindex', '-1');
                            var $msgsWithLink = wrapMessagesInsideLink($msgs);
                            var $msgsWrapper = $('<div role="alert"></div>').append($msgsWithLink);
                            submit_error($msgsWrapper.prop('outerHTML'));
                            show_inline_errors($msgs);
                        } else {
                            submit_error('<div class="woocommerce-error">' +wc_checkout_params.i18n_checkout_error +'</div>');
                        }
                    }

                    if (response.result == 'success') {
                        var red_url = response.redirect;
                        order_id = response.order_id;
                        var action = 'meshulam_grow_wallet_iframe';
                        $.ajax({
                            type: 'POST',
                            url: grow_params.ajax_url,
                            dataType: 'json',
                            data: { order_id: order_id, action: action },
                            success: function (result) {
                                $('.main_meshulam_loader').hide();
                                if (result == false) {
                                    window.location.href = red_url;
                                }else if( result.error ){
                                    submit_error('<div class="woocommerce-error">' + result.error + '</div>');
                                }else {
                                    growPayment.renderPaymentOptions(result.token);
                                    redirect = result.thank_you_url;
                                }
                                $(".close_popup_meshulam").fadeIn(6000);
                            },
                            error: function (error) {
                                $('.main_meshulam_loader').hide();
                                console.log(error); // For testing (to be removed)
                            }
                        });
                    }

                },
                error: function (error) {
                    $('.main_meshulam_loader').hide();
                    console.log(error); // For testing (to be removed)
                }
            });
        }
    });

});

function wrapMessagesInsideLink($msgs) {
    $msgs.find('li[data-id]').each(function () {
        const $this = $(this);
        const dataId = $this.attr('data-id');
        if (dataId) {
            const $link = $('<a>', {
                href: '#' + dataId,
                html: $this.html(),
            });
            $this.empty().append($link);
        }
    });

    return $msgs;
}

function submit_error (error_message) {
    $('.woocommerce-NoticeGroup-checkout, .woocommerce-error, .woocommerce-message, .is-error, .is-success').remove();
    $checkout_form = $('form.checkout');
    $checkout_form.prepend('<div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">' +error_message +'</div>');
    $checkout_form.removeClass('processing').unblock();
    $checkout_form.find('.input-text, select, input:checkbox').trigger('validate').trigger('blur');
    scroll_to_notices();
    $checkout_form.find('.woocommerce-error[tabindex="-1"], .wc-block-components-notice-banner.is-error[tabindex="-1"]').focus();
    $(document.body).trigger('checkout_error', [error_message]);
}

function show_inline_errors ($messages) {

    $messages.find('li[data-id]').each(function () {
        const $this = $(this);
        const dataId = $this.attr('data-id');
        const $field = $('#' + dataId);

        if ($field.length === 1) {
            const descriptionId = dataId + '_description';
            const msg = $this.text().trim();
            const $formRow = $field.closest('.form-row');

            const errorMessage = document.createElement('p');
            errorMessage.id = descriptionId;
            errorMessage.className = 'checkout-inline-error-message';
            errorMessage.textContent = msg;

            if ($formRow && errorMessage.textContent.length > 0) {
                $formRow.append(errorMessage);
            }

            $field.attr('aria-describedby', descriptionId);
            $field.attr('aria-invalid', 'true');
        }
    });

}

function scroll_to_notices () {
    var scrollElement = $('.woocommerce-NoticeGroup-updateOrderReview, .woocommerce-NoticeGroup-checkout');

    if (!scrollElement.length) {
        scrollElement = $('form.checkout');
    }
    $.scroll_to_notices(scrollElement);
}

function detachUnloadEventsOnSubmit () {
    $(window).off('beforeunload', handleUnloadEvent);
}

function handleUnloadEvent (e) {
    if (navigator.userAgent.indexOf('MSIE') !== -1 || !!document.documentMode ) {
        e.preventDefault();
        return undefined;
    }
    return true;
}

function set_payment_method_name(method_id, new_order_id="") {
    if (new_order_id != ''){
        order_id = new_order_id
    }

    if (order_id == '') {
        console.log('Order ID is missing');
        return;
    }

    $.ajax({
        type: 'POST',
        url: grow_params.ajax_url,
        dataType: 'json',
        data: {
            action: 'wallet_set_method_title',
            order_id: order_id,
            method_id: method_id,
        },
        success: function (result) {
            console.log(result);
        },
        error: function (error) {
            console.log(error);
        }
    });

};