<?php

class auth
{
    // check if a user is logged in
    public static function user()
    {
        return isset($_SESSION['mis-user']) ? $_SESSION['mis-user']['id'] : false;
    }

    public static function user_name()
    {
        //return self::user() ? $_SESSION['mis-user']['name'] : false;
        return users::get(auth::user_id())["shortname"];
    }

    public static function user_id()
    {
        return self::user() ? $_SESSION['mis-user']['id'] : false;
    }

    public static function user_institution()
    {
        return users::get(auth::user_id())["institution"];
    }

    public static function isadmin()
    {
        return (userroles::is_assigned("admin")) ? true : false;
    }

    public static function ispostmaster()
    {
        return (userroles::is_assigned("postmaster")) ? true : false;
    }

    public static function login($username, $password)
    {
        $sql = "SELECT * FROM users as u WHERE u.username=:username AND u.password=:password";

        $login = datatable::query($sql, ["username" => $username, "password" => md5($password)]);

        if ($login['success'] && $login['count'] > 0) {

            $user = $login['data'][0];

            self::create_user_session($login['data'][0]['id']);

            $return['success'] = true;
        } else {
            $return['success'] = false;
            $return['status'] = "INVALID";
        }

        return $return;
    }

    private static function create_user_session($id)
    {

        $user = users::get($id);

        if ($user) {

            if (isset($_SESSION['mis-user'])) {
                unset($_SESSION['mis-user']);
            }

            $_SESSION['mis-user'] = array(
                "timestamp" => timestamp(),
                "id" => $id,
                "name" => $user['shortname'],
                "key" => "tempuserkey"
            );

            return true;
        } else {
            return false;
        }
    }
}
