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

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

page::header();
?>

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

<?php require "templates.php" ?>

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

    function show() {

        $("#list").html(UI_loading);
        var i = category();

        if (data[i]) {
            $("#list").html(Mustache.render(template, data[i]));
            filter();
        } else {
            $.getJSON(API + "archive/all.php", {
                category: i
            }, function(response) {
                data[i] = response;
                console.log(data[i]);
                $("#list").html(Mustache.render(template, data[i]));
                filter();
            });
        }


    }

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

    function filter() {

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

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

    }

    function changecategory(category) {
        $(".pill").removeClass("active");
        $("#pill_" + category).addClass("active");
        show();
    }

    function category() {
        return $(".pill.active").data("category");
    }
    changecategory(<?= $_GET["category"] ?? 1 ?>);
</script>


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