<?php
/*
	Stempora web framework
	copyright (c) 2002-2016 Stempora
		web:  www.stempora.com
		mail: support@stempora.com

*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/

global $site;

class CXMLSimpleList extends CLibrary{
	
	var $template; 

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $aclMod;
	

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __construct($form , $items , $tables , $extra = null) {
		global $site;

		$this->db = $site->db;

		$this->template = new CTemplateDynamic("templates/form.list.htm");
		$this->tables = $tables;

		$this->form = $form;
		$this->items = $items;

		$this->extra = $extra;

		$this->__extractSortableFields();

	}



	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Process() {

//		debug($this->form);	
//		debug($this->items);
			
		return $this->Draw();

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Draw() {
		global $base;

		$is_ajax = $_GET["ajax"];

		$this->is_ajax = $is_ajax;

		$this->__SortFallBack();


		if (is_array($this->form["fields"])) {

	
			if ($this->form["header"]["titles"] == "true") {				
				foreach ($this->form["fields"] as $key => $field) {

					$field["field"] = $key;

					$header[$key]["content"] = $this->__headerCell($field);
				}
			} else {
				foreach ($this->form["fields"] as $key => $field) {
					$header[$key]["content"] = "";
				}
			}

			//build the variables

			$vars["skin"] = $this->form["skin"];

			$vars["header"] = $base->html->Table(
				$this->template,
				"Header" , 
				$header
			);


			$vars["tabs"] = $this->__tabs();


			$vars["title"] = $this->form["title"] ? $this->form["title"] : $this->form["subtitle"];

			$vars["body"] = $this->__body();


			$vars["footer"] = $this->__footerRow();	

			$vars["buttons"] = $this->__headerButtons();

			$vars["lang_buttons"] =	$this->LanguageButtons($this->form);
	

			$vars["main"] = $this->template->blockReplace(
				$is_ajax ? "ListAjax" : "List", 
				$vars
			); 
			

			if (is_array($this->form["order"])) {
				$vars["sortable_id"] = "STBFormSort";
				$vars["sortable_link"] = $this->template->blockReplace("SortLink" , array());
			} else {
				$vars["sortable_id"] = "";
				$vars["sortable_link"] = "";
			}			
		}

		$vars["_pre"]	= $this->extra["pre"] ? $this->extra["pre"] : "";
		$vars["_after"]	= $this->extra["after"] ? $this->extra["after"] : "";

		$vars["_pre_javascript"] = $this->form["javascript"]["pre"] ? "<script language=\"Javascript\">" . $this->form["javascript"]["pre"] . "</script>" : "";
		$vars["_after_javascript"] = $this->form["javascript"]["after"] ? "<script language=\"Javascript\">" . $this->form["javascript"]["after"] . "</script>" : "";


		if ($this->form["border"] && !$is_ajax) {
			$html = $this->template->blockReplace(
				"Main" , 
				$vars,
				array(
					"_id"	=> $this->form["id"] ? "id='list_" . $this->form["id"] . "' " : "",
				)
			);

		} else {
			$html = $this->template->blockReplace(
				"MainNoWidget" , 
				$vars
			);
		}

		
		if ($this->form["formtag"]) {

			$form = array(
				"action"	=> $this->form["action"] ? $this->form["action"] : "#",
				"name"		=> $this->form["name"] ? $this->form["name"]  : "list",
				"id"		=> $this->form["formid"],
				"encoding"	=> $this->form["encoding"],
				"method"	=> $this->form["method"],
				"body"		=> $html
			);

			$html = $this->template->blockReplace(
				"Form" , 
				$form
			);
		}
		
		if ($this->form["form"]) {
			$form = $this->form["form"];
		}
		
		
		
		$html = CTemplateStatic::Replace(
			$html,
			CForm::GlobalVars(
				$this->form
			)
		);
		
		if (is_array($this->form["vars"])) {
			$html = CTemplateStatic::Replace(
				$html,			
				$this->__processVars()
			);
		}

		return $html;
		

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __body() {
		global $base;

		$this->cells = $cells = count($this->form["fields"]);
		if (is_array($this->form["fields"]) && is_array($this->items["items"])) {

			foreach ($this->items["items"] as $key => $item) {

				$body[$key]["content"] = $this->__bodyRow($item);
				$body[$key]["id"] = $item[$this->form["table_uid"]];
			}			
		}


		if (is_array($body)) {
			return $base->html->Table(
				$this->template,
				"Body" , 
				$body
			);
		} else {

			if ($this->is_ajax) {
				die("empty");
			} 

			return $this->template->blockReplace(
				"BodyEmpty" , 
				array(
					"cells"	=> $cells,
					"empty"	=> $this->form["norecords"] ? $this->form["norecords"] : "No available records.",
				)
			);
		}
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __bodyRow($item) {
		global $base;

		if (!is_array($item)) {
			return "";
		}


		if (!$this->vars) {
			$this->vars = CForm::GlobalVars(
				$this->form
			);
		}
		
		foreach ($this->form["fields"] as $key => $field) {

			$value = $item[$key];

			switch ($this->form["fields"][$key]["prio"]) {
				case "low":
					$field["prio"] = $this->template->blockreplace("prioLow");
				break;

				case "med":
					$field["prio"] = $this->template->blockreplace("prioMed");
				break;
			}


			if ($value == "___is_protected___") {
				$data[$key]["content"] = $this->template->BlockReplace("cellEmpty" , $field);
			} else {

				if (!isset($field["type"])) {
					$field["type"] = "";
				}
				
	
				switch ($field["type"]) {

					default:					
						$data[$key]["content"] = $this->template->blockReplace(
							"cellDefault" , 
							array(
								"prio"		=> $field["prio"],
								"value"		=> $value,
								"width"		=> $field["width"],
								"align"		=> $field["align"],
								"header"	=> strip_tags($field["header"]) ? strip_tags($field["header"]) . ":" : "",

							)
						);
					break;

					case "button" :
						$field = $this->__oldButton($field);

						$field["target"] = $field["target"];
						$field["align"] = $field["align"];

						if ($field["popup"] == "true") {

							$field["location"] = str_replace( 
								"index.php" , 
								"popup.php" , 
								CTemplateStatic::Replace(
									$field["location"] ,
									$this->vars
								)
							);
						}
						
						$data[$key]["content"] = CTemplateStatic::Replace(
							CTemplateStatic::REplace(
								$this->template->blockReplace(
									$field["popup"] == "true" ? "cellButtonPopup" : "cellButton" , 
									array_merge(
										$field,
										array(
											"prio"	=> $field["prio"],
											"icon"	=> $field["icon"] ? $this->template->BlockReplace("ButtonIcon" , $field) : "",
										)
									)
								),
								$this->vars
							),
							$item
						);

						
					break;
				}
			}
/*
			if ($field["protected"] && $item[$field["protected"]]) {
				$data[$key]["content"] = $this->template->BlockReplace("cellEmpty" , $field);
			}
*/
									
		}

		return $base->html->Table(
			$this->template , 
			"BodyRow" , 
			$data
		);
		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __footerRow() {
		
		$_GET["page"] = max($_GET["page"] , 1);

		if ($this->form["items"]) {

			$data = $_GET;

			unset($data["page"]);

			$link = "index.php?" . http_build_query($data) . "&page={PAGE}";
			

			$return = CHTML::CustomPaging(
				$this->template , 
				"Paging",
				10 , 
				ceil($this->items["count"] / $this->form["items"]) , 
				$_GET["page"] , 
				$link
			);

			if ($return) {
				return $this->template->blockreplace(
					"Footer", 
					array(
						"paging"			=> $return,
						"cells"				=> $this->cells,
						"more_records"		=> is_array($this->form["order"]) ? $this->template->blockReplace(
							"ListMoreRecords",
							array(
								"cols_count"	=> $this->cells,
								"ajax_link"		=> CTemplateStatic::Replace(
									$link , 
									array(
										"PAGE" => $_GET["page"] + 1
									) 
								). "&ajax=true"
							)
						) : "",


					)
				);
			}
			
			return $return;
		}

	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __headerButtons() {
		global $base;


		if (is_array($this->form["header"]["buttons"])) {

			foreach ($this->form["header"]["buttons"] as $key => $button) {

				if (
					!CForm::__isRestricted($button["restricted"]) && 
					(
						!$button["acl"] || 
						(
							$button["acl"] && 
							$this->aclMod && 
							$base->acl->checkModRule($this->aclMod , $button["acl"])
						)
					) 
				) {				

					switch ($button["type"]) {
						case "menu":

							$tmp = array();

							if (is_array($button)) {
								foreach ($button["link"] as $k => $val) {

									if (!CForm::__isRestricted($val["restricted"])) {

										$val["icon"] = $this->TranslateIcon($val["icon"]);

										$tmp[$k] = array(
											"onclick"	=> $val["onclick"],
											"target"	=> $val["target"],
											"icon"		=> $val["icon"] ? $this->template->BlockReplace("ButtonIcon" , $val) : "",
											"title"		=> $val["title"],
											"link"		=> $val["location"],
										);

									}
								}								

								$buttons[$key]["menu"] = CTemplateStatic::Replace(
									$base->html->Table(
										$this->template , 
										"HeaderDrop",
										$tmp
									),
									array(
										"key"	=> $key
									)
								);

								$buttons[$key]["toggle"] = $this->template->blockReplaceSingle("HeaderDrop" , "key" , $key);
							}

							$button["icon"] = $this->TranslateIcon($button["icon"]);


							$buttons[$key]["onclick"] = $button["onclick"];
							$buttons[$key]["target"] = $button["target"];
							$buttons[$key]["icon"] = $button["icon"] ? $this->template->BlockReplace("ButtonIcon" , $button) : "";
							$buttons[$key]["title"] = $button["title"];
							$buttons[$key]["link"] = "#";
						break;
							
						default:

							if (!$button["title"]) {
								$button = $this->__oldButton($button);
							}
							
							$button["icon"] = $this->TranslateIcon($button["icon"]);

							if ($button["popup"] == "true") {

								$button["location"] = str_replace( 
									"index.php" , 
									"popup.php" , 
									$button["location"]
								);

							}
							

							$buttons[$key] = array(
								"onclick"	=> $button["onclick"],
								"target"	=> $button["target"],
								"icon"		=> $button["icon"] ? $this->template->BlockReplace("ButtonIcon" , $button) : "",
								"title"		=> $button["title"],
								"link"		=> $button["location"],
								"menu"		=> "",
								"toggle"	=> $button["popup"] == "true" ? $this->template->blockReplace("ButtonPopup" , $button ) : "" ,
							);
						break;

					}
					
				}
			}
			
			return $this->template->blockReplace(
				"HeaderButtons" , 
				array(
					"buttons"	=> $base->html->Table(
						$this->template , 
						"HeaderButtons" , 
						$buttons
					)
				)
			);
		}
		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __headerCell($data) {
		global $base;

		if (CForm::__isRestricted($data["restricted"]) || ($data["acl"] && $this->aclMod && !$base->acl->checkModRule($this->aclMod , $data["acl"]))) {

			unset($this->form["fields"][$data["field"]]);					
			return "";
		}

		switch ($data["prio"]) {
			case "low":
				$data["prio"] = $this->template->blockreplace("prioLow");
			break;

			case "med":
				$data["prio"] = $this->template->blockreplace("prioMed");
			break;
		}
		
		
		switch ($data["type"]) {
			default:
				return $this->template->blockReplace(
					$this->sortableFields[$data["field"]] ? "HeaderTextSortable" : "HeaderText" , 
					array(
						"title"		=> $data["header"],
						"prio"		=> $data["prio"],
						"link"		=> $this->__sortLink($data["field"]),
						"link_up"	=> $this->__sortLink($data["field"] , "up"),
						"link_down"	=> $this->__sortLink($data["field"] , "down"),
						"width"		=> $data["width"],

						"dir"		=> $this->__sortDir($data["field"]),
					)
				);
			break;

			case "button":
				return $this->template->blockReplace(
					"HeaderButton" , 
					array(
						"width"		=> $data["width"],
						"prio"		=> $data["prio"],
						
					)
				);
			break;

			case "multiple":
				return $this->template->blockReplace(
					"HeaderMultiple" , 
					array(
						"width"		=> $data["width"],
						"prio"		=> $data["prio"],
					)
				);
			break;

		}
		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __extractSortableFields() {

		//check if its a sortable table
		/*
		if (is_array($this->form["order"])) {
			if (!CForm::__isRestricted($this->form["order"]["restricted"])) {
				$this->form["header"]["nolinks"] = "false";
			} else {
				return "";
			}
		}
		*/


		if ($this->form["header"]["nolinks"] == "true") {
			return "";
		}
		
		

/*
		if (is_array($this->items["items"]) && count($this->items["items"])) {

			$this->sortableFields = $this->items["items"][key($this->items["items"])];

			foreach ($this->sortableFields as $key => $val) {
				$this->sortableFields[$key] = true;
			}		
		}	
		
*/

		if (is_array($this->items["table_fields"])) {
			$this->sortableFields = $this->items["table_fields"];
		}
		
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __sortLink($field , $type = "auto") {

		$data = $_GET;
		

		switch ($type) {

			case "auto":
				if ($data["order"] == $field) {
					$data["order_mode"] = $data["order_mode"] == "ASC" ? "DESC" : "ASC";
				} else {
					$data["order"] = $field;
					$data["order_mode"] = "ASC";
				}
				
			break;

			case "up":
				$data["order"] = $field;
				$data["order_mode"] = "ASC";
			break;

			case "down":
				$data["order"] = $field;
				$data["order_mode"] = "DESC";
			break;

		}

		
		return "index.php?" . http_build_query($data);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __sortDir($field) {
		$data = $_GET;
		

		if ($data["order"] == $field) {

			if (strtolower($data["order_mode"]) == "asc") {
				return "up";
			}

			if (strtolower($data["order_mode"]) == "desc") {
				return "down";
			}			
		}
		


	}
	
	


	/*	COMPATIBILITY FUNCTIONS		*/

	static function __oldButton($button) {

		$text = array(
			"addnew"	=> "Add New",
			"edit"		=> "Edit",
			"save"		=> "Save",
			"saveall"	=> "Save",
			"return"	=> "Back",
			"next"		=> "Next",
		);

		$icon = array(
			"addnew"			=> "add",
			"edit"				=> "edit",
			"next"				=> "next",
			"save"				=> "save",
			"saveall"			=> "save",
			"return"			=> "back",

			"/small/details"	=> "details",
			"/small/edit"		=> "edit",
			"/small/delete"		=> "delete",
			"reorder"			=> "move",
		);

		$color = array(
			"/small/details"	=> "Blue",
			"/small/edit"		=> "Blue",
			"/small/delete"		=> "Red",
			"reorder"			=> "Green",

		);

		if (!$button["color"]) {
			$button["color"] = $color[$button["button"]];
		}


		if (!$button["title"]) {
			$button["title"] = $text[$button["button"]];
		}

		if (!$button["icon"]) {
			$button["icon"] = CXMLSimpleList::TranslateIcon($icon[$button["button"]]);
		}
	
		return $button;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	static function TranslateIcon($icon) {

		$icons = array(
			"details"			=> "file",
			"return"			=> "back",

			"move"				=> "move",
		);


		if ($icons[$icon]) {
			return $icons[$icon];
		}

		return $icon;
		
		
	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __processVars() {

		if (is_array($this->form["vars"])) {
			foreach ($this->form["vars"] as $key => $val) {
				//echeking if the default must be evaluated
				if ($val["action"] == "eval") {
					eval("\$val[\"import\"] = " . $val["default"] .";");
				}
				
				switch ($val["type"]) {
					case "eval":
						eval("\$tpl_vars[\"$key\"] = " . $val["import"] . ";");
					break;

					case "value":
						$tpl_vars[$key] = $values["values"][$val["import"]];
					break;

					case "complex_eval":
						eval($val["import"]);
					break;

					case "var":
						$tpl_vars[$key] = $val["import"];
					break;
				}													
			}

			return $tpl_vars;
		}

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __tabs() {

		global $base;

		if (is_array($this->form["tabs"])) {

			$tabs = new CFormsTabs($this->form["tabs"]);
			return $tabs->Render();

			//i should add the active preparation
		}
		
	}
	

	function LanguageButtons(&$form) {		

		if ($form["lang"] != "true") {
			return "";
		}
		

		if (!$form["table_lang"]) {
			return "";
		}
		
		
		if (!$form["languages"]) {
			$form["languages"] = CXMLFormLanguage::LanguageButtons();
		}

		global $base;

		if (is_array($form["languages"])) {

			if ($_REQUEST["lang_id"]) {
				$default = $_REQUEST["lang_id"];

				foreach ($form["languages"] as $key => $val) {
					if ($val["default"] && ( $default == $val["id"])){
						$is_default = true;
					}
				}
			} else {
				foreach ($form["languages"] as $key => $val) {
					if ($val["default"]) {
						$is_default = true;
						$default = $val["id"];
						$_GET["lang_id"] = $_POST["lang_id"] = $default;
					}					
				}
			}
			
			
			

			if (count($form["languages"] )> 1 ) {

				foreach ($form["languages"] as $key => $val) {							

					if ($val["id"] == $default) {
						$form["languages"][$key]["selected"] = $this->template->blockReplace("LangsSelected" , array());
						$default_lang = $val;
					} else {						
						$form["languages"][$key]["selected"] = "";
					}
				}				


				
				if (is_array($form["languages"])) {
					$data = $_GET;
					foreach ($form["languages"] as $key => $val) {
						$data["lang_id"] = $val["id"];

						$form["languages"][$key]["details_link"] = "index.php?". http_build_query($data);
					}					
				}

				return $base->html->table(
					$this->template , 
					"Langs" , 
					$form["languages"]
				);
			}
			
		}
		

		

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __SortFallBack() {

		if (!isset($_GET["order"]) && $this->form["sql"]["vars"]["order"]) {
			$_GET["order"] = $this->form["sql"]["vars"]["order"]["import"];			
		}

		if (!isset($_GET["order_mode"]) && $this->form["sql"]["vars"]["order_mode"]) {
			$_GET["order_mode"] = $this->form["sql"]["vars"]["order_mode"]["import"];			
		}

	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function setAclMod($mod) {
		$this->aclMod = $mod;
	}
	
}


?>