$(function () {
    // reset profile form
    $('#email').val('');
    $('#username').val('');
    $('#password').val('');
    $('#confirmpassword').val('');
    $('#security_answer').val('');
});


// BEGIN database form

// tooltip
$('[data-toggle="tooltip"]').tooltip({
    placement: 'auto',
    boundary: 'window'
});

$('.btn-next').attr('disabled', true);

$("#loading-loader").hide();

$('#database-form').validate({

    rules: {
        host: "required",
        db_name: "required",
        db_user: "required",
        db_password: "required"

    },
    errorPlacement: function (error, element) {
        element.closest('.input-container').after(error);
    },
    messages: {
        host: "field is required",
        db_name: "field is required",
        db_user: "field is required",
        db_password: "field is required",
    },

    submitHandler: function (form) {

        var url =
            $.ajax({
                type: "POST",
                url: $('#database-form').data('path') + $('#database-form').data('action'),
                data: {
                    driver: $("#datasource").val(),
                    host: $("#host").val(),
                    db_name: $("#db_name").val(),
                    db_user: $("#db_user").val(),
                    db_password: $("#db_password").val(),
                    db_port: $("#db_port").val(),
                },
                beforeSend: function () {
                    $('.loader-text').html("Connecting ..");

                    $("#loading-loader").fadeIn();


                },
                success: function (response) {

                    var jsonData = JSON.parse(response);

                    var msg = prepareMessage(jsonData.msg, 100);

                    if (msg.fullMsg === "Connection success") {

                        $('.msg').html(msg.fullMsg).attr("title", msg.fullMsg);

                        $("#test-connection").val("Import DB");

                        $("#database-form").data("action", "importDatabase");

                        $("#test-connection").attr("id", "import-db");

                        $("#import-db").attr("type", "button");

                        $('#import-db').on('click', function () {

                            runMigrations();

                        });

                        detectChangeOnInputs();
                    } else {
                        $('.msg').html(msg.truncatedMsg).attr("title", msg.fullMsg);

                        $('.btn-next').attr('disabled', true);
                    }

                }, complete: function () {
                    $("#loading-loader").fadeOut();

                }

            });
        return false;

    }

});


function runMigrations() {
    $.ajax({
        type: "POST",
        url: $('#database-form').data('path') + $('#database-form').data('action'),
        data: {
        },
        beforeSend: function () {
            $('.loader-text').html("Importing database, please wait.<br> This process may take a few minutes…");

            $("#loading-loader").fadeIn();

        },
        success: function (response) {

            var jsonData = JSON.parse(response);

            var msg = prepareMessage(jsonData.msg, 100);

            if (msg.fullMsg === "DB imported successfully" || msg.fullMsg.includes("The installation has already been completed in this database")) {

                $('.msg').html(msg.truncatedMsg).attr("title", msg.fullMsg);

                $('.btn-next').attr('disabled', false);

            } else {
                $('.msg').html(msg.truncatedMsg).attr("title", msg.fullMsg);

                $('.btn-next').attr('disabled', true);
            }
        },
        complete: function () {
            $("#loading-loader").fadeOut();

        },
    });
}

function detectChangeOnInputs() {
    $('input[type=text],input[type=password]').on('input propertychange', function () {

        $("#import-db").val("Test Connction");
        $('.loader-text').html("Connecting ..");

        $("#import-db").attr("id", "test-connection");

        $("#database-form").data("action", "checkConnection");

        $("#test-connection").attr("type", "submit");
        $('.msg').html('');

    });

}

function prepareMessage(msg, length) {

    if (msg.length > length)
        return {
            fullMsg: msg,
            truncatedMsg: `${msg.substring(0, length)}...`
        };
    else {
        return {
            fullMsg: msg,
            truncatedMsg: msg,
        };
    }

}

// END database form


if ($('.btn-finish').data('disabled') === "enable")
    $('.btn-finish').attr('disabled', false);
else
    $('.btn-finish').attr('disabled', true);


$("#allow-smtp-later").on('click', function () {
    if (!$(this).is(":checked")) {
        $("#smtp-container").fadeIn();
        $("#allow-smtp-later-form").val(0);
        $('.btn-finish').attr('disabled', true)
    } else {
        $("#smtp-container").fadeOut();
        $("#allow-smtp-later-form").val(1);
        $('.btn-finish').attr('disabled', false)

    }
})



$('#setting-form').validate({

    rules: {
        smtp_host: "required",
        smtp_port: "required",
        smtp_username: "required",
        smtp_password: "required",
    },

    submitHandler: function (form) {

        var url =
            $.ajax({
                type: "POST",
                url: $('#setting-form').data('path') + $('#setting-form').data('action'),
                data: {
                    smtp_host: $("#smtp_host").val(),
                    smtp_port: $("#smtp_port").val(),
                    smtp_username: $("#smtp_username").val(),
                    smtp_password: $("#smtp_password").val(),
                    smtp_encryption: $("#smtp_encryption").val(),
                    smtp_auth_mode: $("#smtp_auth_mode").val(),
                },
                beforeSend: function () {
                    $("#loading-loader").fadeIn();
                },
                success: function (response) {
                    var jsonData = JSON.parse(response);

                    var msg = prepareMessage(jsonData.msg, 100);

                    if (msg.fullMsg === "Connection to SMTP is successful") {

                        $('.msg').html(msg.fullMsg).attr("title", msg.fullMsg);

                        $('.btn-finish').attr('disabled', false);

                    } else if (msg.fullMsg === "confirm") {

                        $('#confirm-smtp-modal').modal({
                            show: true,
                            backdrop: false
                        });

                    }
                    else {
                        $('.msg').html(msg.truncatedMsg).attr("title", msg.fullMsg);

                        $('.btn-next').attr('disabled', true);
                    }

                },
                complete: function () {
                    $("#loading-loader").fadeOut();
                },

            });
        return false;

    }

});

$('#confirm-smtp-yes').on('click', function () {

    var url =
        $.ajax({
            type: "POST",
            url: $('#setting-form').data('path') + 'storeSmtpAfterConfirm',
            data: {
                smtp_host: $("#smtp_host").val(),
                smtp_port: $("#smtp_port").val(),
                smtp_username: $("#smtp_username").val(),
                smtp_password: $("#smtp_password").val(),
                smtp_encryption: $("#smtp_encryption").val(),
                smtp_auth_mode: $("#smtp_auth_mode").val(),
            },
            success: function (response) {
                var jsonData = JSON.parse(response);

                var msg = prepareMessage(jsonData.msg, 100);

                if (msg.fullMsg === "Connection to SMTP is successful") {

                    $('.msg').html(msg.fullMsg).attr("title", msg.fullMsg);

                    $('.btn-finish').attr('disabled', false);
                    $('#confirm-smtp-modal').modal('hide')


                }
                else {
                    $('.msg').html(msg.truncatedMsg).attr("title", msg.fullMsg);

                    $('.btn-next').attr('disabled', true);
                }

            },

        });



});

$('#confirm-smtp-no').on('click', function () {

    var url =
        $.ajax({
            type: "POST",
            url: $('#setting-form').data('path') + 'storeSmtpAfterConfirm',
            data: {
                confirm_smtp_no: true,
            },
            success: function (response) {

                $('.btn-finish').attr('disabled', false);
            },

        });


});

document.addEventListener("DOMContentLoaded", function () {

    if (document.getElementById('timezone')) {


        document.getElementById('timezone').value = Intl.DateTimeFormat().resolvedOptions().timeZone;

        if ($('#allow-smtp-later').is(':checked')) {
            $("#smtp-container").css("display", "none");;
            $('.btn-finish').attr('disabled', false)

        }
    }
});

// END setting form


