<?php

require_once('UserDataSet.php');
class User {
    protected $_username, $_loggedIn, $_userId, $_accessLevel;

    public function getUsername() {
        return $this->_username;
    }
    public function getUserId() {
        return $this->_userId;
    }
    public function __construct() {
        session_start();

        $this->_username = "None";
        $this->_loggedIn = false;
        $this->_userId = "0";
        $this->_accessLevel = null;

        if(isset($_SESSION['login'])) {
            $this->_username = $_SESSION['login'];
            $this->_userId = $_SESSION['uid'];
            $this->_loggedIn = true;
            $this->_accessLevel = $_SESSION['accessLevel'];
        }
    }

    public function init() {
        $this->_username = "None";
        $this->_userId = "0";
        $this->_loggedIn = false;

        if(isset($_SESSION['login'])) {
            $this->_username = $_SESSION['login'];
            $this->_userId = $_SESSION['uid'];
            $this->_loggedIn = true;
        }
    }
    private function setAccessLevel($level) {
        $this->_accessLevel = $level;
        $_SESSION['accessLevel'] = $level;
    }
    public function getAccessLevel() {
        return $this->_accessLevel;
    }
    public function Authenticate($username, $password): bool
    {
        $users = new UserDataSet();
        $userDataSet = $users->checkUserCredentials($username, $password);
        $accessLevel = $users->checkAccessLevel($username);
        if(count($userDataSet) > 0) {
            $_SESSION['login'] = $username;
            $_SESSION['uid'] = $userDataSet[0]->getId();
            $this->setAccessLevel($accessLevel);
            $this->_loggedIn = true;
            $this->_username = $username;
            $this->_userId = $userDataSet[0]->getId();
            return true;
        }
        else {
            $this->_loggedIn = false;
            return false;
        }
    }

    public function logout() {
        unset($_SESSION['login']);
        unset($_SESSION['uid']);
        $this->_loggedIn = false;
        $this->_username = "None";
        $this->_userId = "0";
        session_destroy();
    }

    public function isLoggedIn(): bool
    {
        return $this->_loggedIn;
    }
    public function __destruct()
    {

    }


}
