<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$app = "assets/app";
if (!empty($_GET["obdebug"]))
{
	$app = "assets/app2";
}

$base_url = base_url();

$is_logged_in = $this->session->userdata('is_logged_in') ? true : false;

//$this->session->userdata("name");
$licmanager = get_user_data("licmanager", true);
$licmanager = empty($licmanager) ? false : true;

$cId = null;
if($is_logged_in){
		$userData = $this->session->userdata("user");
		if(!empty($userData) && !empty($userData["email"]) && $userData["email"] != "null")
		{
			$email = $userData["email"];
			$LoggedInUser =array("email" =>$email,
			"id" =>$this->session->userdata()["user"]["id"],
			"name" => !empty($userData["name"]) ? $userData["name"] : "",
			"logged-on" => gmdate('Y-m-d H:i:s'));
			// $tmp = 	json_encode($LoggedInUser);
			echo '<script>
				var loggedInusers = JSON.parse(localStorage.getItem("loggedInUsers"));
				var id = "'.$this->session->userdata()["user"]["id"].'"
				var alreadyAddedAccunt = false;
				if(loggedInusers && loggedInusers.length) {
					loggedInusers.forEach((element ,idx) => {
						if(element.id == id)
						{
							loggedInusers[idx] = '. json_encode($LoggedInUser,JSON_UNESCAPED_SLASHES).';
							alreadyAddedAccunt = true;
						}
					});
				} else {
					loggedInusers = []
				}
				if(!alreadyAddedAccunt) { 
					loggedInusers.unshift('.json_encode($LoggedInUser,JSON_UNESCAPED_SLASHES).');
				}
				loggedInusers.sort((a,b)=> (new Date(b["logged-on"]) - new Date(a["logged-on"])));
				localStorage.setItem("loggedInUsers",JSON.stringify(loggedInusers));
			</script>';
			if($email){
				echo '<script> localStorage.setItem("loggedInEmail","'.$email.'");</script>';
			}
		}
	}	
if ($is_logged_in)
{	
	$cId = get_company("cId", false);
}

$q = '?v=' . OB_VERSION;
if (ENVIRONMENT == 'development')
{
	$q .= '&t=' . time();
}

$jsList = array();
$moduleList = array();
if($is_logged_in && !$licmanager)
{
	$jsList[] = $app . "/runtime.js";
	$jsList[] = $app . "/polyfills.js";
/*	
	if (ENVIRONMENT == 'development')
	{
	}
*/
	if ($is_logged_in)
	{
		$clientJs = array();
		$clientJs = glob(FCPATH . $app . "/src_app_*_module_ts.js");
		if (!empty($clientJs) && count($clientJs) > 0)
		{
			foreach($clientJs as $file)
			{
				$jsList[] = str_replace(FCPATH, "", $file);
			}
		}
	}

	$jsList[] = $app . "/main.js";
}

if($is_logged_in && $licmanager)
{
	$jsList[] = "assets/onpremises/runtime.js";
	$jsList[] = "assets/onpremises/polyfills-es5.js";
	$jsList[] = "assets/onpremises/polyfills.js";
	if (ENVIRONMENT == 'development')
	{
		$jsList[] = "assets/onpremises/styles.js";
		$jsList[] = "assets/onpremises/vendor.js";
	}
	$jsList[] = "assets/onpremises/main.js";
}

echo PHP_EOL;
foreach ($jsList as $val)
{
	echo '<script type="text/javascript" src="' . base_url($val . $q) . '"></script>'.PHP_EOL;
}
foreach ($moduleList as $val)
{
	echo '<script type="module" src="' . base_url($val . $q) . '"></script>'.PHP_EOL;
}
	?></body>
</html>
