<?php
require_once(PATH_CONTROLLERS . "Common.php");
require_once(PATH_LIB . "LicenseFile.php");

require_once(PATH_MODELS . "admin/UserGroupClass.php");
require_once(PATH_MODELS . "admin/UserClass.php");
require_once(PATH_MODELS . "../controllers\admin\usergroup\UserGroup.php");
require_once(PATH_MODELS . "admin/UserRight.php");
require_once(PATH_MODELS . "admin/UserPasswordHistoryClass.php");

class Home extends GLBase
{
	private $type;
	private $clsUser;
	private $clsgroup;
	private $clsright;

	function __construct()
	{
		$this->db 		= $_SESSION[SE_DB];
		$this->orgid 	= $_SESSION[SE_ORGID];
		$this->clsUser 	= new UserClass($this->db);
		$this->clsgroup = new UserGroupClass($this->db);
		$this->clsright = new UserRight();
	}
	function __destruct()
	{
		unset($this->clsUser);
		unset($this->clsgroup);
		unset($this->clsright);
		unset($this->db);
	}
	public function processRequest($params)
	{
		$this->type = REQ_VIEW;
		if (isset($params) && count($params) > 0) {
			if (isset($params['type']))
				$this->type = $params['type'];
		}

		//The idle heartbeat only touches $_SESSION, so answer it before opening a database
		//connection. open() builds a brand new PDO connection every call, and paying for one
		//per minute per signed-in user just to stamp a timestamp is pure waste.
		if ($this->type == "C_KEEP_ALIVE") {
			if (!$this->checkSessionTimeout($this->type))
				return false;
			$this->processKeepSessionAlive();
			return true;
		}

		try {
			$this->db->open();
			$this->loadSetting();
			if (!$this->checkSessionTimeout($this->type)) {
				$this->db->close();
				return false;
			}

			switch ($this->type) {
				case Command::PortalHome:
					$this->processHomeInfo($params);
					break;
				case Command::PortalLogout:
					$this->processLogout();
					break;
				case REQ_VIEW:
					$this->processView();
					break;
				case Command::changePwd:
					$this->processChangePwd($params);
					break;
				case "C_CHANGE_BU":
					$this->processChangeBU($params);
					break;
				case "C_KEEP_ALIVE":
					$this->processKeepSessionAlive();
					break;
				default:
					$this->sendJsonResponse(Status::Error, "invalid request.", "", $this->type);
					break;
			}
			$this->db->close();
			return true;
		} catch (Exception $e) {
			$this->db->close();
			die($e->getMessage());
		}
	}


	private function processLogout()
	{
		session_unset();
		$this->sendJsonResponse(Status::Ok, "", "", $this->type);
	}
	private function processView()
	{
		ob_start();

		$row_user  = $this->clsUser->getRecord($_SESSION[SE_USERID]);
		$row_group = $this->clsgroup->getRecord($row_user[UserTable::C_USER_GROUP]);
		
		if (is_null($row_group[UserGroupTable::C_RIGHTS]))
			$this->clsright->initRights();
		else {
			$this->clsright->toRights($row_group[UserGroupTable::C_RIGHTS]);
		}
		$rights = $this->clsright->getAdminRights();

		include(PATH_VIEWS . "home/HomeView.php");
		echo Util::minifyHtml(html: ob_get_clean());
	}

	private function processChangeBU($params)
	{
		$_SESSION[SE_BU] = $this->getParam($params, "bu", "");
		$_SESSION[SE_LEDGER] = $this->getParam($params, "ledger", "");

		// Log::write($params);
		//generate new session id
		session_regenerate_id(true);
		$_SESSION[SE_ID] = session_id();
		// Log::write($_SESSION[SE_ID]);

		$data = "?c=" . Util::convertLink("Home") . "&d=" . time();
		$this->sendJsonResponse(Status::Ok, "", $data, $this->type);
	}
	private function processChangePwd($params)
	{
		$user_id = 0;
		$cls = new UserPasswordHistoryClass($this->db);

		if ($_SESSION[SE_USERID] != 0)
			$user_id = $_SESSION[SE_USERID];
		else
			$user_id = $params['id'];

		$user_row = $this->clsUser->getRecord($user_id);
		if ($this->clsUser->encryptPwd1($params['oldPwd']) != $user_row[UserTable::C_PWD1]) {
			$this->sendJsonResponse(Status::Error, "Wrong old password", "", $this->type);
			return;
		}

		if ($this->clsUser->encryptPwd1($params['newPwd']) == $user_row[UserTable::C_PWD1]) {
			$this->sendJsonResponse(Status::Error, "New password cannot be same as old password", "", $this->type);
			return;
		}

		if ($cls->checkPasswordSimiliarToPrevious($params['id'], $params['newPwd'])) {
			$cls->insertPasswordHistory($params['id'], $params['newPwd']);
			$this->clsUser->changePassword($params['id'], $params['newPwd']);
		} else {
			$this->sendJsonResponse(Status::Error, "New password cannot be same as previous 3 password", "", $this->type);
			return;
		}

		$strCheck = Util::checkPasswordComplexity($params['newPwd']);
		if ($strCheck != "") {
			$this->sendJsonResponse(Status::Error, $strCheck, "", $this->type);
			return;
		}

		try {
			$this->clsUser->changePassword($user_id, $params['newPwd']);
			$this->sendJsonResponse(Status::Ok, "Your password has been successfully changed ", "", $this->type);
		} catch (Exception $e) {
			Log::write("[CHG_PWD] " . $e->getMessage());
			$this->sendJsonResponse(Status::Error, "Unsuccessful database operation", "", $this->type);
		}
	}
	private function getHomeInfo()
	{
		ob_start();

		include(PATH_VIEWS . "prospect/ProspectToDoView.php");
		return Util::minifyHtml(ob_get_clean());
	}

	private function processHomeInfo($params)
	{
		ob_start();
		include(PATH_VIEWS . "prospect/ProspectToDoView.php");
		$dataReturn = array();

		$action_menu = '<section class="content-header" id="main-header" style="padding-left: 230px;">' .
			'</section>';

		$var_screen = str_replace("[index]", $params['index'], Util::minifyHtml(ob_get_clean()));
		$dataReturn = [];
		$dataReturn['htmlContent'] = $var_screen;
		$dataReturn['action_menu'] = $action_menu;
		$dataReturn['headTitle']  = "My Dashboard";
		$this->sendJsonResponse(Status::Ok, "Load Home Info", $dataReturn, $this->type);
	}

	private function getOrganizationName()
	{
		return $_SESSION[SE_PORT_ORGNAME];
	}
	private function getFullName()
	{
		return $_SESSION[SE_PORT_FULLNAME];
	}

	public function createMenuFunc($href, $desc, $type)
	{
		return "javascript:showPage('" . Util::convertLink($href) . "','" . $desc . "'" . ",'" . "$type" . "')";
	}

	private function createMobileFunc($href, $type)
	{
		return "javascript:showMobilePage('" . $href . "','" . "$type" . "')";
	}

	private function createJsFunc($func)
	{
		return "javascript:" . $func;
	}


	private function getUserProfile()
	{
		$userId = $_SESSION[SE_USERID];
		return $this->clsUser->getRecord($userId);
	}

	private function getStatusFilterComboBox()
	{
		$arr = array();
		$arr[] = array('code' => '0', 'desc' => 'All Claims');
		$arr[] = array('code' => '1', 'desc' => 'Not Submitted Claims');
		$arr[] = array('code' => '2', 'desc' => 'Pending Claims');
		$arr[] = array('code' => '3', 'desc' => 'Completed Claims');
		return Util::createOptionValue($arr);
	}

	private function processKeepSessionAlive() {
		$_SESSION["Active_Time"] = time();
		$this->sendJsonResponse(Status::Ok, "", "", $this->type);
	}
}
