<?php

header('Content-Type: text/html; charset=UTF-8');

$accessControl = array(
	"IncludeFile" => true
);
# for pdf on the server at the @ !!
@include_once "AccessControl.php";

class PageLoader {

	var $views;
	var $styles;
	var $scripts;
	var $code;
	var $content;


	function __construct() {
		
		# set up some default values
		$this->views = array("html" => "templates/logaholic_6/default-template.php");
		$this->styles = [];
		$this->scripts = [];
		$this->code = "";	
			
	}

	function BuildPage() {

		if (file_exists("templates/custom.css")) {
			$this->styles[] = array("src" => "templates/custom.css");
		}

		if (file_exists("templates/custom.js")) {
			$this->scripts[] = "templates/custom.js";			
		}
		
		$this->content = file_get_contents($this->views["html"]);
		unset($this->views["html"]);
		
		$this->content = $this->InjectCSS($this->styles);

		# get the main html
		$this->content = $this->LoadViews($this->views);
		
		$this->content = $this->InjectScripts($this->scripts, $this->code);		

		return $this->content;
		
	}

	function LoadViews($views) {
		$views["licenseModal"] = "app/views/LicenseModal.php";
		$views["UserAccount"] = "app/views/UserMenu.php";

		$content = $this->content;

		# Overwrite the body if we want to
		if(!empty($views['body'])){

			$content = preg_replace('/(<body).*(<!-- Load js sources -->)/s', "<body class=\"skin-blue\"><?php include '{$views['body']}'; ?><!-- Load js sources -->" , $content);

			unset($views['body']);
		}

		# Load other views into the template
		$code = "<script>\n";
		foreach ($views as $k => $v) {
			if (is_array($v)) {
				$code .= '$.ajax({ async : false, url : "'.$v[0].'", success :function(r){  $("'.$k.'").html(r);  }   });';
			} else {
				$view ="<?php include '$v'; ?>";
				$content = str_replace("<!-- $k -->", $view, $content);
			}
		}
		$this->code = $code. "</script>" . $this->code;

		return $content;

	}

	function InjectScripts($scripts, $code) {
		$inject = "<!-- Logaholic Scripts -->";
		
		foreach ($scripts as $val) {
			$inject .= "<script src=\"$val\" type=\"text/javascript\" charset=\"utf-8\"></script>\n";
		}

		// foreach ($scripts as $script) {
  // 			$inject .= file_get_contents($script);
		// }
		$inject .= $code;
		//$content = str_replace("<!-- Logaholic Scripts -->", "<script>".$inject."</script>", $this->content);
		$content = str_replace("<!-- Logaholic Scripts -->", $inject, $this->content);
		return $content;
	}

	function InjectCSS($css) {

		$inject = "<!-- Logaholic 6 CSS -->";
		foreach ($css as $val) {
			$media = "";
			if(!empty($val['media'])){ $media = "media=\"{$val['media']}\""; }

			$inject .= "<link href=\"{$val['src']}\" rel=\"stylesheet\" type=\"text/css\" $media />\n";
		}
		$content = str_replace("<!-- Logaholic 6 CSS -->", $inject, $this->content);
		return $content;

	}

	function Display() {
		global $cm;
		$this->BuildPage();
		eval("?>".$this->content);
	}


}