<?php
include "Connection.php";
$conn = new Connection();
//$login = '/';
        

if(isset($_REQUEST["funName"])){
	$db = $conn->getConnection();
	$fun = $_REQUEST["funName"];
        
	switch($fun){
		case "login":        
		case "logout":        
		case "checksession":
			$fun();
		break;
    
        default:
            $conn->message(false,"PAGE NOT FOUND");
        break;
        
	}
}else
{
     $conn->message(false,"PAGE NOT FOUND");
}

// Sessions Checking
function checksession() {
	global $conn;
	$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
	//$pageData = $conn->loadJSON($_REQUEST["lang"]);
	if(isset($_SESSION["userid"])) {
        
		$role = $_SESSION["role"];
		$start = (int)$_REQUEST["start"];
		$limit = (int)$_REQUEST["limit"];
		$isloaded = $_REQUEST["ismenuload"];
		$username = $_SESSION["username"];
		$obj = new stdClass();
		$obj->username = $_SESSION["username"];
		$obj->userid = $_SESSION["userid"];
		$obj->role = $_SESSION["role"];
		if(strtolower($isloaded) == "no") {
			if($role  == 0) {
				$module_str = "SELECT a.moduleid,a.modulepath, a.modulename, a.issubmodule,a.parentid FROM ".TABLE_MODULE." a WHERE a.status=1 AND a.issubmodule=0 ORDER BY `a`.`moduleid` ASC";
				$module_query = $conn->query($module_str);
				$mainarr = $module_query->fetchAll(PDO::FETCH_OBJ);
				for($id = 0;$id < count($mainarr);$id++){
					$mainarr[$id]->permission = "1|1|1";
				}
				$submodule_str = "SELECT a.moduleid,a.modulepath, a.modulename, a.issubmodule, a.parentid FROM ".TABLE_MODULE." a WHERE a.status=1 AND a.issubmodule=1 ORDER BY `a`.`moduleid` ASC";
				$submodule_query = $conn->query($submodule_str);
				$submodule_arr = $submodule_query->fetchAll(PDO::FETCH_OBJ);
				for($nid = 0;$nid < count($submodule_arr);$nid++){
					$submodule_arr[$nid]->permission = "1|1|1";
				}
				
				$module_arr = checkModule($mainarr,$submodule_arr,$lang);	
			}
			else {
               
				$module_str = "SELECT b.moduleid, b.modulename, b.modulepath,b.issubmodule,b.parentid,a.permission FROM ".TABLE_PERMISSION." a LEFT JOIN (SELECT * FROM ".TABLE_MODULE.")b ON b.moduleid=a.moduleid WHERE a.roleid='$role' AND b.status='1' AND b.issubmodule=0 ORDER BY b.`moduleid` ASC";
				$module_query = $conn->query($module_str);
				$mainarr = $module_query->fetchAll(PDO::FETCH_OBJ);
				$submodule_str = "SELECT b.moduleid, b.modulename, b.modulepath,b.issubmodule,b.parentid,a.permission FROM ".TABLE_PERMISSION." a LEFT JOIN (SELECT * FROM ".TABLE_MODULE.")b ON b.moduleid=a.moduleid WHERE a.roleid='$role' AND b.status='1' AND b.issubmodule=1 ORDER BY b.`moduleid` ASC";
				$submodule_query = $conn->query($submodule_str);
				$submodule_arr = $submodule_query->fetchAll(PDO::FETCH_OBJ);
				$module_arr = checkModule($mainarr, $submodule_arr, $lang);
			}
			$obj->control = $module_arr;			
		}
		$statusstr = "SELECT a.statusid, a.status FROM ".TABLE_STATUS." a ORDER BY a.statusid ASC LIMIT ".$start.",".$limit;
		$status_query = $conn->query($statusstr);
		$status_arr = $status_query->fetchAll(PDO::FETCH_OBJ);
		$obj->status = $status_arr;
		$conn->message(true,$conn->getMessage($lang,'login','success1'),$obj );
	}else{
		$conn->message(false,$conn->getMessage($lang,'login','error1'));
	}
}

// Login
function login() {
	global $conn;
    $lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
	$emp_code = escape_str($_REQUEST["emp_code"]);	
	$password = md5($_REQUEST["password"]);
	//$pageData = $conn->loadJSON($_REQUEST["lang"]);
    
	try{
		$str = "SELECT * FROM ".TABLE_USER." WHERE emp_code = '".$emp_code."' AND password='".$password."' AND (role = 1 OR role = 2) AND status = 1 AND is_deleted=0";
		$query = $conn->query($str);
		$row = $query->rowCount();
		
		if($row != 0) {
			$arr = $query->fetchAll(PDO::FETCH_OBJ);
			$obj = new stdClass();
			$obj->emp_code = $emp_code;
            $obj->username = $emp_code;
			$obj->userid = $arr[0]->userid;
            $obj->role=$arr[0]->role;
			$_SESSION["userid"] =$arr[0]->userid;
			$_SESSION["role"] =$arr[0]->role;
			$_SESSION["emp_code"] =$arr[0]->emp_code;
            $_SESSION["username"]=$arr[0]->fname;
            
			$role = $arr[0]->role;

			if($role  == 0) {
				$module_str = "SELECT a.moduleid, a.modulepath, a.modulename, a.issubmodule, a.parentid FROM ".TABLE_MODULE." a WHERE a.status = 1 AND a.issubmodule = 0 ORDER BY `a`.`moduleid` ASC";
				$module_query = $conn->query($module_str);
				
				$mainarr = $module_query->fetchAll(PDO::FETCH_OBJ);
				for($id = 0;$id < count($mainarr);$id++){
					$mainarr[$id]->permission = "1|1|1";
				}
				$submodule_str = "SELECT a.moduleid, a.modulepath, a.modulename, a.issubmodule, a.parentid FROM ".TABLE_MODULE." a WHERE a.status = 1 AND a.issubmodule = 1 ORDER BY `a`.`moduleid` ASC";
				$submodule_query = $conn->query($submodule_str);
				$submodule_arr = $submodule_query->fetchAll(PDO::FETCH_OBJ);
				
				for($nid = 0;$nid < count($submodule_arr);$nid++){
					$submodule_arr[$nid]->permission = "1|1|1";
				}
				$module_arr = checkModule($mainarr, $submodule_arr, $lang);
				$obj->control = $module_arr;
				$conn->message(true,$conn->getMessage($lang,'login','success1'),$obj);
			}
			else if($role  == 1 || $role  == 2) {
				$module_str = "SELECT b.moduleid, b.modulename, b.modulepath, b.issubmodule, b.parentid, a.permission FROM ".TABLE_PERMISSION." a LEFT JOIN (SELECT * FROM ".TABLE_MODULE.") b ON b.moduleid = a.moduleid WHERE a.roleid = '$role' AND b.status = 1 AND b.issubmodule = 0 ORDER BY `b`.`moduleid` ASC";
				$module_query = $conn->query($module_str);
				$mainarr = $module_query->fetchAll(PDO::FETCH_OBJ);
				$submodule_str = "SELECT b.moduleid, b.modulename, b.modulepath, b.issubmodule, b.parentid, a.permission FROM ".TABLE_PERMISSION." a LEFT JOIN (SELECT * FROM ".TABLE_MODULE." ) b ON b.moduleid=a.moduleid WHERE a.roleid = '$role' AND b.status = 1 AND b.issubmodule = 1 ORDER BY `b`.`moduleid` ASC";
				$submodule_query = $conn->query($submodule_str);
				$submodule_arr = $submodule_query->fetchAll(PDO::FETCH_OBJ);
				$module_arr = checkModule($mainarr, $submodule_arr, $lang);
				$obj->control = $module_arr;
				$conn->message(true,$conn->getMessage($lang,'login','success1'),$obj);
			}
			else {
				$conn->message(false,$conn->getMessage($lang,'login','error2'));
			}
		}
		else{
			$conn->message(false,$conn->getMessage($lang,'login','error3'));
		}
	}
	catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'login','error4'));
	}
}

// Logout
function logout() {
	global $conn;
	$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';
        
	session_destroy();
    $conn->message(true,$conn->getMessage($lang,'login','success1'));   
}

// Check Modules
function checkModule ($arr, $subarr, $lang){
	global $conn;
	$parentarray = array();
	$submodularr = array();
	$submodulparentarr = array();
	try{
		for($id = 0; $id < count($arr); $id++){
			$parentarray[] = $arr[$id]->moduleid;
			$obj = subModule($arr[$id],$subarr);
			if($obj->cont){
				$arr[$id]->menuitems = $obj->items;
				$arr[$id]->issubmenu = true;
			}else{
				$arr[$id]->issubmenu = false;
			}
		}
		for($mid = 0; $mid < count($subarr); $mid++){
			if(!array_search($subarr[$mid]->parentid,$parentarray)){
				$submodulparentarr[] = $subarr[$mid]->parentid; 
				$submodularr[] = $subarr[$mid];
			}
		}
		$returnArr = array_unique($submodulparentarr);
		if(count($returnArr) != 0){
			for($kid = 0;$kid < count($returnArr); $kid++){
				$moduleid = $returnArr[$kid];
				$module_str = "SELECT a.moduleid,a.modulepath, a.modulename, a.issubmodule, a.parentid FROM ".TABLE_MODULE." a WHERE a.status = 1 AND a.issubmodule = 0 AND a.moduleid = '$moduleid'";
				$module_query = $conn->query($module_str);
				$mainarr = $module_query->fetchAll(PDO::FETCH_OBJ);
			}
			for($nid = 0; $nid < count($mainarr);$nid++){
				$mainarr[$nid]->permission = "0|0|0";
				$mainarr[$nid]->modulepath = "";
				$obj = subModule($mainarr[$nid],$submodularr);
				if($obj->cont){
					$mainarr[$nid]->menuitems = $obj->items;
					$mainarr[$nid]->issubmenu = true;
				}
			}
		}
		
	}catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'login','error4'));
	}
	return $arr;
	
}

// Check Sub Modules
function checkSubModule($obj,$subarr){
	global $conn;
	$subobj = new stdClass();
	$subobj->cont = false;
	$itemarr = array();
	try{
		for($id = 0; $id < count($subarr); $id++){
			if($subarr[$id]->moduleid == $obj->parentid){
				$subobj->cont = true;
				$itemarr[] = $subarr[$id];
				$subobj->items = $itemarr;
			}
		}
		
	}catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'login','error4'));
	}
	return $subobj;
	
}

// Sub Modules
function subModule($obj,$subarr){
	global $conn;
	$subobj = new stdClass();
	$subobj->cont = false;
	$itemarr = array();
	try{
		for($id = 0; $id < count($subarr); $id++){
			if($subarr[$id]->parentid == $obj->moduleid){
				$subobj->cont = true;
				$itemarr[] = $subarr[$id];
				$subobj->items = $itemarr;
			}
		}
		
	}catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'login','error4'));
	}
	return $subobj;
	
}