<?php
	include_once('global.php');
	include_once('img.svg.php');
	date_default_timezone_set("Asia/Kuala_Lumpur"); 
	error_reporting(E_ERROR);
	
	$MY_TB_NAME = 't_pemohon';
	$MY_SESSION_NAME = 'sejahtera_authen_usr_public';
	$auth_name = 'sejahtera_authen_public';
	$timeout_limit = 9000000;
	
	$bypass_check_script = [];
	$bypass_check_script[] = "login_pemohon.php";
	$bypass_check_script[] = "login_pemohon-check.php";
	$bypass_check_script[] = "login_pemohon-get_soalan.php";
	$bypass_check_script[] = "logout_pemohon.php";
	$bypass_check_script[] = "profile_pemohon.php";
	$bypass_check_script[] = "profile_pemohon-info_insert.php";
	$bypass_check_script[] = "profile_pemohon-pwd_insert.php";
	$bypass_check_script[] = "normalPrint.php";
	$bypass_check_script[] = "permission.php";
	$bypass_check_script[] = "index_pemohon.php";
	$bypass_check_script[] = "general.php";
	
	$auth = new auth($auth_name);
	
	// Test session authentication 
	$BASE_FOLDER = '/app/';
	//$phpscript_name = substr($_SERVER["PHP_SELF"], strrpos($_SERVER["PHP_SELF"], "/")+1, strlen($_SERVER["PHP_SELF"]));
	$phpscript_name = str_replace($BASE_FOLDER, '', $_SERVER["PHP_SELF"]);																 
	//$phpscript_name = str_replace($BASE_FOLDER, '', $_SERVER["PHP_SELF"]);
	$validSess = $auth->test_session($timeout_limit);
	//var_dump( $_SERVER["PHP_SELF"]);
	//var_dump( $phpscript_name);
	//exit(0);
	/*
	var_dump($phpscript_name);
	echo '<br>';
	var_dump($validSess);
	echo '<br>';
	var_dump($bypass_check_script);
	echo '<br>';
	var_dump(!in_array($phpscript_name, $bypass_check_script));
	echo '<br>';
	var_dump(in_array($phpscript_name, $bypass_check_script));
	echo '<br>';
	*/
	
	if($validSess==TRUE && !in_array($phpscript_name, $bypass_check_script)){
		//header('Location: '.$BASE_FOLDER.'login_pemohon.php');
		exit;
	}
	else
	{
		/*
		echo "validSess = $validSess<br>";
		echo "valid authen_usr<br>";
		echo "MY_SESSION_NAME = ".$MY_SESSION_NAME."<br>";
		echo '<pre>';
		var_dump($_SESSION);
		echo '</pre>';
		*/
		
		if(isset($_SESSION[$MY_SESSION_NAME]))
		{
			//echo "set authen_usr<br>";
			$my_details = $_SESSION[$MY_SESSION_NAME];
			$MY_COOKIE_NAME = 'sejahtera_role';
			setcookie($MY_COOKIE_NAME, $my_details->user_level, time() + (86400 * 30), "/"); // 86400 = 1 day
			
			try
			{
				$PDO->beginTransaction();
				
				$PASS_VALUE_SETUP = 0;
				//GET LAST masaakhiraktif
				$Query = "SELECT masaakhiraktif, masaakhirlogout
				  FROM $MY_TB_NAME
				  WHERE id_pemohon = ?";
	
				$PDO_stmt = $PDO->prepare($Query);
				$PDO_stmt->bindValue(1, $my_details->usr_id, PDO::PARAM_STR);
				$PDO_stmt->execute();
				$detail_list = $PDO_stmt->fetch(PDO::FETCH_ASSOC);
				//echo "usr_id = ".$my_details->usr_id."<br>";
				//echo ($detail_list['masaakhiraktif'])." vs ".($detail_list['masaakhirlogout'])."<br>";
				//echo strtotime($detail_list['masaakhiraktif'])." vs ".strtotime($detail_list['masaakhirlogout'])."<br>";
				//echo (strtotime("now") - strtotime($detail_list['masaakhiraktif']))."<br>";
				//timeout found, and didn't log out
				if((strtotime($detail_list['masaakhiraktif']) > strtotime($detail_list['masaakhirlogout'])) && (strtotime("now") - strtotime($detail_list['masaakhiraktif']) > 1200))
				{
					$PASS_VALUE_SETUP = 2;
					$pengguna_Array = array();
					$pengguna_Array[] = array('masaakhirlogout', date('Y-m-d H:i:s', strtotime($detail_list['masaakhiraktif']) + 900), PDO::PARAM_STR);
					$whereCondition = "WHERE id_pemohon = ".$my_details->usr_id;
					$PASS_COUNTER_SETUP += PDO_UPDATE($PDO, $MY_TB_NAME, $pengguna_Array, $whereCondition);
					
					$loginLog_Array = array();
					$loginLog_Array[] = array('id_pengguna', $my_details->usr_id, PDO::PARAM_INT);
					$loginLog_Array[] = array('id_peranan', $my_details->user_level, PDO::PARAM_INT);
					$loginLog_Array[] = array('status_login', 'B', PDO::PARAM_STR);
					$loginLog_Array[] = array('jenis_log', 'O', PDO::PARAM_STR);
					$loginLog_Array[] = array('bil_percubaan', 0, PDO::PARAM_INT);
					$loginLog_Array[] = array('tkh_log', date('Y-m-d H:i:s', strtotime($detail_list['masaakhiraktif']) + 900), PDO::PARAM_STR);
					$loginLog_Array[] = array('ip_address', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
					
					$PASS_COUNTER_SETUP += PDO_INSERT($PDO, 's_loginlog', $loginLog_Array);
				}
				else
				{
					$PASS_VALUE_SETUP = 1;
					$pengguna_Array = array();
					$pengguna_Array[] = array('masaakhiraktif', dateTimeNow(), PDO::PARAM_STR);
				
					$whereCondition = "WHERE id_pemohon = ".$my_details->usr_id;
					$PASS_COUNTER_SETUP += PDO_UPDATE($PDO, $MY_TB_NAME, $pengguna_Array, $whereCondition);
				}
				//*****************************************
				//COMMIT if PASS_COUNTER_SETUP == PASS_VALUE_SETUP
				//*****************************************
				if ($PASS_COUNTER_SETUP == $PASS_VALUE_SETUP)
				{
					//echo "PASS_COUNTER_SETUP = ".$PASS_COUNTER_SETUP.'<br>';
					//echo "PASS_VALUE_SETUP = ".$PASS_VALUE_SETUP.'<br>';
					$PDO->commit();
					if($PASS_VALUE_SETUP == 2 && $phpscript_name != "login_pemohon.php" && $phpscript_name != "index_pemohon.php") //need to re-login
					{
						header('Location: '.$BASE_FOLDER.'login_pemohon.php');
						exit;
					}
				}
				else
				{
					$PDO->rollBack();
				}
			}
			catch (Exception $e) 
			{
				$PDO->rollBack();
				echo "Failed: " . $e->getMessage();
			}
		}
	}
	
	//handle ajax, modal
	if(preg_match ('/^(.+)\-(.+)\.php$/', $phpscript_name))
	{
		$phpscript_name = preg_replace("/^(.+)\-(.+)\.php$/", '$1.php', $phpscript_name);
	}
	
	$bypass_check_script[] = "index_pemohon.php";
	if(!in_array($phpscript_name, $bypass_check_script)){
		$accessGrant = checkAccess($PDO, $my_details->user_level, $phpscript_name);
		if(!$accessGrant)
		{
			header('Location: '.$BASE_FOLDER.'permission.php');
			exit;
		}	
	}
		
	if(isset($my_details->user_level) && $my_details->user_level > 0)
	{
		//get all user pages id
		$user_stmt = $PDO->prepare("
			SELECT id_tetingkap
			FROM t_pautan 
			WHERE id_peranan = ?
			AND aktif = 1
		");
		$user_stmt->bindValue(1, $my_details->user_level, PDO::PARAM_INT);
		$user_stmt->execute();
		// put all into hash for easier comparison
		$userPages = array();
		while($res = $user_stmt->fetch(PDO::FETCH_ASSOC)) {
			$userPages[$res['id_tetingkap']]= 1;
		}
		
		//get all kategori and build main menu
		$mainKat_stmt = $PDO->prepare("
			SELECT id_kategori, id_parent, desk_kategori AS katName, susunan, icon
			FROM t_kategori
			WHERE id_parent = 0
			AND aktif = 1
			ORDER BY susunan
		");
		$mainKat_stmt->execute();
		$mainMenu = array();
		$sideMenu = array();
		while($mainKatResult = $mainKat_stmt->fetch(PDO::FETCH_ASSOC)) 
		{
			$mainMenu[$mainKatResult['id_kategori']] = $mainKatResult;
		}
		
		//get all kategori and build sub menu
		$kat_stmt = $PDO->prepare("
			SELECT id_kategori, id_parent, desk_kategori AS katName, susunan, icon
			FROM t_kategori
			WHERE aktif = 1
			ORDER BY susunan
		");
		$kat_stmt->execute();
		while($katResult = $kat_stmt->fetch(PDO::FETCH_ASSOC)) 
		{
			$openMe = false;
			//check in tetingkap table
			$tetingkap_stmt = $PDO->prepare("
				SELECT id_tetingkap, desk_tetingkap AS name, nama_skrip AS url, susunan, susunan_side, icon_side
				FROM t_tetingkap
				WHERE id_kategori = ?
				AND aktif = 1
				ORDER BY susunan
			");
			$tetingkap_stmt->bindValue(1, $katResult['id_kategori'], PDO::PARAM_INT);
			$tetingkap_stmt->execute();
			$tingkapArray = array();
			while($tetingkapResult = $tetingkap_stmt->fetch(PDO::FETCH_ASSOC)) 
			{
				if (array_key_exists($tetingkapResult['id_tetingkap'], $userPages))
				{
					$tingkapArray[] = $tetingkapResult;
					if($tetingkapResult['susunan_side'] > 0)
					{
						$sideMenu[$tetingkapResult['susunan_side']] = $tetingkapResult;
					}
				}
				
				if($phpscript_name == $tetingkapResult['url'])//is this page, open this kategory
				{
					$openMe = true;
				}
			}
			
			if(count($tingkapArray) > 0)
			{
				if($katResult['id_parent'] == '0') //put as main menu
				{
					if(is_null($mainMenu[$katResult['id_kategori']]['child']))
					{
						$mainMenu[$katResult['id_kategori']]['menu'] = $tingkapArray;
						if($openMe == true)
						{
							$mainMenu[$katResult['id_kategori']]['open'] = 'open';
						}
					}
				}
				else //sub menu
				{
					$tempArray = array();
					$tempArray = $katResult;
					$tempArray['menu'] = $tingkapArray;
					$mainMenu[$katResult['id_parent']]['child'][] = $tempArray;
					if($openMe == true)
					{
						$mainMenu[$katResult['id_parent']]['open'] = 'open';
					}
				}
			}
		
		}
	}	
?>