{% extends "base_settings_page.html" %}
{% block content %}

<a href="/admin/create_user" class="btn btn-primary">Create a new user</a>

<p>&nbsp;</p>

<table class="table table-hover" style="max-width: 1000px;" aria-describedby="Clients list">
    <thead>
    <tr>
        <th scope="col">Username</th>
        <th scope="col">First name</th>
        <th scope="col">Last name</th>
        <th scope="col">Email</th>
        <th scope="col">Account type</th>
        <th scope="col">Enabled</th>
        <th scope="col">Actions</th>
    </tr>
    </thead>
    <tbody>
    {% for u in users %}
    <tr id="row-user-{{ u.uid.0 }}">
        <td>{{ u.username }}</td>
        <td>{{ u.first_name }}</td>
        <td>{{ u.last_name }}</td>
        <td>{{ u.email }}</td>
        <td>{% if u.admin %}Admin{% else %}Regular user{% endif %}</td>
        <td>{% if u.enabled %}Enabled{% else %}Disabled{% endif %}</td>
        <td>
            <a href="/admin/edit_user?id={{ u.uid.0 }}">Edit</a>
            <a href="javascript:delete_user('{{ u.uid.0 }}', '{{ u.username }}')">Delete</a>
        </td>
    </tr>
    {% endfor %}
    </tbody>
</table>

<script>
    async function delete_user(id, username) {
        if(!confirm("Do you really want to delete " + username + "'s account?"))
            return;

        try {
            let data = new URLSearchParams();
            data.append("user_id", id);

            const res = await fetch("/admin/api/delete_user", {
                body: data,
                method: "POST",
            });

            if (res.status != 200)
                return alert("Failed to delete user account!");

            alert("User account was successfully deleted!");
            document.getElementById("row-user-" + id).remove()
        } catch(e) {
            console.error(e);
            alert("Failed to delete user account!");
        }
    }


</script>

{% endblock content %}