<?php
ApplicationSettings::RegisterDefaultSetting("session", "expiry_window", "604800"); //a week

class Session extends DBObject {
	private static $_instance,$_user;
	
	public function __construct($id=0) {
		parent::__construct("sessions", "session_id", $id);
	}
	
	public function Save() {
		if ($this->SessionId==null)
			$this->SessionId=Utils::GenerateRandomString(32);
		
		$expiryWindow=(int)ApplicationSettings::GetSetting("session", "expiry_window");
		$this->SessionExpiry=time()+$expiryWindow;
		setcookie("session_id",$this->SessionId,$this->SessionExpiry,'/');
		
		parent::Save();
	}

	public function HasExpired(){
		return $this->SessionExpiry<time();
	}

	private static function Instantiate(){
		if (self::$_instance!=null)
			return;
		
		$instance=null;
		if (isset($_COOKIE['session_id'])){
			$instance=new Session($_COOKIE['session_id']);
			if ($instance->HasExpired())
				$instance=new Session();
		} else
			$instance=new Session();
		
		self::$_instance=$instance;
	}
	
	public static function Destroy(){
		self::Instantiate();
		
		$PDO=BaseRepository::GetPDO();
		$prep=$PDO->prepare("DELETE FROM sessions WHERE session_id=?");
		$prep->execute(array(self::$_instance->SessionId));
		
		self::$_instance=null;
	}
	
	public static function IsUserLoggedIn() {
		self::Instantiate();
		$user=self::GetLoggedInUser();
		return $user->UserId!=null;
	}

	public static function GetLoggedInUser() {
		self::Instantiate();
		
		if (isset(self::$_user))
			return self::$_user;
		
		self::$_user=new User(self::$_instance->UserId);
		
		return self::$_user;
	}
	
	public static function SetLoggedInUser($user) {
		self::Instantiate();
		self::$_instance->UserId=$user->UserId;
		self::$_instance->Save();
	}
}
