<?php

class archive extends datatable
{
    protected static $data = array(
        "created_at" => [
            "locked" => true,
            "default" => "#timestamp"
        ],
        "created_by" => [
            "locked" => true,
            "default" => "#user"
        ],
        "lastupdated_at" => [
            "locked" => true,
            "default" => "#timestamp"
        ],
        "lastupdated_by" => [
            "locked" => true,
            "default" => "#user"
        ],
        "filename" => [],
        "description" => [],
        "filetype" => [],
        "filesize" => [],
        "category" => [],
        "hash" => [],
        "visible" => [],
        "downloads" => []
    );

    protected static $table = array(
        "name" => "mis_archive",
        "primary" => "id"
    );

    public static function getbyhash($hash)
    {
        $data =  self::query("select * from " . static::$table['name'] . " where hash = :hash", ["hash" => $hash]);

        if ($data['success'] && $data['count'] == 1) {
            return $data['data'][0];
        } else {
            return false;
        }
    }

    public static function categories()
    {
        $data =  self::query("SELECT c.id, c.name, c.shortname, c.description, x.count from mis_archive_categories as c left join (select count(*) as count, category from mis_archive group by category) as x on x.category = c.id");

        if ($data['success']) {
            return $data['data'];
        } else {
            return false;
        }
    }

    public static function subcategories($category = null)
    {
        if ($category) {
            $data =  self::query("SELECT c.id, c.name, c.icon, x.count from mis_inventory_categories as c left join (select count(*) as count, category from mis_inventory group by category) as x on x.category = c.id where c.parent = :parent", ["parent" => $category]);
        } else {
            $data =  self::query("SELECT c.id, c.name, c.shortname, c.icon, x.count from mis_inventory_categories as c left join (select count(*) as count, category from mis_inventory group by category) as x on x.category = c.id where c.parent is not null");
        }

        if ($data['success']) {
            return $data['data'];
        } else {
            return false;
        }
    }

    public static function filehash()
    {
        $hash = substr(sha1(rand()), 12);

        if (!self::getbyhash($hash)) {
            return $hash;
        } else {
            return self::filehash();
        }
    }


    public static function statusesbycategory($category)
    {

        $data =  self::query("SELECT * from mis_inventory_statuses as s left join (select count(*) as count, status from mis_inventory where category = :category group by status) as x on x.status = s.id", ["category" => $category]);

        if ($data['success']) {
            return $data['data'];
        } else {
            return false;
        }
    }
}
