<%- include('./partials/header'); %>
<style>
    .userpfp {
        width: 100px;
        height: 100px;
        border-radius: 50%;
    }
</style>
<link rel="stylesheet" href="/assets/css/selectize.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js"></script>
<br>
<br>
<h1 class="text-light text-center">Admin Panel</h1>
<br>
<br>
<div class="one card card-body col-md-6 m-auto user-list">
    <select name="user-dropdown" id="user-dropdown" onchange="selectUser()">
    <option value="" selected>Please select a User</option>
</select>
</div>
<br>
<div class="wrapper">
    <div id="ban-etc-buttons" style="visibility: hidden; background-color: #b1cbe6;" class="one card card-body col-md-6 m-auto">
        <h2 class="text-center">Actions</h2>
        <br>
        <h4>User is currently:</h4>
        <h4 id="banunbantext" style="color:green">Not Banned</h4>
        <br>
        <button type="button" class="btn btn-success verify-account" onclick="verifyUser()">Manually Verify User Email</button>
        <br class="verify-account">
        <button type="button" class="btn btn-success unban-account" onclick="unbanUserAcc()">Unban User Account</button>
        <br class="unban-account">
        <button type="button" class="btn btn-danger ban-account" onclick="banUserAcc()">Ban User Account</button>
        <br class="ban-account">
        <button type="button" class="btn btn-success" onclick="updateUserEmail()">Update User Email</button>
        <br>
        <button type="button" class="btn btn-warning cancel-vip" onclick="cancelUserVIP()">Cancel VIP Subscription</button>
        <br class="cancel-vip"><br>
        <button type="button" class="btn btn-danger" onclick="deleteUserAcc()">Delete User Account</button>
    </div>
    <br>
    <div id="user-data" style="visibility: hidden; background-color: #b1cbe6;" class="two card card-body col-md-6 m-auto">
        <img class="userpfp" id="userpfp" style="visibility: hidden;"></img>
        <br>
        <b><p id="selectedusertext" class="text-dark">Selected User: </p></b>
        <p id="userdatatext" class="text-dark"></p>
        <br>
    </div>

</div>
<%- include('./partials/footer'); %>
<script>
    const webhookURL =
        "https://discord.com/api/webhooks/854405974097920040/vVfV1GzYnt7M5fUcnQWap3hbuCLNBYioDX4DBU-tfGC9J4OKOOk3hS2K7szgYGexG3Q7";
    const allUsersArr = [];

    // Fetch all of the users.
    fetch(`/api/fetch-users-no-staff`).then(data => data.json()).then(users => {
        const allUsers = users;
        const userDropdown = document.querySelector(`#user-dropdown`);


        allUsers.forEach((user, index) => {
            const optionElement = document.createElement(`option`);

            optionElement.value = index;
            optionElement.textContent = user.name;

            userDropdown.appendChild(optionElement);
            allUsersArr.push(user);
        });

        $(`#user-dropdown`).selectize();
    });

    const selectUser = async() => {
        const userdataDiv = document.querySelector(`#user-data`);
        const buttonsDiv = document.querySelector(`#ban-etc-buttons`);
        const e = document.querySelector(`#user-dropdown`);
        const banunbantext = document.querySelector(`#banunbantext`);

        const selectedUser = e.options[e.selectedIndex].text;

        if (selectedUser === `Please Select a user`) return userdataDiv.style.visibility = `hidden`;
        if (!selectedUser) return userdataDiv.style.visibility = `hidden`;
        userdataDiv.style.visibility = `visible`;
        buttonsDiv.style.visibility = `visible`;

        const DisplayText = document.querySelector(`#selectedusertext`);
        DisplayText.innerHTML = `Selected User: ${selectedUser}`;

        const userDataDisplayText = document.querySelector(`#userdatatext`);

        const trueUserData = await getData(selectedUser)

        let imgSource = trueUserData.avatarURL;

        if (imgSource == "/assets/uploads/defaultpfp.png") {
            imgSource = "/assets/img/defaultpfp.png";
        }
        let userImage = document.querySelector(`#userpfp`);
        userImage.style.visibility = 'visible';
        userImage.setAttribute("src", imgSource);

        let textToInsert = ``;
        for (const prop in trueUserData) {
            if (typeof trueUserData[prop] === `object`) {
                let stringText = ``;
                const nestedObj = trueUserData[prop];
                for (const property2 in nestedObj) {
                    const extraObjectToAppend =
                        `${prop}.${property2.toString()}: <b>${nestedObj[property2].toString()}</b><br>`;
                    stringText = stringText.concat(extraObjectToAppend);
                }
                textToInsert = textToInsert.concat(stringText);
            } else {
                const stringText = `${prop.toString()}: <b>${trueUserData[prop].toString()}</b><br>`;
                textToInsert = textToInsert.concat(stringText);
            }
        }

        userDataDisplayText.innerHTML = textToInsert;

        if (trueUserData.emailVerified) {
            $(`.verify-account`).hide();
        }

        if (!trueUserData.perms.vip) {
            $(`.cancel-vip`).show();
        }

        if (trueUserData.isBanned) {
            $(`.ban-account`).hide();
            $(`.unban-account`).show();
            banunbantext.style.color = "red";
            banunbantext.innerHTML = "Banned";
        } else {
            $(`.unban-account`).hide();
            $(`.ban-account`).show();
            banunbantext.style.color = "green";
            banunbantext.innerHTML = "Unbanned";
        }

        // `Username: <b>${trueUserData.name}</b><br>Email: <b>${trueUserData.email}</b><br> Banned: <b>${trueUserData.isBanned}</b><br>IPs: <b>${trueUserData.creationIP}, ${trueUserData.lastIP}</b><br>`
    };

    const deleteUserAcc = async() => {
        const userdataDiv = document.querySelector(`#user-data`);
        const e = document.querySelector(`#user-dropdown`);
        const selectedUser = e.options[e.selectedIndex].text;

        let conformation = confirm(
            `Are you sure you want to delete the account of ${selectedUser}? You will NOT be able to undo this action!`
        );
        if (conformation == false) {
            return;
        } else {
            await fetch(`/api/delete-account/${selectedUser}`)
            alert("Deleted user account!")

            let modName = (await fetch('/authenticated').then(resp => {
                return resp.json()
            })).username;
            let textContent =
                `⛔ **Deleted** ThrowdownTV User via Admin Panel\nUsername: **${selectedUser}**\nModerator: **${modName}**\n -`;
            var params = {
                content: textContent
            };
            await fetch(webhookURL, {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(params)
            }).then(okay => {
                window.location.reload(true);
            })

            window.location.reload(true);
        }
    }

    const banUserAcc = async() => {
        const userdataDiv = document.querySelector(`#user-data`);
        const e = document.querySelector(`#user-dropdown`);
        const selectedUser = e.options[e.selectedIndex].text;

        const trueUserData = await getData(selectedUser)
        if (trueUserData.isBanned) return alert("User is already banned!");
        let conformation = confirm(
            `Are you sure you want to ban the account of ${selectedUser}?`
        );
        if (conformation == false) {
            return;
        } else {
            let banReason = window.prompt("What is the ban reason for this user?");
            let modName = (await fetch('/authenticated').then(resp => {
                return resp.json()
            })).username;

            let ttData = await fetch(`/api/banuser/${selectedUser}`).then(data => data.json()).then(data => {
                return data;
            });

            let textContent =
                `⛔ **Banned** ThrowdownTV User via Admin Panel\nUsername: **${selectedUser}**\nModerator: **${modName}**\nReason: ${banReason}\n -`;
            var params = {
                content: textContent
            };
            await fetch(webhookURL, {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(params)
            }).then(okay => {
                window.location.reload(true);
            })
            window.location.reload(true);
        }
    }

    const updateUserEmail = async() => {
        const userdataDiv = document.querySelector(`#user-data`);
        const e = document.querySelector(`#user-dropdown`);
        const selectedUser = e.options[e.selectedIndex].text;

        let conformation = confirm(
            `Are you sure you want to update the email of ${selectedUser}?`
        );
        if (conformation == false) {
            return;
        } else {
            let newEmail = window.prompt("Enter the new email address for the user");
            if (!newEmail) return;

            let ttData = await fetch(`/api/update-email/${selectedUser}/${newEmail}`).then(data => data.json()).then(data => {
                window.location.reload(true);
                return data;
            });

            return window.location.reload(true);
        }
    }

    const verifyUser = async() => {
        const userdataDiv = document.querySelector(`#user-data`);
        const e = document.querySelector(`#user-dropdown`);
        const selectedUser = e.options[e.selectedIndex].text;

        const trueUserData = await getData(selectedUser)
        if (trueUserData.emailVerified) return alert("User is already verified!");
        let conformation = confirm(
            `Are you sure you want to manually verify the email of ${selectedUser}?`
        );
        if (conformation == false) {
            return;
        } else {
            let modName = (await fetch('/authenticated').then(resp => {
                return resp.json()
            })).username;

            let ttData = await fetch(`/api/verify-user-email/${selectedUser}`).then(data => data.json()).then(data => {
                return data;
            });

            let textContent =
                `✅ **Cancelled** VIP Subscription\nUsername: **${selectedUser}**\nModerator: **${modName}**\n -`;
            var params = {
                content: textContent
            };
            await fetch(webhookURL, {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(params)
            }).then(okay => {
                window.location.reload(true);
            })
            window.location.reload(true);
        }
    }

    const cancelUserVIP = async() => {
        const userdataDiv = document.querySelector(`#user-data`);
        const e = document.querySelector(`#user-dropdown`);
        const selectedUser = e.options[e.selectedIndex].text;

        const trueUserData = await getData(selectedUser)
        if (!trueUserData.perms.vip) return alert("User isn't a VIP!");
        let conformation = confirm(
            `Are you sure you want to cancel the VIP subscription of ${selectedUser}?`
        );
        if (conformation == false) {
            return;
        } else {
            let modName = (await fetch('/authenticated').then(resp => {
                return resp.json()
            })).username;

            let ttData = await fetch(`/api/cancel-subscription/${selectedUser}`).then(data => data.json()).then(data => {
                return data;
            });

            let textContent =
                `✅ **Cancelled** VIP Subscription\nUsername: **${selectedUser}**\nModerator: **${modName}**\n -`;
            var params = {
                content: textContent
            };
            await fetch(webhookURL, {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(params)
            }).then(okay => {
                window.location.reload(true);
            })
            window.location.reload(true);
        }
    }

    const unbanUserAcc = async() => {
        const userdataDiv = document.querySelector(`#user-data`);
        const e = document.querySelector(`#user-dropdown`);
        const selectedUser = e.options[e.selectedIndex].text;

        const trueUserData = await getData(selectedUser)
        if (!trueUserData.isBanned) return alert("User is not banned!");
        let conformation = confirm(
            `Are you sure you want to unban the account of ${selectedUser}?`
        );
        if (conformation == false) {
            return;
        } else {
            let modName = (await fetch('/authenticated').then(resp => {
                return resp.json()
            })).username;

            let ttData = await fetch(`/api/unbanuser/${selectedUser}`).then(data => data.json()).then(data => {
                return data;
            });

            let textContent =
                `✅ **Unbanned** ThrowdownTV User via Admin Panel\nUsername: **${selectedUser}**\nModerator: **${modName}**\n -`;
            var params = {
                content: textContent
            };
            await fetch(webhookURL, {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(params)
            }).then(okay => {
                window.location.reload(true);
            })
            window.location.reload(true);
        }
    }

    const getData = async(username) => {
        let userData;
        let ttData = await fetch(`/api/fetch-user/${username}`).then(data => data.json()).then(data => {
            return data;
        })
        return ttData;
    };
</script>