<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bot List</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/1.1.0/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sanitize-html/1.26.0/sanitize-html.min.js"></script>
    <%- include("./components/header.ejs") %>
</head>
<body>
    <%- include("./components/navbar.ejs", { bot, user }) %>

    <div class="container">
        <div class="jumbotron">
            <h2>Edit</h2>
            <p>You are now editing <strong><%= botInfo.username %>#<%= botInfo.discriminator %></strong></p>
            <a href="/bots/<%= botInfo.id %>/delete" type="button" class="btn btn-danger">Delete Bot</a>
        </div>
        <div class="alert alert-dismissible alert-success" id="success-save" style="display: none;">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            <strong>Saved changes successfully!</strong>
        </div>
        <div class="alert alert-dismissible alert-danger" id="error-save" style="display: none;">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            <strong>Oopsie! Something went terribly wrong!</strong>
        </div>
        <div class="alert alert-dismissible alert-warning" id="warning-save" style="display: none;">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            <strong></strong>
        </div>
        <div class="form">
            <form action="/bots/<%= botInfo.id %>/edit" method="POST" onsubmit="return validateForm()">
                <div class="form-group required">
                    <label for="botID">Your Bot ID</label>
                    <input type="number" class="form-control" id="botID" value="<%= botInfo.id %>" disabled>
                </div>
                <div class="form-group required">
                    <label for="botPrefix">Prefix</label>
                    <input type="text" class="form-control" id="botPrefix" value="<%= botDB.prefix %>" placeholder="<%= bot.config.prefix %>" onkeyup="setValidation($(this), checkValid($(this)))" autocomplete="off">
                </div>
                <div class="form-group required">
                    <label for="botShortDesc">Short Description</label>
                    <input type="text" class="form-control" id="botShortDesc" value="<%= botDB.shortDesc %>" aria-describedby="botShortDeschelp" placeholder="Revolutionary bot with..." onkeyup="setValidation($(this), checkValid($(this), 'char_100'))" autocomplete="off">
                    <small id="botShortDeschelp" class="form-text text-muted">Short Description about the bot (Min. 50 & Max. 100 characters)</small>
                </div>
                <div class="form-group required">
                    <label for="botLongDesc">Long Description</label>
                    <textarea class="form-control" id="botLongDesc" rows="3" placeholder="More about the Revolution..." onkeyup="setValidation($(this), checkValid($(this), 'char_300'))" autocomplete="off"><%= botDB.longDesc %></textarea>
                    <small id="botLongDeschelp" class="form-text text-muted">HTML & Markdown can be used (Min. 300 characters)</small>
                </div>
                <div class="botLongDescPreviewBox">
                    <label>Long Description Preview</label>
                    <div class="card bg-light mb-3">
                        <div class="card-body">
                            <div id="botLongDescPreview"></div>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="botWebsite">Website</label>
                    <input type="url" class="form-control" id="botWebsite" value="<%= botDB.botWebsite %>" placeholder="https://zyrouge.gq" autocomplete="off">
                </div>
                <div class="form-group">
                    <label for="botSupport">Support Server</label>
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                          <span class="input-group-text">https://discord.gg/</span>
                        </div>
                        <input type="text" class="form-control" id="botSupport" value="<%= botDB.botServer %>" placeholder="8KV5zCg" autocomplete="off">
                    </div>
                </div>
                <div class="form-group">
                    <label for="botInvite">Invite URL</label>
                    <input type="url" class="form-control" id="botInvite" value="<%= botDB.customInvite %>" aria-describedby="botInvitehelp" placeholder="https://discordapp.com/oauth2/authorize?client_id=<%= bot.user.id %>&scope=bot&permissions=8" autocomplete="off">
                    <small id="botInvitehelp" class="form-text text-muted">Can be generated at <a target="__blank" href="https://discordapi.com/permissions.html">Discord API Permissions</a></small>
                </div>
                <div class="form-group" id="tags-box">
                    <label class="mb-0">Bot Tags</label>
                    <small class="form-text text-muted mt-0 mb-2">Max. 4 tags</small>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="tag-moderation" value="moderation" name="tag" <% if (botDB.botTags.includes("moderation")) { %> checked <% } %>>
                        <label class="custom-control-label" for="tag-moderation">Moderation</label>
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="tag-fun" value="fun" name="tag" <% if (botDB.botTags.includes("fun")) { %> checked <% } %>>
                        <label class="custom-control-label" for="tag-fun">Fun</label>
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="tag-economy" value="economy" name="tag" <% if (botDB.botTags.includes("economy")) { %> checked <% } %>>
                        <label class="custom-control-label" for="tag-economy">Economy</label>
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="tag-leveling" value="leveling" name="tag" <% if (botDB.botTags.includes("leveling")) { %> checked <% } %>>
                        <label class="custom-control-label" for="tag-leveling">Leveling</label>
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="tag-utility" value="utility" name="tag" <% if (botDB.botTags.includes("utility")) { %> checked <% } %>>
                        <label class="custom-control-label" for="tag-utility">Utility</label>
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="tag-anime" value="anime" name="tag" <% if (botDB.botTags.includes("anime")) { %> checked <% } %>>
                        <label class="custom-control-label" for="tag-anime">Anime</label>
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="tag-meme" value="meme" name="tag" <% if (botDB.botTags.includes("meme")) { %> checked <% } %>>
                        <label class="custom-control-label" for="tag-meme">Meme</label>
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="tag-music" value="music" name="tag" <% if (botDB.botTags.includes("music")) { %> checked <% } %>>
                        <label class="custom-control-label" for="tag-music">Music</label>
                    </div>
                </div>
                <div class="alert alert-dismissible alert-danger" id="form-error-popup" style="display: none;"></div>
                <p style="color: #555;">By clicking submit, you agree to our's and Discord's TOS.</p>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
        <br><br>
    </div>
</body>

<script>
$(function() {
    renderDesc();

    const url = new URL(window.location.href);
    const success = url.searchParams.get("success");
    if(success === "true") {
        $("#success-save").css("display", "block");
    } else if(success === "false") {
        const error = url.searchParams.get("error");
        $("#error-save strong").text(`${$("#error-save strong").text()} ${error || ""}`);
        $("#error-save").css("display", "block");
    }

    const warning = url.searchParams.get("warning");
    if(warning) {
        $("#warning-save").text(warning);
        $("#warning-save").css("display", "block");
    }

    $("form").submit(function (event) {
        event.preventDefault();

        const validated = validateForm();
        if(!validated) return
    
        const form = $(this);

        const tags = [];
        $.each($("input[name='tag']:checked"), function() {
            tags.push($(this).val());
        });

        const data = {
            id: $("#botID").val().toString() || null,
            prefix: $("#botPrefix").val() || null,
            description: {
                short: $("#botShortDesc").val() || null,
                long: $("#botLongDesc").val() || null
            },
            website: $("#botWebsite").val() || null,
            support: $("#botSupport").val() || null,
            invite: $("#botInvite").val() || null,
            tags
        };

        $.ajax({
            type: form.attr("method"),
            url: form.attr("action"),
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (resp) {
                if(resp.code === "OK") window.location.replace("/bots/<%= botInfo.id %>/edit?success=true");
                else window.location.replace("/bots/<%= botInfo.id %>/edit?success=false&error=" + resp.e);
            },
            error: function (resp) {
                if(resp.responseJSON.code === "INVALID_BOT") {
                    setValidation($("#botID"), false);
                }
                $("#form-error-popup").html(`<strong>${resp.responseJSON.message}</strong>`).css("display", "block");
            }
        });
    });
});

function validateForm() {
    let INVALID_STUFFS = 0;

    /* ID */
    const botID = $("#botID");
    if(botID) {
        const isValid = checkValid(botID);
        setValidation(botID, isValid);
        if(!isValid) INVALID_STUFFS += 1;
    }

    /* Prefix */
    const botPrefix = $("#botPrefix");
    if(botPrefix) {
        const isValid = checkValid(botPrefix);
        setValidation(botPrefix, isValid);
        if(!isValid) INVALID_STUFFS += 1;
    }

    /* Short Desc */
    const botShortDesc = $("#botShortDesc");
    if(botShortDesc) {
        const isValid = checkValid(botShortDesc);
        setValidation(botShortDesc, isValid, "char_100");
        if(!isValid) INVALID_STUFFS += 1;
    }

    /* Long Desc */
    const botLongDesc = $("#botLongDesc");
    if(botLongDesc) {
        const isValid = checkValid(botLongDesc);
        setValidation(botLongDesc, isValid, "char_300");
        if(!isValid) INVALID_STUFFS += 1;
    }

    const isValid = INVALID_STUFFS === 0;

    if(!isValid) $("#form-error-popup").text(`Oh snap! ${INVALID_STUFFS} invalid inputs were found! Click submit after fixing them.`).css("display", "block");

    return isValid;
}

function checkValid(div, key) {
    if(!div.val()) return false;
    if(key === "char_100" && !(div.val().length >= 50 && div.val().length <= 100)) return false;
    if(key === "char_300" && div.val().length <= 300) return false;
    return true;
}

function setValidation(div, valid) {
    const INVALID_CLASS = "is-invalid";
    const VALID_CLASS = "is-valid";

    if(valid) {
        if(div.hasClass(INVALID_CLASS)) div.removeClass(INVALID_CLASS);
        div.addClass(VALID_CLASS);
    } else {
        if(div.hasClass(VALID_CLASS)) div.removeClass(VALID_CLASS);
        div.addClass(INVALID_CLASS);
    }
}

const longDesc = $('#botLongDesc');
const longDescPreview = $('#botLongDescPreview');

longDesc.on('change keyup paste', renderDesc);
function renderDesc() {
    const markdownRender = marked(longDesc.val());
    const allowedTags = sanitizeHtml.defaults.allowedTags.concat(["img", "center"]);
    const sanitizedRender = sanitizeHtml(markdownRender, {
        allowedTags
    });
    longDescPreview.html(sanitizedRender);
}

$(".custom-control-input").on('change', function() {
    const tags = [];
    $.each($("input[name='tag']:checked"), function() {
        tags.push($(this).val());
    });
    if(tags.length > 4) {
        this.checked = false;
    }
});
</script>

<style>
.form-group.required label:after {
    content:" *";
    color:red;
}
</style>
</html>