<?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_pengguna';
	$MY_SESSION_NAME = 'sejahtera_authen_usr';
	$auth_name = 'sejahtera_authen';
	$timeout_limit = 9000000;
	
	$bypass_check_script = [];
	$bypass_check_script[] = "login.php";
	$bypass_check_script[] = "login-check.php";
	$bypass_check_script[] = "logout.php";
	$bypass_check_script[] = "profile.php";
	$bypass_check_script[] = "profile-info_insert.php";
	$bypass_check_script[] = "profile-pwd_insert.php";
	$bypass_check_script[] = "normalPrint.php";
	$bypass_check_script[] = "permission.php";
	//$bypass_check_script[] = "index.php";
	$bypass_check_script[] = "general.php";
	$bypass_check_script[] = "register.php";
	$bypass_check_script[] = "register-insert.php";
	$bypass_check_script[] = "p01_borang.php";
	$bypass_check_script[] = "p02_borang.php";
	$bypass_check_script[] = "p05_borang.php";
	$bypass_check_script[] = "p07_borang.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>';
	*/
	
	if($validSess==TRUE && !in_array($phpscript_name, $bypass_check_script)){
		header('Location: '.$BASE_FOLDER.'login.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_pengguna = ?";
	
				$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_pengguna = ".$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_pengguna = ".$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.php" && $phpscript_name != "index.php" && $phpscript_name != "katalaluan.php") //need to re-login
					{
						header('Location: '.$BASE_FOLDER.'login.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.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';
					}
				}
			}
		
		}
	}
	
	/*
	function getMenu($myMainMenu)
	{
		if(count($myMainMenu) > 0)
		{
			foreach($myMainMenu as $key => $menu) {
				
				foreach($menu['child'] as $key2 => $menu2) 
				{
					//echo 'menu2 = '.$menu2['katName'].'<br>';
					if (count($menu2['menu']) > 0)
					{
						foreach($menu2['menu'] as $key3 => $menu3) 
						{
							//echo '&nbsp;&nbsp;&nbsp;menu3 = '.$menu3['name'].'<br>';
						}
					}
				}
				
				if (isset($menu['child'])) //for sub menu
				{
					echo '<li class="m-menu__item  m-menu__item--submenu m-menu__item--rel" data-menu-submenu-toggle="click" data-redirect="true" aria-haspopup="true">';
					echo '<a  href="#" class="m-menu__link m-menu__toggle">';
						echo '<span class="m-menu__item-here"></span>';
						echo '<span class="m-menu__link-text">';
							echo $menu['katName'];
						echo '</span>';
						echo '<i class="m-menu__hor-arrow la la-angle-down"></i>';
						echo '<i class="m-menu__ver-arrow la la-angle-right"></i>';
					echo '</a>';
					
					echo '<div class="m-menu__submenu  m-menu__submenu--fixed m-menu__submenu--left" style="width:'.(250 * count($menu['child'])).'px">';
						echo '<span class="m-menu__arrow m-menu__arrow--adjust"></span>';
						echo '<div class="m-menu__subnav">';
							echo '<ul class="m-menu__content">';
								foreach($menu['child'] as $key2 => $menu2) 
								{
									echo '<li class="m-menu__item">';
										echo '<h3 class="m-menu__heading m-menu__toggle">';
											echo '<span class="m-menu__link-text">';
												echo $menu2['katName'];
											echo '</span>';
											echo '<i class="m-menu__ver-arrow la la-angle-right"></i>';
										echo '</h3>';
										if (count($menu2['menu']) > 0)
										{
											echo '<ul class="m-menu__inner">';
											foreach($menu2['menu'] as $key3 => $menu3) 
											{
												echo '<li class="m-menu__item "  data-redirect="true" aria-haspopup="true">';
													echo '<a href="'.$menu3['url'].'" class="m-menu__link ">';
														echo '<i class="m-menu__link-bullet m-menu__link-bullet--dot">';
															echo '<span></span>';
														echo '</i>';
														echo '<span class="m-menu__link-text">';
															echo $menu3['name'];
														echo '</span>';
													echo '</a>';
												echo '</li>';
											}
											echo '</ul>';
										}
									echo '</li>';
								}
							echo '</ul>';
						echo '</div>';
					echo '</div>';
				}
				if (count($menu['menu']) > 0) //for direct menu from main 
				{
					foreach($menu['menu'] as $key4 => $menu4) 
					{
						echo '<li>';
						echo '<a href="'.$menu4['url'].'">';
						echo '<i class="icon-layers"></i>'.$menu4['name'].'233</a>';
						echo '</li>';
					}
				}
			}
		}
	}
	
	function getSideMenu($mySideMenu)
	{
		ksort($mySideMenu);
		foreach($mySideMenu as $key => $item) 
		{
			echo '<li class="m-menu__item  m-menu__item--submenu" aria-haspopup="true"  data-menu-submenu-toggle="hover" data-redirect="true">';
				echo '<a href="'.$item['url'].'" class="m-menu__link">';
					echo '<i class="m-menu__link-icon '.$item['icon_side'].'"></i>';
					echo '<span class="m-menu__link-text">';
						echo $item['name'];
					echo '</span>';
					echo '<i class="m-menu__ver-arrow la la-angle-right"></i>';
				echo '</a>';
				echo '<div class="m-menu__submenu ">';
					echo '<span class="m-menu__arrow"></span>';
					echo '<ul class="m-menu__subnav">';
						echo '<li class="m-menu__item  m-menu__item--parent" aria-haspopup="true"  data-redirect="true">';
							echo '<span class="m-menu__link">';
								echo '<span class="m-menu__link-text">';
									echo $item['name'];
								echo '</span>';
							echo '</span>';
						echo '</li>';
					echo '</ul>';
				echo '</div>';
			echo '</li>';
		}
	}
	*/
	
?>