<?php

require_once('renderClass_abstract.php');
require_once('renderFormClass.php');
require_once('renderFunctionsClass.php');
require_once('renderImageClass.php');
require_once('renderNavigationClass.php');
require_once('renderPopupClass.php');
require_once('renderSpecialContentClass.php');
require_once('renderWidgetClass.php');

class renderClass extends renderClass_abstract
{
	public $_renderSearch = array("\r\n", "\n", "\r", "\t");
	public $_renderReplace = '';
	public $_pathTpl = PATH_PORTAL_TPL;
	public $_config = array();
	public $_layout = '';
	public $_template = '';
	public $_langArray = array();
	public $_textsFromConfig = true;
	public $_navpath = array();
	public $_postData = null;
	public $_errors = null;
	public $_tpl = null;
	public $_subTemplate = '';
	public $_siteId = '';
	public $_dataParameter = array();
	public $_website = array();
	public $_webkey = 0;
	public $_modrewrite = false;
	public $_specialSite = false;
	private $_editable = false;
	private $_tplElements = array();
	private $_data = array();
	private $_db = null;
	private $_html = null;

	public function setPathTpl($pathTpl)
	{
		$this->_pathTpl = $pathTpl;
	}

	public function setConfig($config)
	{
		$this->_config = $config;
		if (isset ($this->_config['portal']['website']))
		{
			$this->setWebsite($this->_config['portal']['website']);
		}
	}

	private function setWebsite($website)
	{
		$return_array = array();
		$tmp_array = array_flip($website['navId']);
		foreach ($tmp_array as $key => $value)
		{
			foreach ($website as $tmp_key => $tmp_value)
			{
				$return_array[$key][$tmp_key] = $website[$tmp_key][$value];
			}
		}
		$this->_website = $return_array;
	}

	public function setLayout($layout)
	{
		$this->_layout = $layout;
	}

	public function setTemplate($template)
	{
		$this->_template = $template;
	}

	public function setEditable($editable)
	{
		$this->_editable = $editable;
	}

	public function setSubTemplate($subtemplate)
	{
		$this->_subTemplate = $subtemplate;
	}

	public function setTplElements($tplElements)
	{
		$this->_tplElements = $tplElements;
	}

	public function setSiteId($siteId)
	{
		$this->_siteId = $siteId;
	}

	public function setDataParameter($dataParameter)
	{
		$this->_dataParameter = $dataParameter;
	}

	public function setLang($langArray)
	{
		$this->_langArray = $langArray;
	}

	public function setTextsFromConfig($fromConfig)
	{
		$this->_textsFromConfig = $fromConfig;
	}

	public function setWebkey($_webkey)
	{
		$this->_webkey = $_webkey;
	}

	public function setData($data)
	{
		$this->_data = $data;
	}

	public function setNavpath($navpath)
	{
		$this->_navpath = $navpath;
	}

	public function setDb($db)
	{
		$this->_db = $db;
	}

	public function setErrors($errors)
	{
		$this->_errors = $errors;
	}

	public function setPostData($postData)
	{
		$this->_postData = $postData;
	}

	public function setSpecialSite($specialSite)
	{
		$this->_specialSite = $specialSite;
	}

	public function output()
	{
		$html = $this->readTemplate();
		echo $html->saveHTML();
	}

	private function readTemplate()
	{
		$html = file_get_contents($this->_pathTpl . $this->_layout . '/tpl_' . $this->_template . '.php');
		$html = str_replace($this->_renderSearch, $this->_renderReplace, $html);
		$html = str_replace(array('PHP_ROOT_PATH/', 'PHP_SITE_PATH/'), array(PATH_ROOT, PATH_SITE), $html);
		$tpl = new DOMDocument ();
		$tpl->preserveWhitespace = false;
		$tpl->formatOutput = false;
		$tpl->loadHTML($html);
		$this->_tpl = $tpl;

		if ($this->_template === 'portal')
		{
			if (!isset ($this->_data ['keyvisual']))
			{
				if (file_exists(PATH_IMG . $this->_layout . '/keyvisual_' . $this->_siteId . '.jpg'))
				{
					$this->_data['keyvisual'][] = array('id' => $this->_siteId, 'path' => PATH_IMG . $this->_layout . '/', 'navId' => '', 'src' => 'keyvisual_' . $this->_siteId . '.jpg', 'title' => null);
				}
				else
				{
					$this->_data['keyvisual'][] = array('id' => 0, 'path' => PATH_IMG . $this->_layout . '/', 'navId' => '', 'src' => 'keyvisual_0.jpg', 'title' => null);
				}
			}

			$this->_data ['headline_main'] = $this->_langArray ['portal']['headline_main'];
			$this->_data ['headline_site'] = $this->_langArray ['headline'][$this->_siteId];
		}

		foreach ($this->_data as $id => $content)
		{
			$tmp_content = null;
			switch ($id)
			{
				case 'headline_main'            :
					$tmp_content = $this->_tpl->createDocumentFragment();
					$tmp_content->appendChild(new DOMText ($content));
					break;

				case 'headline_site'            :
					$tmp_content = $this->_tpl->createDocumentFragment();

					foreach ($content as $arrHeadline)
					{
						$headline = $this->_tpl->createElement('h1');
						$headline->setAttributeNode(new DOMAttr ('class', $arrHeadline[1]));
						$headline->appendChild(new DOMText ($arrHeadline[0]));
						$tmp_content->appendChild($headline);
					}
					break;

				case 'sub_content'                :
					$tmp_content = renderPopupClass:: createPopup($content);
					break;

				case 'content'                    :
				case 'login'                    :
					$tmp_content = (is_null($content['siteContents']))
						? null
						: $this->getPageContents($content['siteContents']);
					break;

				case 'keyvisual'                :
					$tmp_content = $this->_tpl->createDocumentFragment();
					foreach ($content as $img_data)
					{
						$tmp_content->appendChild(renderImageClass:: createImage($img_data, false, $id));
					}
					break;

				case 'navi_main'                :
				case 'navi_special'                :
				case 'navi_sub'                    :
				case 'navi_last'                :
					$tmp_content = renderNavigationClass:: createNavigation($content);
					break;

				case 'spielbericht_gespielt'    :
				case 'spielbericht_abgesagt'    :
				case 'spielbericht_pokal'        :
				case 'spielbericht_spielfrei'    :
				case 'uebersicht'                :
					$tmp_content = renderSpecialContentClass:: createSpecialContent($id, $content, (($id === 'uebersicht') ? 'spielbericht_gespielt' : $id));
					break;

				case 'widget'                    :
					$tmp_content = renderWidgetClass:: createWidget($content);
					break;

				default                            :
					break;
			}

			if (!is_null($tmp_content))
			{
				if (in_array($id, array('uebersicht', 'spielbericht', 'spielbericht_gespielt', 'spielbericht_abgesagt', 'spielbericht_pokal', 'spielbericht_spielfrei', 'widget')))
				{
					$node = $tpl->getElementById('content');
				}
				else if (in_array($id, array('keyvisual')))
				{
					$node = $tpl->getElementById($id);
					$node->setAttributeNode(new DOMAttr ('data-editable', $id));
					$node->setAttributeNode(new DOMAttr ('id', $id . '_' . $content[0]['id']));
				}
				else
				{
					$node = $tpl->getElementById($id);
				}
				$node->appendChild($tmp_content);
			}
		}

		if ($this->_editable === true)
		{
			/* Editor Layer einbinden */
			$html = file_get_contents($this->_pathTpl . $this->_layout . '/tpl_editor.php');
			$html = str_replace($this->_renderSearch, $this->_renderReplace, $html);
			$html = str_replace(array('PHP_ROOT_PATH/', 'PHP_SITE_PATH'), array(PATH_ROOT, PATH_SITE), $html);
			$editor = new DOMDocument ();
			$editor->preserveWhitespace = false;
			$editor->formatOutput = false;
			$editor->loadHTML($html);
			$eCont = $editor->getElementById('editor_layer');
			$new_node = $tpl->importNode($eCont, true);
			$body = $tpl->getElementsByTagName('body')->item(0);
			$body->insertBefore($new_node, $body->firstChild);

			/* Editor Elemente einbinden - Nur für Standardseiten */
			if (!$this->_specialSite)
			{
				$html = file_get_contents($this->_pathTpl . $this->_layout . '/tpl_elements.php');
				$html = str_replace($this->_renderSearch, $this->_renderReplace, $html);
				$html = str_replace(array('PHP_ROOT_PATH/', 'PHP_SITE_PATH'), array(PATH_ROOT, PATH_SITE), $html);
				$elements = new DOMDocument ();
				$elements->preserveWhitespace = false;
				$elements->formatOutput = false;
				$elements->loadHTML($html);
				$eCont = $elements->getElementById('editor_elements');
				$eCont = $tpl->importNode($eCont, true);
				$elemCont = $tpl->getElementById('element_content');
				foreach ($this->_website[$this->_webkey]['contentElems'] as $subTpl)
				{
					$node = renderSpecialContentClass:: createSpecialContent($subTpl, array(0 => array('content' => 'text')), null);
					$node->setAttribute('class', $node->getAttribute('class') . ' elem_button');
					$node->setAttributeNode(new DOMAttr ('data-editable', $subTpl));
					$new_node = $tpl->importNode($node, true);
					$elemCont->appendChild($new_node);
				}
				$body = $tpl->getElementsByTagName('body')->item(0);
				$body->insertBefore($eCont, $body->firstChild);
			}

			$head = $tpl->getElementsByTagName('head')->item(0);

			/* Editor CSS ( lokal ) einbinden */
			$css = $this->_tpl->createElement('link');
			$css->setAttributeNode(new DOMAttr ('href', PATH_CSS . $this->_layout . '_editor.css'));
			$css->setAttributeNode(new DOMAttr ('type', 'text/css'));
			$css->setAttributeNode(new DOMAttr ('rel', 'stylesheet'));
			$head->appendChild($css);

			/* Editor JS - Variablen einbinden */
			$data = 'var userId = "' . $_SESSION['sess_userId'] . '";' . "\n";
			$data .= 'var sessLang = "' . $_SESSION['sess_loginLang'] . '";' . "\n";
			$data .= 'var navigationId = "' . $this->_siteId . '";' . "\n";
			$data .= 'var pathMed = "' . PATH_MED . '";' . "\n";
			$data .= 'var stdKeyvisual = "' . PATH_MED . $this->_website[$this->_webkey]['prefix'] . '/sample_keyvis.jpg";' . "\n";
			$data .= 'var stdImage = "' . PATH_MED . $this->_website[$this->_webkey]['prefix'] . '/sample_image.jpg";' . "\n";

			foreach ($this->_website[$this->_webkey] as $var => $value)
			{
				if (is_array($value))
				{
					$data .= 'var ' . $var . ' = ' . json_encode($value) . ';' . "\n";
					continue;
				}
				$data .= 'var ' . $var . ' = "' . $value . '";' . "\n";
			}

			$data .= ($this->_specialSite)
				? 'var specialSite = true;'
				: 'var specialSite = false;';

			$js = $this->_tpl->createElement('script');
			$js->setAttributeNode(new DOMAttr ('type', 'text/javascript'));
			$js->appendChild(new DOMCdataSection (utf8_encode($data)));
			$head->appendChild($js);

			/* Editor Sprachdatei ( remote ) einbinden */
			$js = $this->_tpl->createElement('script');
			$js->setAttributeNode(new DOMAttr ('type', 'text/javascript'));
			$js->setAttributeNode(new DOMAttr ('src', $this->_website[$this->_webkey]['editorUrl'] . '' . $this->_website[$this->_webkey]['editorVersion'] . '/js/lang.js.php?lang=' . $_SESSION['sess_loginLang']));
			$head->appendChild($js);

			/* Editor JS ( remote ) einbinden */
			$js = $this->_tpl->createElement('script');
			$js->setAttributeNode(new DOMAttr ('type', 'text/javascript'));
			$js->setAttributeNode(new DOMAttr ('src', $this->_website[$this->_webkey]['editorUrl'] . '' . $this->_website[$this->_webkey]['editorVersion'] . '/js/editor.js'));
			$head->appendChild($js);

			$js = $this->_tpl->createElement('script');
			$js->setAttributeNode(new DOMAttr ('type', 'text/javascript'));
			$js->setAttributeNode(new DOMAttr ('src', $this->_website[$this->_webkey]['editorUrl'] . '' . $this->_website[$this->_webkey]['editorVersion'] . '/js/ckeditor/ckeditor.js'));
			$head->appendChild($js);

		}

		/* Nicht benötigte Elemente entfernen */
		foreach ($this->_tplElements as $element)
		{
			if (!isset ($this->_data [$element]))
			{
				$oldNode = $tpl->getElementById($element);
				$oldNode->parentNode->removeChild($oldNode);
			}
		}

		return $tpl;
	}

	private function getPageContents($content)
	{
		$arrContent = explode(';', $content);

		$tbl_prefix = ($this->_webkey !== 0)
			? $this->_website[$this->_webkey]['prefix']
			: 'portal';

		$new_node = $this->_tpl->createDocumentFragment();

		foreach ($arrContent as $singleContent)
		{
			$tmp_content = explode('_', $singleContent);
			$tmp_result = $this->_db->query('SELECT * FROM ' . $tbl_prefix . '_content_' . $tmp_content [0] . ' WHERE id = "' . $tmp_content [1] . '";');
			$tmp_data = $tmp_result->fetch_assoc();

			switch ($tmp_content[0])
			{
				case 'form'    :
					$new_node = renderFormClass:: createForm($tmp_data);
					break;

				default        :
					$node = renderSpecialContentClass:: createSpecialContent($tmp_content[0], array($tmp_data), $tmp_content[0]);

					if ($this->_editable)
					{
						$node->setAttributeNode(new DOMAttr ('data-editable', $tmp_content[0]));
						$node->setAttributeNode(new DOMAttr ('id', 'content_' . $tmp_content[0] . '_' . $tmp_content[1]));
					}

					$new_node->appendChild($node);
					break;

			}
		}

		return $new_node;
	}

	public function applySortRules($tpl, $node, $xpath)
	{
		$elements = $xpath->query(".//*[@data-sortable]", $node);
		foreach ($elements as $sortNode)
		{
			$sortImg = $tpl->createElement('img');
			$sortText = $sortNode->firstChild;
			$href = $this->_postData;
			if ($sortNode->getAttribute('data-sortable') === $this->_postData['orderBy'])
			{
				if ($this->_postData['orderDir'] === 'ASC')
				{
					$sortImg->setAttributeNode(new DOMAttr ('src', PATH_IMG . 'icon-sortup.png'));
					$href['orderDir'] = 'DESC';
				}
				else
				{
					$sortImg->setAttributeNode(new DOMAttr ('src', PATH_IMG . 'icon-sortdown.png'));
					$href['orderDir'] = 'ASC';
				}
			}
			else
			{
				$sortImg->setAttributeNode(new DOMAttr ('src', PATH_IMG . 'icon-sortwo.png'));
				$href['orderBy'] = $sortNode->getAttribute('data-sortable');
			}

			$newLink = '';
			foreach ($href as $key => $value)
			{
				$newLink .= '&' . $key . '=' . $value;
			}

			$sortNode->setAttribute('href', $sortNode->getAttribute('href') . '?' . substr($newLink, 1));
			$sortNode->replaceChild($sortImg, $sortText);
			$sortNode->appendChild(new DOMText ($sortText->nodeValue));
		}
	}

	public function applyFunction($name, $data, $tpl, $node, $prefix)
	{
		switch ($name)
		{
			case 'createNavigationRights'    :
				$rights = renderFunctionsClass::createNavigationRights($data, $tpl, $node);
				break;
			default                    :
				break;
		}
	}
}