<?php

class User {

    public static function hashPass($password) {
        return password_hash($password, PASSWORD_ARGON2I);
    }

    private static function verifyPass($password, $hash) {
        if (password_verify($password, $hash)) {
            return true;
        } else {
            return false;
        }
    }

    public static function checkLogin() {
        if (isset($_SESSION['user'])) {
            $db = new DBClass();
            $query = "SELECT * FROM `" . Config::$db_tableusers . "` WHERE `id` = '" . $_SESSION['user'] . "'";
            if ($db->numRows($db->query($query)) != 1) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    public static function checkLevel($requiredlevel) {
        if (User::checkLogin()) { // We are logged in, lets continue this check
            $db = new DBClass();
            $query = "SELECT level FROM `" . Config::$db_tableusers . "` WHERE `id` = '" . $_SESSION['user'] . "'";
            $result = $db->fetchAll($db->query($query))[0];

            if ($result['level'] >= $requiredlevel) { // OK, our user DOES have the required level, return true
                return true;
            } else { // User was authenticated, but doesnt have the required level
                return false;
            }
        } else { // If user wasnt logged in, we return false
            return false;
        }
    }

    public static function userLevel() {

        // _SESSION['userlevel'] shows users current level. 50 = admin, 80 = leadadmin 100 = sysop
        if (!isset($_SESSION['lvl'])) {
            return 0;
        } else {
            $level = $_SESSION['lvl'];

            $db = new DBClass();
            $query = "SELECT * FROM `" . Config::$db_tableusers . "` WHERE `id` = '" . $_SESSION['user'] . "' AND `level` = '" . $level . "'";
            // We check the userlevel, and verifies that the userlevel exist on the user.
            if ($db->numRows($db->query($query)) != 1) {
                return 0;
            } else {
                return $level;
            }
        }
    }

}
