<?php

require_once dirname(__FILE__) . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('User');

/**
 * SESSION timeout.
 * 
 * @use $_SESSION['USER_SESSION_EXPIRE'] = 1800;// TODO: read from DB - ADMIN_USERS in authorize user or default value 30 min
 * @use $_SESSION['USER_SESSION_LAST_ACTIVITY'] = ;
 * 
 */
class S {

	public static function init() {
		@session_start();// PHP Notice:  A session had already been started - ignoring session_start()

		$ses_keys = array();
		$ses_keys[] = 'DEBUG';
		$ses_keys[] = 'USER_PROFILE';
		$ses_keys[] = 'CURRENT_MENU';
		$ses_keys[] = 'LAST_MENU';
		$ses_keys[] = 'LAST1_MENU';
		$ses_keys[] = 'THIS';
		$ses_keys[] = 'LAST_FUNCTION';
		$ses_keys[] = 'LAST1_FUNCTION';
		$ses_keys[] = 'CURRENT_FUNCTION';
		$ses_keys[] = 'USER_SESSION_LAST_ACTIVITY';
		$ses_keys[] = 'USER_SESSION_EXPIRE';
		foreach ($ses_keys as $k) {
			if (!isset($_SESSION[$k])) $_SESSION[$k] = null;
		}

		self::timeoutFetch();
	}

	public static function get($key) {
		$null = null;
		return (isset($_SESSION[$key]))? $_SESSION[$key] : $null;
	}

	/**
	 * TODO: ustalic czas trwania sesji np. wg. stanowiska
	 */
	public static function timeoutFetch() {
		if (empty($_SESSION['USER_SESSION_EXPIRE']) || $_SESSION['USER_SESSION_EXPIRE'] <= 0) {
			$_SESSION['USER_SESSION_EXPIRE'] = ini_get('session.gc_maxlifetime');//1800 - 3min
		}
		if (empty($_SESSION['USER_SESSION_LAST_ACTIVITY'])) {
			$_SESSION['USER_SESSION_LAST_ACTIVITY'] = time();
		}
	}

	/**
	 * Check if user is logged in, and how much time not clicked.
	 */
	public static function timeoutCheck() {
		if (!User::logged()) {// if not logged in dont check timeout
			return false;
		}

		$time = time();
		$last_activity = V::get('USER_SESSION_LAST_ACTIVITY', 0, $_SESSION, 'int');
		if ($last_activity <= 0) {// error last activity not set
			return false;
		}
		$ses_expire = V::get('USER_SESSION_EXPIRE', 0, $_SESSION, 'int');
		if (!$ses_expire) {// error expire not set
			return false;
		}

		if ($time - $last_activity > $ses_expire) {
			// last request was more than 30 minates ago
			self::destroy();
			return false;
		} else {
			return true;
		}
	}

	public static function destroy() {
		session_destroy();// destroy session data in storage
		session_unset();// unset $_SESSION variable for the runtime
	}

	public static function timeout_update() {// TODO: legacy
		self::timeoutUpdate();
	}

	public static function timeoutUpdate($force = false) {
		if ($force) {
			$_SESSION['USER_SESSION_LAST_ACTIVITY'] = time();
			return true;
		}
		else if (self::timeoutCheck()) {
			$_SESSION['USER_SESSION_LAST_ACTIVITY'] = time();
			return true;
		}
		return false;
	}

	public static function timeout_get() {// TOOD: legacy
		return self::timeoutGet();
	}

	public static function timeoutGet() {
		if (self::timeoutCheck()) {
			$ret = $_SESSION['USER_SESSION_EXPIRE'] - (time() - $_SESSION['USER_SESSION_LAST_ACTIVITY']);
		} else {
			$ret = 'expired';
		}
		return $ret;
	}

	public static function show_session_timer() {
		echo '<code id="'."session-timer".'" style="padding:0 5px;font-weight:bold;color:red;" title="Czas sesji">'."".'</code>';
	}

	public static function timeout_update_js() {
		self::printTimeoutUpdateJs();
	}

	public static function printTimeoutUpdateJs() {
		if (!User::logged()) {
			return;
		}

		//echo"\n".'<script type="text/javascript" src="stuff/jquery.js"></script>';
		?>
		<script type="text/javascript">
var _sesTimerEl=null;
var _sesExpireTimer='<?php echo $_SESSION['USER_SESSION_EXPIRE']; ?>';
var _sesExpireCheck=false;

function sesExpireTimeoutUpdate(){
	//console.log('sesExpireTimeoutUpdate: ' + _sesExpireTimer);
	if(!_sesTimerEl) return;
	if(_sesExpireTimer>=0){
		var min = Math.floor(_sesExpireTimer / 60);
		var sek = _sesExpireTimer % 60;
		if (sek < 10) { sek = '0' + sek; }
		_sesTimerEl.innerHTML='' + min + ':' + sek + '';
		window.setTimeout('sesExpireTimeoutUpdate()', 1000);
	}else{
		_sesTimerEl.innerHTML='expired!';
		window.setTimeout('sesExpireTimeoutUpdate()', 1000);
	}
	_sesExpireTimer-=1;
}


var sessionTimeoutStop = false;
var sessionTimeoutCheckFreq = 5;
var sessionTimeoutCheck = sessionTimeoutCheckFreq;
function sesAjaxTimerCheck(){
	if (sessionTimeoutStop) return;
	jQuery.get('session-expire.php'
		, {task: 'getTimer'}
		, function(data){
			if (sessionTimeoutStop) return;
			if (data==='expired' || data === '0' || data === '401: Unauthorized') {
				_sesExpireTimer=-1;// logout

				var exprModal=document.getElementById('session-timer-modal');
				if (!exprModal) {
					var modalHtml = '<div id="session-timer-modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="session-timer-modal-label" aria-hidden="true">' +
						'	<div class="modal-header">' +
						'		<h3 id="session-timer-modal-label">Zostałeś wylogowany</h3>' +
						'	</div>' +
						'	<div class="modal-footer">' +
						'		<a href="index.php" class="btn btn-primary">Zaloguj</a>' +
						'	</div>' +
						'</div>';
					exprModal = jQuery(modalHtml).appendTo('body');
				}
				jQuery('#session-timer-modal').modal({show: true, keyboard: false, backdrop: 'static'});

			} else {
				//console.log('session time = '+data);
				_sesExpireTimer=data;
			}
		}
	);
	if (sessionTimeoutStop) return;
	if(_sesExpireTimer>=0){
		window.setTimeout('sesAjaxTimerCheck()', sessionTimeoutCheckFreq * 1000);
		_sesExpireCheck=false;
	}else{
		// last chance
//		if (_sesExpireCheck) {
//			alert('Your current Session is over.');
//		} else {
//			window.setTimeout('sesAjaxTimerCheck()', sessionTimeoutCheckFreq * 1000);
//			_sesExpireCheck=true;
//		}
	}
}

jQuery(document).ready(function(){
	_sesTimerEl=document.getElementById('session-timer');
	if(_sesTimerEl){
		_sesTimerEl.innerHTML='...';
		sesExpireTimeoutUpdate();
	}
	sesAjaxTimerCheck();
});

function stopTimer(){
	//console.log('stopTimer()...');
	sessionTimeoutStop = true;
	return true;
}
		</script>
		<?php
	}

}
