<?php

class renderPopupClass extends renderClass_abstract
{
	private $_imgData = array();

	public function createPopup($popupData)
	{
		if ($this->_subTemplate !== '')
		{
			$html = file_get_contents($this->_pathTpl . $this->_layout . '/tpl_' . $this->_template . '_' . $this->_subTemplate . '.php');
			$html = str_replace($this->_renderSearch, $this->_renderReplace, $html);
			$subTpl = new DOMDocument ();
			$subTpl->preserveWhitespace = false;
			$subTpl->formatOutput = true;
			$subTpl->loadHTML($html);
			$subCont = $subTpl->getElementById('sub_content')->firstChild;

			$xpath = new DOMXpath ($subTpl);

			/* Textersetzungen */
			foreach ($this->_langArray [$this->_template] as $key => $value)
			{
				$replaces = $xpath->query("//*[starts-with( . , '%" . $key . "%' )]");
				foreach ($replaces as $replace)
				{
					if ($replace->firstChild->nodeType === 3)
					{
						$replace->replaceChild(new DOMCdataSection  ($value), $replace->firstChild);
					}
				}
			}

			/* Funktionen */
			if (isset ($popupData['functions']) && !empty ($popupData['functions']))
			{
				foreach ($popupData['functions'] as $function)
				{
					if ($function['position'] === 'userWebsiteRights')
					{
						$node = $subTpl->getElementById('websiteRights')->cloneNode(true);
						$node->firstChild->nodeValue = $node->firstChild->nodeValue . ': ' . $this->_website[$function['key']]['names'];
						$node->removeAttribute('id');
						$node->setAttributeNode(new DOMAttr ('id', $function['prefix'] . 'Rights'));

						$newNode = $subTpl->getElementById('websiteRights')->parentNode->insertBefore($node, $subTpl->getElementById('websiteRights'));

						/* Elemente ersetzen */
						$arr_replaces = array('for', 'id', 'name', 'onclick');
						foreach ($arr_replaces as $str_replace)
						{
							$replaces = $xpath->query(".//*[contains(@" . $str_replace . " , 'Website')]", $newNode);
							foreach ($replaces as $replace)
							{
								$attribute = $replace->getAttribute($str_replace);
								$replace->removeAttribute($str_replace);
								$replace->setAttributeNode(new DOMAttr ($str_replace, str_replace('Website', $function['prefix'], $attribute)));
							}
						}

						$elem = $xpath->query(".//*[@id='user" . $function['prefix'] . "Rights_outer']", $newNode);
						$node = $elem->item(0);
					}
					else
					{
						$node = $subTpl->getElementById($function['position'] . '_outer');
					}

					if (!is_null($node))
					{
						$this->applyFunction($function['name'], $function['data'], $subTpl, $node, $function['prefix']);
					}
				}

				$node = $subTpl->getElementById('websiteRights');
				$node->parentNode->removeChild($node);
			}

			/* Headerdaten */
			if (isset ($popupData['header']) && !empty ($popupData['header']))
			{
				$header_node = $subTpl->getElementById('sub_content_header');
				foreach ($popupData['header'] as $key => $value)
				{
					$replaces = $xpath->query(".//*[@id='" . $key . "']", $header_node);
					foreach ($replaces as $replaceNode)
					{
						switch ($replaceNode->tagName)
						{
							case 'select'    :
								foreach ($value as $optionValue => $optionName)
								{
									$option = $subTpl->createElement('option');
									$option->setAttributeNode(new DOMAttr ('value', $optionValue));
									if (isset ($this->_postData[$key]) && $this->_postData[$key] == $optionValue)
									{
										$option->setAttributeNode(new DOMAttr ('selected', 'selected'));
									}
									$option->appendChild(new DOMText ($optionName));
									$replaceNode->appendChild($option);
								}
								break;
							case 'input'    :
								$replaceNode->setAttributeNode(new DOMAttr ('value', $value));
								$replaceNode->setAttributeNode(new DOMAttr ('autocomplete', 'off'));
							default            :
								break;
						}
					}
				}
			}

			$this->applySortRules($subTpl, $subCont, $xpath);

			/* Ausgabedaten */
			if (isset ($popupData['main']) && !empty ($popupData['main']))
			{
				$main = $subTpl->getElementById('sub_content_main');
				$subNode = $main->firstChild;

				$testArray = $popupData['main'][0];

				/* Datenfelder */
				$arr_mainKeys = array();
				foreach ($testArray as $key => $value)
				{
					$elements = $xpath->query("//*[@data-name='" . $key . "']", $main);
					if ($elements->length !== 0)
					{
						$arr_mainKeys[] = $key;
					}
				}

				/* Eingabefelder */
				$arr_mainInputs = array();
				foreach ($testArray as $key => $value)
				{
					$elements = $xpath->query("//form//*[@name='" . $key . "' or @name='" . $key . "[ ]']", $main);
					if ($elements->length !== 0)
					{
						$arr_mainInputs[] = $key;
					}
				}

				/* Hauptdaten */
				foreach ($popupData['main'] as $dataArray)
				{
					$dataNode = $main->firstChild->cloneNode(true);

					/* Schaltflächen ( Links ) für die Bearbeitung in den Übersichtsseiten */
					foreach ($this->_dataParameter as $key => $new_parameter)
					{
						$data_navigation = $xpath->query(".//*[@data-navigation='" . $key . "']//a", $dataNode);
						if ($data_navigation->length !== 0)
						{
							foreach ($data_navigation as $navigation_item)
							{
								if ($navigation_item->hasAttribute('href'))
								{
									$navigation_item->setAttribute('href', $navigation_item->getAttribute('href') . '&' . $new_parameter . '=' . $dataArray[$new_parameter]);
								}
							}

						}
					}

					/* Spezielle Regeln anwenden */
					switch ($this->_template)
					{
						/* Aktive - inaktive Elemente Unterscheiden */
						case 'usermanagement'    :
							if (isset ($dataArray['userActive']) && $dataArray['userActive'] === 'Y')
							{
								$dataNode->setAttributeNode(new DOMAttr ('class', 'data_active'));
							}
							else
							{
								$dataNode->setAttributeNode(new DOMAttr ('class', 'data_inactive'));
							}
							break;
						default                    :
							break;
					}

					/* Werte zuweisen */
					foreach ($arr_mainKeys as $key => $value)
					{
						$elements = $xpath->query(".//*[@data-name='" . $value . "']", $dataNode);
						if ($elements->item(0)->hasChildNodes())
						{
							$elements->item(0)->removeChild($elements->item(0)->firstChild);
						}
						/* TODO : Warum ist ein utf8_encode nötig? Evtl Server - Konfig */
						// $elements	-> item( 0 ) -> appendChild ( new DOMText ( ( mb_detect_encoding ( $dataArray[ $value ] ) === 'UTF-8' ) ? $dataArray[ $value ] : utf8_encode ( $dataArray[ $value ] ) ) );
						$elements->item(0)->appendChild(new DOMText ($dataArray[$value]));
					}

					foreach ($arr_mainInputs as $key => $value)
					{
						$elements = $xpath->query(".//form//*[@name='" . $value . "' or @name='" . $value . "[ ]']", $dataNode);
						foreach ($elements as $element)
						{
							switch ($element->tagName)
							{
								case 'input'    :
									if ($element->hasAttribute('type'))
									{
										switch ($element->getAttribute('type'))
										{
											case 'text'        :
											case 'hidden'    :
												$element->removeAttribute('value');
												$element->setAttributeNode(new DOMAttr ('value', $dataArray[$value]));
												break;
											case 'radio'    :
												if ($element->hasAttribute('id') && $element->getAttribute('id') === ($value . '_' . $dataArray[$value]))
												{
													$element->setAttributeNode(new DOMAttr ('checked', 'checked'));
												}
												break;
											case 'checkbox'    :
												if (is_array($dataArray[$value]))
												{
													if ($element->hasAttribute('id') && in_array($element->getAttribute('id'), $dataArray[$value]))
													{
														$element->setAttributeNode(new DOMAttr ('checked', 'checked'));
													}
												}
												break;
											default            :
												break;
										}
									}
									else
									{
										$element->removeAttribute('value');
										$element->setAttributeNode(new DOMAttr ('value', $dataArray[$value]));
									}
									break;
								default            :
									break;
							}
						}
					}
					$main->appendChild($dataNode);
				}

				$subNode->parentNode->removeChild($subNode);
			}
			else
			{
				/* TODO : Keine Daten */
				$oldNode = $subTpl->getElementById('sub_content_main');
				$oldNode->parentNode->removeChild($oldNode);
			}
		}

		/* Fehlermeldungen */
		if (!is_null($this->_errors))
		{
			$main = $subTpl->getElementById('sub_content_main');
			$subNode = $main->firstChild;
			foreach ($this->_errors as $error)
			{
				$errorNode = $subTpl->createElement('p');
				$errorNode->setAttributeNode(new DOMAttr ('class', 'error'));
				$errorNode->appendChild(new DOMText ($this->_langArray['error'][$error]));
				$main->insertBefore($errorNode, $subNode);
			}
		}

		$new_node = $this->_tpl->importNode($subCont, true);
		return $new_node;
	}

}