/*
    Created: 2025-02-27
    Author: Kārlis Grīnvalds
    Last edited: 2026-06-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();
        }
    });
    // Adds function to a checkbox to show the inputted password
    $("#ShowPasswordBtn").on("change", function() {
        if ($("#ShowPasswordBtn:checked").val() === undefined) {
            $("#PasswordInputField").attr("type", "password");
        }
        else {
            $("#PasswordInputField").attr("type", "text");
        }
    });
}

// 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
            if (activeLock > 0) {
                return;
            }
            LockUI();
            await $.ajax({
                url: "/user/login",
                method: "POST",
                data: data,
                success: function() {
                    activeLock++;
                    UnlockUI();
                    // Hides the error text
                    $("#ErrorText").hide();
                    $("#ErrorText").text("");
                    // User does exist, session has been started and user gets redirected back
                    RedirectBack("/");
                },
                error: function(response) {
                    UnlockUI();
                    // 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);
}