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

// Used for admin_panel.html

// Executes all the needed code
async function Load() {
    $("#TopicLink").attr("href", "/" + Topic() + "/Page:Main?a=edit");
    $("#ViewEntriesBtn").attr("href", "/" + Topic() + "/Page:Entries");
    $("#ViewFilesBtn").attr("href", "/" + Topic() + "/Page:Files");
    await $.ajax({
        url: "/permissions/topic",
        method: "GET",
        data: {
            topic: Topic()
        },
        success: function(response) {
            if (response != null) {
                let keys = Object.keys(response);
                let inputs = $("#TProw input");
                let counter = 0;
                $("#TopicVisibility").text(response.public == 1 ? "public" : "private");
                for (let _ = 0; _ < keys.length; _++) {
                    if (keys[_] != "id" && keys[_] != "public") {
                        inputs[counter].checked = (response[keys[_]] == 1 ? "checked" : "");
                        counter++;
                    }
                }
            }
            $("#TProw input").on("change", function() {
                ChangeElement($(this).parent(), "topic");
            });
        }
    });
    $("#TopicVisibility").on("click", function() {
        ChangeElement(this, "topic");
        $("#TopicVisibility").text($("#TopicVisibility").text() == "public" ? "private" : "public");
    });
    $("#SaveTopicBtn").on("click", async function() {
        if ($("#SaveTopicBtn").attr("disabled") == undefined) {
            let data = {
                topic: Topic(),
                public: $("#TopicVisibility").text() == "public" ? 1 : 0,
                perms: []
            };
            let inputs = $("#TProw input");
            for (let _ = 0; _ < inputs.length; _++) {
                data.perms.push(inputs[_].checked == true ? 1 : 0);
            }
            if (activeLock > 0) {
                return;
            }
            LockUI();
            await $.ajax({
                url: "/permissions/topic",
                method: "PUT",
                data: data,
                success: function() {
                    UnlockUI();
                    AlertWindow("success", "Topic settings saved!", "", false);
                    $("div#TopicStuff .changed").removeClass("changed");
                    $("#SaveTopicBtn").attr("disabled", true);
                    $("#TopicMessage").hide();
                }
            });
        }
    });

    $("#UserPermissionContainer").on("toggle", function() {
        if (!this.open) {
            UserPermContainer("close", "", 0);
        }
    });
    PermTable();
    $("#UProw input").on("change", function() {
        ChangeElement($(this).parent(), "user");
    });
    $("#SavePermissionsBtn").on("click", async function() {
        $("#UserMessage").text("");
        $("#UserMessage").hide();
        if ($("#UserNameInput").val().trim().length > 0) {
            let data = {
                topic: Topic(),
                user: $("#UserNameInput").val(),
                perms: []
            };
            let checkboxes = $("#UProw input");
            for (let _ = 0; _ < checkboxes.length; _++) {
                data.perms.push(checkboxes[_].checked == true ? 1 : 0);
            }
            let url = "/permissions/user";
            let method = "POST";
            if ($("#PermID").val().length > 0) {
                url = "/permissions/user/" + $("#PermID").val();
                method = "PUT";
            }
            if (activeLock > 0) {
                return;
            }
            LockUI();
            await $.ajax({
                url: url,
                method: method,
                data: data,
                success: function(response) {
                    UnlockUI();
                    AlertWindow("success", response.message, "", false);
                    UserPermContainer("close", "", 0);
                    PermTable();
                },
                error: function(response) {
                    UnlockUI();
                    $("#UserMessage").text(response.responseJSON.messages.error);
                    $("#UserMessage").show();
                }
            });
        }
        else {
            $("#UserMessage").text("Input username");
            $("#UserMessage").show();
        }
    });
    $("#CancelPermissionsBtn").on("click", function() {
        UserPermContainer("close", "", 0);
    });
    $("#UserSearchInput").on("input", function() {
        let tableRows = $("#TableOfEntries tr:not(.yippee)");
        let search_ = $("#UserSearchInput").val().toLowerCase();
        for (let _ = 0; _ < tableRows.length; _++) {
            let text_ = tableRows[_].innerHTML.split("</td>")[0].substring(4).toLowerCase();
            if (!text_.includes(search_)) {
                $(tableRows[_]).hide();
            }
            else {
                $(tableRows[_]).show();
            }
        }
    });
}

function ChangeElement(element, field) {
    if (field == "topic") {
        $(element).addClass("changed");
        $("#SaveTopicBtn").removeAttr("disabled");
        $("#TopicMessage").show();
    }
    else {
        $(element).addClass("changed");
    }
}

async function PermTable() {
    $("#TableOfEntries tr:not(.yippee)").remove();
    await $.ajax({
        url: "/permissions/users",
        method: "GET",
        data: {
            topic: Topic()
        },
        success: function(response) {
            for (let _ = 0; _ < response.length; _++) {
                let html = "<td>" + response[_].username + "</td>";
                let text_ = "";
                for (let value_ of Object.values(response[_].permissions)) {
                    text_ += value_.length > 0 ? "<li>" + value_ + "</li>" : "";
                }
                html += "<td>" + ((text_.length > 0) ? "<ul>" + text_ + "</ul>" : "none") + "</td>";
                html += "<td><a id=\"EditUser" + response[_].id + "\">Edit</a> <a id=\"RemoveUser" + response[_].id + "\">Remove</a></td>";
                $("#TableOfEntries").append("<tr id=\"Row" + response[_].id + "\">" + html + "</tr>");
                $("#EditUser" + response[_].id).on("click", function() {
                    UserPermContainer("open", response[_].username, response[_].id);
                    let checkboxes = $("#UProw input");
                    let permValues = Object.values(response[_].permissions);
                    for (let c = 0; c < checkboxes.length; c++) {
                        checkboxes[c].checked = (permValues[c].length > 0) ? true : false;
                    }
                });
                $("#RemoveUser" + response[_].id).on("click", async function() {
                    UserPermContainer("close", "", 0);
                    if (activeLock > 0) {
                        return;
                    }
                    LockUI();
                    await $.ajax({
                        url: "/permissions/user/" + response[_].id,
                        method: "DELETE",
                        data: {
                            topic: Topic()
                        },
                        success: function() {
                            UnlockUI();
                            AlertWindow("success", "Removed user's permissions!", "", false);
                            $("#Row" + response[_].id).remove();
                        }
                    });
                });
            }
        }
    });
}

function UserPermContainer(action, username, id) {
    if (action == "open") {
        $("#UserPermissionContainer").attr("open", "");
        if (username.length == 0 && id == 0) {
            $("#UserNameInput").removeAttr("readonly");
        }
        else {
            $("#UserNameInput").val(username);
            $("#PermID").val(id);
            $("#UserNameInput").attr("readonly", true);
        }
    }
    else {
        let checkboxes = $("#UProw input");
        for (let _ = 0; _ < checkboxes.length; _++) {
            checkboxes[_].checked = false;
        }
        $("#UserMessage").text("");
        $("#UserMessage").hide();
        $("#UserNameInput").val("");
        $("#PermID").val("");
        $("#UserPermissionContainer .changed").removeClass("changed");
        $("#UserPermissionContainer").removeAttr("open");
    }
}