<?php
class controller extends API
{
	protected $DOM, $ACT, $ACTION;
	protected $DB;

	public function __construct($arg = "", $mod = "")
	{
		$this->DB = $GLOBALS['CONFIG']['DBHANDLE'];

		$classname = get_class($this);
		$validate = $classname === 'Login' ? false : true;
		if ($validate) {
			if ($this->validateJWT()) {
				if (method_exists($this, $mod)) {
					call_user_func(array($this, $mod), $arg);
				} else {					
					$this->index($arg);					
				}
			}
		} else {
			
			$this->index($arg);
		}
	}

	protected function createDOM()
	{
		return new DOMDocument();
	}

	protected function elementsTag($tag)
	{
		return $this->DOM->getElementsByTagName($tag);
	}

	protected function setAttribute($id, $attr, $content)
	{
		$element = $this->DOM->getElementById($id);
		if ($element)
			$element->setAttribute($attr, $content);
	}

	protected function setContent($id, $content)
	{
		$element = $this->DOM->getElementById($id);
		if ($element) $element->nodeValue =  str_replace('&', "&amp;", $content);
		else {
			$xPath = new DOMXPath($this->DOM);
			$element = $xPath->query("//*[contains(@class,'$id')]");

			if ($element->length)
				$element[0]->nodeValue = str_replace('&', "&amp;", $content);
		}
	}

	protected function loadTheme($tpl)
	{
		global $CONFIG;

		$theme = $CONFIG['THEMES_DOC'] . "/" . $tpl;

		$handle = fopen($theme, "r");
		$content = fread($handle, filesize($theme));
		$content = str_replace(array("&"), array("&amp;"), $content);
		$this->DOM = new DOMDocument();
		libxml_use_internal_errors(true);
		$this->DOM->loadHTML($content);
		libxml_clear_errors();
	}

	protected function writeTheme($data = [])
	{
		if (!empty($data)) {
			foreach ($data as $key => $val)
				$this->setContent($key, $val);
		}

		$content = $this->DOM->saveHTML();
		echo htmlspecialchars_decode($content);
	}

	protected function index() {}
}
