/*
    Created: 2026-04-13
    Author: Kārlis Grīnvalds
    Last edited: 2026-06-04
    Edited by: Kārlis Grīnvalds
*/

// Used for edit_entry.html

// Executes all the needed code
async function Load() {
    // Gets the url parameter
    const entryName = window.location.href.split(Topic() + "/")[1].split("?a=")[0];
    await $.ajax({
        url: "/entry",
        method: "GET",
        data: {
            topic: Topic(),
            entry_name: entryName
        },
        success: async function(response) {
            // Inserts all entry data in input fields
            $("#EntryTitle").val(DecodeHTMLSymbols(response[0].title));
            $("#EntryContent").val(DecodeHTMLSymbols(response[0].content));
            // Adds a function to save button
            $("#SaveChanges").on("click", async function() {
                // Checks, if the fields have been filled
                if ($("#EntryTitle").val().trim().length > 0 && $("#SaveChanges").attr("value") != "disabled" && $("#Delete").attr("value") != "disabled") {
                    $("#SaveChanges").attr("value", "disabled");
                    // Hides the error text
                    $("#ErrorText").hide();
                    $("#ErrorText").text("");
                    // Prepares POST data
                    let data = {
                        topic: Topic(),
                        name: $("#EntryTitle").val().replaceAll(" ", "_"),
                        title: $("#EntryTitle").val(),
                        content: $("#EntryContent").val()
                    };
                    if (activeLock > 0) {
                        return;
                    }
                    LockUI();
                    // Updates the entry and returns the results
                    await $.ajax({
                        url: "/entry/" + response[0].id,
                        method: "POST",
                        data: data,
                        success: function(response) {
                            activeLock++;
                            // Entry has been updated and returns user to the entry
                            UnlockUI();
                            AlertWindow("success", "Entry has been updated!", "/" + Topic() + "/" + response.redirect, true);
                        },
                        error: function(response) {
                            UnlockUI();
                            // Outputs an error message
                            $("#ErrorText").show();
                            $("#ErrorText").text(response.responseJSON.messages.error);
                        }
                    });
                }
                else {
                    // Outputs an error message
                    $("#ErrorText").show();
                    $("#ErrorText").text("All input fields must be filled out!");
                }
            });
            $("#CancelChanges").on("click", function() {
                RedirectBack("/" + Topic() + "/" + entryName);
            });
            $("#SaveChanges").attr("value", "");
            await $.ajax({
                url: "/user/permissions",
                method: "GET",
                data: {
                    topic: Topic(),
                    select: ["delete_entries"]
                },
                success: function(permissions) {
                    if (Object.keys(permissions).length > 0) {
                        if (permissions.delete_entries) {
                            $("div.form-btns").append("<button id=\"Delete\">Delete</button>");
                            // Deletes the entry and returns the results
                            $("#Delete").on("click", async function() {
                                if ($("#SaveChanges").attr("value") != "disabled" && $("#Delete").attr("value") != "disabled") {
                                    $("#Delete").attr("value", "disabled");
                                    if (activeLock > 0) {
                                        return;
                                    }
                                    LockUI();
                                    await $.ajax({
                                        url: "/entry/" + response[0].id,
                                        method: "DELETE",
                                        data: {
                                            topic: Topic()
                                        },
                                        success: function() {
                                            activeLock++;
                                            // Entry has been deleted succesfully!
                                            UnlockUI();
                                            AlertWindow("success", "Entry has been deleted!", "/" + Topic() + "/Page:Entries", true);
                                        },
                                        error: function(response) {
                                            UnlockUI();
                                            // Something went wrong in the deletion
                                            $("#ErrorText").show();
                                            $("#ErrorText").text("Data is missing!");
                                        }
                                    });
                                }
                            });
                        }
                    }
                }
            });
        }
    });
}