<?php

class userroles extends datatable
{
    protected static $table = array(
        "name" => "mis_user_roles",
        "primary" => "id",
        "creators" => "admin",
        "editors" => ""
    );

    protected static $data = array(
        "timestamp" => [
            "default" => "#timestamp"
        ],
        "user" => [],
        "role" => []
    );

    public static function has_roleassigned($user, $role)
    {

        $response = self::query("select * from " . static::$table['name'] . " where user = :user and role = :role", ["user" => $user, "role" => $role]);

        if ($response['count'] > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static function has_roleassigned_bycode($user, $role_code)
    {

        $response = self::query("select * from " . static::$table['name'] . " as r, mis_user_role_types as t where r.user = :user and r.role = t.id and t.code = :role", ["user" => $user, "role" => $role_code]);

        if ($response['count'] > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static function is_assigned($role_code, $user = null)
    {

        if ($user == null) {
            $user = auth::user_id();
        }

        $response = self::query("select * from " . static::$table['name'] . " as r, mis_user_role_types as t where r.user = :user and r.role = t.id and t.code = :role", ["user" => $user, "role" => $role_code]);

        if ($response['count'] > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static function assign($user, $role)
    {
        if ($role == 1) {
            return;
        }
        $response = self::query("insert into " . static::$table['name'] . " (user, role) values  (:user,:role)", ["user" => $user, "role" => $role]);
        if ($response['count'] > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static function remove($user, $role)
    {
        if ($role == 1) {
            return;
        }

        $response = self::query("delete from " . static::$table['name'] . " where user = :user and role = :role", ["user" => $user, "role" => $role]);

        if ($response['count'] > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static function assigned($user)
    {
        $response = self::query("select * from " . static::$table['name'] . " as u, mis_user_role_types as t where u.role = t.id and u.user = :user order by t.id", ["user" => $user]);

        if ($response['count'] > 0) {
            return $response['data'];
        } else {
            return false;
        }
    }

    public static function types()
    {
        $response = self::query("select * from mis_user_role_types");

        if ($response['count'] > 0) {
            return $response['data'];
        } else {
            return false;
        }
    }
}
