<?php
namespace App\UserAccess;

class UserAccess extends UserAccessAbstract
{

	/**
	 * The selected user id
	 * @var int
	 */
	protected $idUser = null;

	/**
	 * The protected constructor...
	 */
	public function __construct($idUser)
	{
		$this->idUser = $idUser;
	}

	/**
	 * If section is inactive then user doens't have access to this and return false
	 * {@inheritDoc}
	 * @see \App\UserAccess\UserAccessAbstract::hasAccessToSection()
	 */
	public function hasAccessToSection($section)
	{
		$sectionsList = \Entity\User::select($this->idUser)->accessSectionsList;
		return $sectionsList[$section]??false;
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\UserAccess\UserAccessAbstract::hasAccessToOption()
	 */
	public function hasAccessToOption($option)
	{
		$optionsList = \Entity\User::select($this->idUser)->accessOptionsList;
		return !empty($optionsList[$option]);
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\UserAccess\UserAccessAbstract::getAccessOptionValue()
	 */
	public function getAccessOptionValue($option)
	{
		$optionsList = \Entity\User::select($this->idUser)->accessOptionsList;
		return $optionsList[$option]??false;
	}

	/**
	 * {@inheritDoc}
	 * @see \App\UserAccess\UserAccessAbstract::isAuthenticated()
	 */
	public function isAuthenticated()
	{

		// if no database check while login - cannot tell if the user is logged in or not
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();
		if ($CFG['auth']['authType']!='databaseCheck') {
			return null;
		}

		// get user details
		$userLoginEnt = \Entity\UserLoginSession::select($this->idUser);

		// check how much time has passed since his last click
		if ( (TIMESTAMP - $userLoginEnt->lastClick) > $this->getUserSessionLifetime() ) {
			return false;
		}

		return true;

	}

	protected function getUserSessionLifetime()
	{
		return \App\Config\PasswordSecurity::getInstance()->getUserSessionLifetimeCached();
	}


	/**
	 * Stores a keep-alive for this user,
	 * @see \App\UserAccess\UserAccessAbstract::refreshDbLoginSession()
	 */
	public function refreshDbLoginSession()
	{
		try {
			$userLoginSessEnt = \Entity\UserLoginSession::update($this->idUser);
			$userLoginSessEnt->lastClick = TIMESTAMP;
			$userLoginSessEnt->save();
		} catch (\App\Entity\Exception $e) {
			\Log::getInstance()->critical( sprintf( "Could not update login sessions `lastClick` into database for user id %s. Some other error messages might have been logged.", $this->idUser ) );
		}
	}

}
