@{
    ViewData["Title"] = "Admin";
}
@inject IConfiguration config;
@{
    bool emailServerIsSetup = true;
    var mailConfig = config.GetSection("MailConfig").Get<MailConfig>();
    if (mailConfig is null || string.IsNullOrWhiteSpace(mailConfig.EmailServer))
    {
        emailServerIsSetup = false;
    }
}
@model AdminViewModel
<div class="container">
    <div class="row">
        <div class="col-1">
            <a href="/Home" class="btn btn-secondary btn-md mt-1 mb-1"><i class="bi bi-arrow-left-square"></i></a>
        </div>
        <div class="col-11">
            <span class="display-6">Admin Panel</span>
        </div>
    </div>
    <hr />
    <div class="row">
        <div class="col-md-5 col-12">
            <span class="lead">Tokens</span>
            <hr />
            <div class="row">
                <div class="col-6">
                    <button onclick="generateNewToken()" class="btn btn-primary btn-md mt-1 mb-1"><i class="bi bi-pencil-square me-2"></i>Generate User Token</button>
                </div>
                <div class="col-6 d-flex align-items-center">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" role="switch" id="enableAutoNotify" @(emailServerIsSetup ? "checked" : "disabled")>
                        <label class="form-check-label" for="enableAutoNotify">Auto Notify(via Email)</label>
                    </div>
                </div>
            </div>
            <table class="table table-hover">
                <thead class="sticky-top">
                    <tr class="d-flex">
                        <th scope="col" class="col-4">Token</th>
                        <th scope="col" class="col-6">Issued To</th>
                        <th scope="col" class="col-2">Delete</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (Token token in Model.Tokens)
                    {
                        <tr class="d-flex">
                            <td class="col-4" style="cursor:pointer;" onclick="copyToClipboard(this)">@token.Body</td>
                            <td class="col-6 text-truncate">@token.EmailAddress</td>
                            <td class="col-2">
                                <button type="button" class="btn btn-danger" onclick="deleteToken(@token.Id, this)"><i class="bi bi-trash"></i></button>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
        <div class="col-12 col-md-7">
            <span class="lead">Users</span>
            <hr />
            <table class="table table-hover">
                <thead class="sticky-top">
                    <tr class="d-flex">
                        <th scope="col" class="col-4">Username</th>
                        <th scope="col" class="col-4">Email</th>
                        <th scope="col" class="col-2">Is Admin</th>
                        <th scope="col" class="col-2">Delete</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (UserData userData in Model.Users)
                    {
                        <tr class="d-flex" style="cursor:pointer;">
                            <td class="col-4">@userData.UserName</td>
                            <td class="col-4">@userData.EmailAddress</td>
                            <td class="col-2"><input class="form-check-input" type="checkbox" value="" onchange="updateUserAdmin(@userData.Id, this)" @(userData.IsAdmin ? "checked" : "")/></td>
                            <td class="col-2"><button type="button" class="btn btn-danger" onclick="deleteUser(@userData.Id, this)"><i class="bi bi-trash"></i></button></td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>
</div>
<script>
    function updateUserAdmin(userId, sender){
        var isChecked = $(sender).is(":checked");
        $.post('/Admin/UpdateUserAdminStatus', { userId: userId, isAdmin: isChecked }, function (data) {
            if (data){
                reloadPage();
            } else {
                errorToast("An error has occurred, please try again later.");
            }
        });
    }
    function reloadPage() {
        window.location.reload();
    }
    function deleteToken(tokenId) {
        $.post(`/Admin/DeleteToken?tokenId=${tokenId}`, function (data) {
            if (data) {
                reloadPage();
            } else {
                errorToast("An error has occurred, please try again later.");
            }
        });
    }
    function deleteUser(userId) {
        $.post(`/Admin/DeleteUser?userId=${userId}`, function (data) {
            if (data) {
                reloadPage();
            } else {
                errorToast("An error has occurred, please try again later.");
            }
        })
    }
    function copyToClipboard(e) {
        var textToCopy = e.textContent;
        navigator.clipboard.writeText(textToCopy);
        successToast("Copied to Clipboard");
    }
    function generateNewToken() {
        Swal.fire({
            title: 'Generate Token',
            html: `
                            <input type="text" id="inputEmail" class="swal2-input" placeholder="Email Address">
                            `,
            confirmButtonText: 'Generate',
            focusConfirm: false,
            preConfirm: () => {
                const emailAddress = $("#inputEmail").val();
                if (!emailAddress) {
                    Swal.showValidationMessage(`Please enter an email address`)
                }
                return { emailAddress }
            },
        }).then(function (result) {
            if (result.isConfirmed) {
                var autoNotify = $("#enableAutoNotify").is(":checked");
                $.get('/Admin/GenerateNewToken', { emailAddress: result.value.emailAddress, autoNotify: autoNotify }, function (data) {
                    if (data.success) {
                        reloadPage();
                    } else {
                        errorToast(data.message)
                    }
                });
            }
        });
    }
</script>