/*
    Created: 2025-02-27
    Author: Kārlis Grīnvalds
    Last edited: 2025-12-04
    Edited by: Kārlis Grīnvalds
*/

// Used for log_in.html

// Adds functions to a button and input fields
async function Load() {
    // The enter button on the website gets an "on submit" function
    $("#EnterBtn").on("click", function() {
        $("#EnterBtn").prop("disabled", true);
        LogIn();
    });
    // Input fields can run the same "on submit" function
    $("#EmailInputField, #PasswordInputField").on("keypress", function(e) {
        // Checks if the key press was enter
        if(e.which == 13 && !$("#EnterBtn").prop("disabled")) {
            $("#EnterBtn").prop("disabled", true);
            LogIn();
        }
    });
}

// Does the log in process
async function LogIn() {
    // Checks if the user has inserted an email and a password
    if ($("#EmailInputField").val().trim().length > 0 && $("#PasswordInputField").val().trim().length > 0) {
        if ($("#EmailInputField").val().trim().length >= 5 && $("#PasswordInputField").val().trim().length >= 8) {
            // Prepares POST data
            let data = {
                email: $("#EmailInputField").val(),
                password: $("#PasswordInputField").val(),
            };
            // Checks, if that user exists
            await $.ajax({
                url: "/user/session",
                method: "POST",
                data: data,
                success: function() {
                    // Hides the error text
                    $("#ErrorText").hide();
                    $("#ErrorText").text("");
                    // User does exist, session has been started and user gets send to the main page
                    Link("/");
                },
                error: function(response) {
                    // Outputs an error message
                    $("#ErrorText").show();
                    $("#ErrorText").text(response.responseJSON.messages.error);
                    $("#EnterBtn").prop("disabled", false);
                }
            });
        }
        else {
            // Outputs an error message
            $("#ErrorText").show();
            $("#ErrorText").text("Incorrect email or password!");
        }
    }
    else {
        // Outputs an error message
        $("#ErrorText").show();
        $("#ErrorText").text("All input fields need to be filled!");
    }
    $("#EnterBtn").prop("disabled", false);
}