<?php
require "../../src/config.php";

//check permissions
if (!auth::isadmin()) {
    router::redirect("login");
}

page::set([
    "title" => "Users",
    "nav-parent" => "admin_users",
    "layout" => "admin",
    "size" => "box-full"
]);

page::header();
?>

<div class="card">
    <div class="card-body">
        <div id="list"></div>
    </div>
</div>

<script id="template" type="text/template">

    <div class="datalist">

        {{#data}} 

            <div class="listitem" id="{{id}}">

                    <div class="row listitem-content">

                        <div class="col li-icon pe-2">
                            <span class=""><?= UI::icon("profile") ?></span> 
                        </div>
                        <div class="col">
                        <div class="text-md">{{name}}</div>
                        <div class="text-muted text-xs">{{designation}}</div>

                        <span class=" " hidden>
                            {{#roles}}
                            <span class="text-xs">{{name}}</span>
                            {{/roles}}
                        </span>
                        </div>
                        <div class="col-3">
                            {{#lastseen}}
                                <span class="text-muted text-xs">{{lastseen}}</span>
                            {{/lastseen}}
                        </div>
                        <div class="col-1">
                            <a href="update?id={{id}}"> <?= UI::icon("edit") ?></a>
                        </div>

                    </div>



            </div>
        
        {{/data}}

    </div>
    
</script>

<script>
    var data = [];
    var template = $("#template").html();

    function show() {

        $("#list").html(UI_loading);

        $.getJSON(API + "users.php", function(response) {
            data = response;
            console.log(data);
            $("#list").html(Mustache.render(template, data));
        });
    }

    show();


    $("#search").on("input", filter);
    $("#institute_select").on("change", filter);

    function filter() {

        var search = new RegExp($("#search").val(), "i");
        var search_key = $("#search_select").find(":selected").data("key");
        var institution = $("#institute_select").find(":selected").val();

        console.log(search + ", " + ", " + search_key + ", " + institution);
        console.log($("#search").val());

        $.each(data["data"], function(key, value) {
            if (value[search_key].search(search) != -1 && (institution == value["institution"] || institution == "all")) {
                $("#" + value.id).slideDown(200);
            } else {
                $("#" + value.id).slideUp(200);
            }
        });

    }

    $("#search_select").on("change", function() {
        $("#search").val("").trigger("input");
    });
</script>


<?php page::footer(); ?>