<?php
namespace EasyChat;

 
Class Template {

	private $template;
	private $controller;
	private $layouts;
	private $vars = array();
	
	private $controller_obj;
	
	function __construct($layouts, $controllerName, $controller_obj = null) {
		$this->layouts = $layouts;
		
		$resolved = false;
		if (class_exists($controllerName)) {
			try {
				$reflector = new \ReflectionClass($controllerName);
				$fileName = $reflector->getFileName();
				if ($fileName) {
					$this->controller = strtolower(basename($fileName, '.php'));
					$resolved = true;
				}
			} catch (\Exception $e) {
				 
			}
		}
		
		if (!$resolved) {
			 
			$parts = explode('\\', $controllerName);
			$className = end($parts);
			
			 
			if (strpos($className, 'Controller_') === 0) {
				$className = substr($className, 11);
				$this->controller = strtolower($className);
			} else {
				 
				$this->controller = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $className));
			}
		}
		
		$this->controller_obj = $controller_obj;
	}
	
	 
	function vars($varname, $value) {
		if (isset($this->vars[$varname]) == true) {
			trigger_error ('Unable to set var `' . $varname . '`. Already set, and overwrite not allowed.', E_USER_NOTICE);
			return false;
		}
		$this->vars[$varname] = $value;
		return true;
	}
	
	 
	function view($name) {
		$pathLayout = SITE_PATH . DS . 'views' . DS . 'layouts' . DS . $this->layouts . '.php';
		$contentPage = SITE_PATH . DS . 'views' . DS . $name . '.php';
		if (file_exists($pathLayout) == false) {
			trigger_error ('Layout `' . $this->layouts . '` does not exist.', E_USER_NOTICE);
			return false;
		}
		if (file_exists($contentPage) == false) {
			trigger_error ('Template `' . $name . '` does not exist.', E_USER_NOTICE);
			return false;
		}
		
		$all_vars = $this->vars;
		if ($this->controller_obj && isset($this->controller_obj->vars) && is_array($this->controller_obj->vars)) {
			$all_vars = array_merge($this->controller_obj->vars, $all_vars);
		}

		foreach ($all_vars as $key => $value) {
			$$key = $value;
		}

		include ($pathLayout);                
	}
}