<?php
/*
	Stempora Web Framework
	Copyright (c) 2002-2014 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com		
*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CLayouts extends CPlugin{
	
	var $tplvars; 

	function CLayouts() {
		//$this->CPlugin($db, $tables , $templates);
	}

	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;

		parent::DoEvents();

		if ($_GET["mod"] == "layouts") {

			$this->tpl_module = array(
				"mod_name" => "Layouts"
			);

			$sub = $_GET["sub"];
			$action = $_GET["action"];
			
			switch ($sub) {
				case "landing":
					$_GET["sub"] = $sub = "layouts";
				case "items":
				case "templates":
				case "layouts":
				case "layouts.parent":

					if (isModSubAct("layouts" , "layouts"  , "itemdetails")) {
						$data = new CSQLAdmin("layouts.parent", $this->__parent_templates,$this->db,$this->tables,$extra);
						$extra["details"]["after"] = $data->DoEvents();
					}
					

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$this->PrepareFields($data->forms["forms"]);
					$this->PrepareLayoutFields($data->forms["forms"]);

					if ($sub == "layouts") {
						$data->functions = array( 
									"ondelete"			=> array(&$this , "DeleteLayout"),
						);					
					}
					
					return $data->DoEvents();
				break;


				case "duplicate":
					return $this->Duplicate();
				break;

				case "editor":
					return $this->Editor();
				break;

				case "editor-save":
					return $this->EditorSave();
				break;

				case "settings":

/*
						$this->tpl_module = array(
							"mod_name" => "Layouts Settings"
						);
*/

						$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
						$this->PrepareDashboard($data->form);

						if ($data->Done()) {

							$this->vars->SetVars(
								$this->vars->ExtractVals(
									CForm::KeyFields($data->form),
									$_POST
								)
							);
						}
						
						return $data->Show(							
							$this->vars->GetVars(
								CForm::KeyFields($data->form)
							)
						
						);
				break;


			}
		}
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareLayoutFields(&$forms) {

		if (($_GET["sub"] == "layouts.parent") && ($_REQUEST["layout_parent"])) {
			$layout = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_id={$_REQUEST[layout_parent]}");

			//if its a footer then remove the design selection
			if ($layout["layout_template"] == "2") {
					CForm::DeleteFields($forms["edit"] , array("layout_template"));
					CForm::DeleteFields($forms["add"] , array("layout_template"));
			}
		}

		if (($_GET["sub"] == "items") && ($_REQUEST["layitem_layout"])) {

			$layout = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_id={$_REQUEST[layitem_layout]}");

			$forms["search"]["fields"]["layitem_column"]["dynamic"]["to"] = $layout["layout_columns"];

			

			if ($_GET["action"] == "add") {

				global $_LANG;


				$widgets = $this->GetWidgets();				
				if (is_array($widgets)) {

					foreach ($widgets as $key => $val) {
						
						$forms["add"]["fields"]["layitem_widget"]["options"][$val["widget_id"]] = $val["widget_name"];
					}
					


					
				}
				

			}			
			
		}
		
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetWidgets() {
				global $_LANG;

				$this->plugins["languages"]->DefaultLang();

				$widgets = $this->db->QFetchRowArray(
					"SELECT widget_type_name , widget_module_type, widget_module , w.widget_id, widget_name FROM 
					{$this->tables['core:widgets_lang']} as l,
					{$this->tables['core:languages']} as lang,
					{$this->tables['core:widgets']} as w

					WHERE
						l.lang_id = lang.lang_id AND 
						lang.lang_default = 1 AND 
						l.widget_id = w.widget_id  AND 
						l.widget_id > 0

					ORDER BY widget_module 
				"
				);
				
				if (is_array($widgets)) {
					foreach ($widgets as $key => $val) {

						$widgets[$key]["short_name"]  = $widgets[$key]["widget_name"] ;
						$widgets[$key]["module_name"] = "";

						switch ($val["widget_module_type"]) {
							case "0":
								$widgets[$key]["widget_type_name"] = "";
							break;
							//user
							case "1":
								$mod = $this->module->plugins["modules"]->GetModuleInfo($val["widget_module"] , false);
								$widgets[$key]["widget_name"] = $mod["mod_name"] . " - " . $val["widget_type_name"] . " - ( " . $val["widget_name"] . " )";									
								$widgets[$key]["module_name"] = $mod["mod_name"] ;								
								
							break;

							//system
							case "2":
								$mod = $this->module->plugins["modules"]->GetDefaultModuleInfoById($val["widget_module"]);
								$widgets[$key]["widget_name"] = $mod["module_name"] . " - " . $val["widget_type_name"] . " - ( " . $val["widget_name"] . " )";
								$widgets[$key]["module_name"] = $mod["module_name"] == "Widgets" ? "Static" : $mod["module_name"] ;
							break;

							default:

							break;

						}
						
					}
				}


				return $widgets;

	}
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Duplicate() {

		$layout = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_id={$_GET['layout_id']}");

		if (!is_array($layout)) {
			return "Invalid link !";
		}

		$blocks = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_parent={$layout[layout_id]} ORDER BY layout_order ASC");

		unset($layout["layout_id"]);
		unset($layout["layout_system"]);
		unset($layout["layout_generic"]);

		$layout["layout_name"] .= " ( Copy )";

		$lid = $this->db->QueryInsert(
			$this->tables['core:layouts'] , 
			$layout
		);

		if (is_array($blocks)) {
			foreach ($blocks as $key => $block) {

				//read all widgets
				$widgets = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:layouts_items']} WHERE layitem_layout={$block[layout_id]} ORDER BY layitem_order ASC");

				$tmp = $block;

				unset($block["layout_id"]);
				unset($block["layout_system"]);
				unset($block["layout_generic"]);

				$block["layout_parent"] = $lid;

				$bid = $this->db->QueryInsert(
					$this->tables['core:layouts'],
					$block,
					"layout_order"
				);

				if (file_exists("../upload/layouts/{$tmp[layout_id]}.jpg")) {
					copy(
						"../upload/layouts/{$tmp[layout_id]}.jpg",
						"../upload/layouts/{$bid}.jpg",
						0777
					);
				}
				
				if (file_exists("../upload/parallax/{$tmp[layout_id]}.jpg")) {
					copy(
						"../upload/parallax/{$tmp[layout_id]}.jpg",
						"../upload/parallax/{$bid}.jpg",
						0777
					);
				}

				if (file_exists("../upload/parallax/{$tmp[layout_id]}.mp4")) {
					copy(
						"../upload/parallax/{$tmp[layout_id]}.mp4",
						"../upload/parallax/{$bid}.mp4",
						0777
					);
				}

				if (is_array($widgets)) {
					foreach ($widgets as $_key => $widget) {

						unset($widget["layitem_id"]);
						unset($widget["layitem_order"]);

						$widget["layitem_layout"] = $bid;

						$wid = $this->db->QueryInsert(
							$this->tables['core:layouts_items'] , 
							$widget,
							"layitem_order"
						);
					}
				}			
			}			
		}
		
		//redirect to details page
		urlredirect(
			"index.php?mod=layouts&sub=layouts&layout_id={$lid}&action=edit&returnurl=" . 

			urlencode("index.php?mod=layouts&sub=layouts&layout_id={$lid}&action=itemdetails&returnurl=" . 
				urlencode("index.php?mod=layouts&sub=layouts")
			)
		);
				
	}
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DeleteLayout($record) {

		$blocks = $this->db->Linear($this->db->QFetchRowArray("SELECT layout_id FROM {$this->tables['core:layouts']} WHERE layout_parent={$record[layout_id]}"));

		if (is_array($blocks)) {
			$this->db->Query("DELETE FROM {$this->tables['core:layouts_items']} WHERE layitem_layout IN (" . implode("," , $blocks) . ")");
			$this->db->Query("DELETE FROM {$this->tables['core:layouts']} WHERE layout_id IN (" . implode("," , $blocks) . ")");
		}
		
		$this->db->Query("DELETE FROM {$this->tables['core:layouts_items']} WHERE layitem_layout={$record[layout_id]}");
	}

	

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

		global $base , $_TSM , $_LANG_ID;


		$_TSM["PUB:MODULE_NAME"] = "Layout Widgets Editor";


		//$_TSM

		$template = new CTemplateDynamic($this->tpl_path . "admin.editor.htm");

		$main_layout = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_id={$_GET[layout_id]} ");
		$layouts = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_parent={$_GET[layout_id]} ORDER BY layout_parent ASC,layout_order ASC");
		//$sublayouts = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['core:layouts']} WHERE layout_parent={$_GET[layout_id]} ORDER BY layout_order ASC");

		$widgets = $this->getWidgets();

		if (is_array($layouts)) {

			foreach ($layouts as $key => $layout) {

				$cnt ++;

				$columns_data = "";

				for ($i = 1; $i<=$layout["layout_columns"]; $i++ ) {

					$wid = $this->db->Linear($this->db->QFetchRowArray("SELECT layitem_widget FROM {$this->tables['core:layouts_items']} WHERE layitem_layout={$layout[layout_id]} AND layitem_column={$i} ORDER BY layitem_order ASC"));




					$columns_data .= $template->blockReplace(
						"Column" , 
						array(
							"widgets" => is_array($wid) ? implode("," , $wid) : "",
							"id"	=> $i,
							"size"	=> $layout["layout_c{$i}"],
							"data"	=> $base->htmlElements->Widget(
								array(
									"title"		=> "Group #{$i}",
									"icon"		=> "cogs",
									"skin"		=> "Blue",
									"height"	=> "",

									"content"	=> $template->blockReplace(
										"ColumnWidgets" , 
										array(
											
										)
									)
								)
							)
						)
					);			
				}


				//dont show paralax blocks that doesnt 
				if (!$layout["layout_parallax"] || ($layout["layout_parallax"] && $layout["layout_parallax_widgets"])) {

					$columns .= $base->htmlElements->Widget(
						array(
							"title"		=> "Block #{$cnt} " . ($layout["layout_name"] ? " (" . $layout["layout_name"] . ") " : "") , 
							"icon"		=> "cogs",
							"skin"		=> "Orange",
							"height"	=> "",

							"id"		=> "layout_block_1",

							"content"	=> $template->blockreplace(
								"Columns",
								array(
									"id"		=> $layout["layout_id"],

									"columns"	=> $columns_data
								)
							)											

						)
					);

				}				
			}
				
		}
		

		/*

		*/

		if (is_array($widgets)) {

			foreach ($widgets as $key => $val) {
				
				if ($val["widget_module_type"] == "1") {
					$mids[] = $val["widget_module"];
				}				

				$modules[$val["widget_module"]] = $val["module_name"];
			}	

			$_orig_widgets = $widgets;
			//debug($widgets,1);
			
			if (is_array($mids)) {
				//read all the modules to check for parents
				$mids_data = $this->db->QFetchRowArray(
					"SELECT mod_id , mod_parent FROM {$this->tables['core:user_modules']} WHERE mod_id in (" . implode("," , $mids) . ")"
				);

				//extract all the parents
				foreach ($mids_data as $key => $val) {
					$_mids[$val["mod_id"]] = $val;
					$pids[] = $val["mod_parent"];
				}

				$mids = $_mids;

			}

			//read the parents
			if (is_array($pids)) {
				$pids_data = $this->db->QFetchRowArray(
					"SELECT p.mod_id , mod_name FROM {$this->tables['core:user_modules']} as p ,{$this->tables['core:user_modules_lang']} as l
					WHERE p.mod_id=l.mod_id and l.lang_id={$_LANG_ID} AND p.mod_id in (" . implode("," , $pids) . ")"
				);

				if (is_array($pids_data)) {
					foreach ($pids_data as $key => $val) {
						$_pids[$val["mod_id"]] = $val;
					}						
				}

				$pids = $_pids;
			}					
				//debug($mids);

			

			if (is_array($pids)) {
				//process all widgets with parents
				foreach ($widgets as $key => $val) {
					switch ($val["widget_module_type"]) {

						case "1":
							$parent = $mids[$val["widget_module"]]["mod_parent"];
							if ($parent) {

								if (!$_menu[$parent]) {
									$_menu[$parent] = array(
										"title"	=> $_pids[$parent]["mod_name"],
										"items"	=> array()
									);//$_pids[$parent];
								}

								$_menu[$parent]["items"][$val["widget_module"]] =  array(
									"id"	=> $val["widget_module"],
									"title"	=> $val["module_name"],
								);									

								unset($widgets[$key]);
							} 
						break;
					}
				}
			}

			if (is_array($widgets) && count($widgets)) {
				//process widgets without parent and system widgets
				foreach ($widgets as $key => $val) {

					switch ($val["widget_module_type"]) {
						//instance module
						case "1":
							//check if it has a parent							
							$_menu[$val["widget_module"]] =  array(
								"id"	=> $val["widget_module"],
								"title"	=> $val["module_name"],
							);									
						break;

						//global modules
						case "2":

							if ($val["module_name"] == "Widgets") {
								$val["module_name"] = "Static Widgets";
							}
							

							$system[$val["widget_module"]] =  array(
								"id"	=> $val["widget_module"],
								"title"	=> $val["module_name"],
							);																	
						break;
					}
					
				}
			}
					
			if (is_Array($system)) {
				foreach ($system as $key => $val) {
					$_menu[] = $val;
				}						
			}
					
			if (is_array($_menu)) {

				foreach ($_menu as $key => $val) {

					if (is_array($val["items"])) {
						$widgets_options.= "<optgroup label='{$val[title]}'>\n";

						foreach ($val["items"] as $k => $v) {
							$widgets_options.= "\t<option value='.widget-type-{$v[id]}'>{$v[title]}</option>\n";
						}
						
						$widgets_options.= "</optgroup>\n";
					
					} else {
						$widgets_options.= "<option value='.widget-type-{$val[id]}'>{$val[title]}</option>\n";
					}					
				}
				
			}
			
		}
		
		
		return $template->blockReplace(
			"Main" , 

			array(

				"return"	=> urldecode($_GET["returnurl"]),

				"tabs"		=> CFormsTabs::newInstance(CConfig::newInstance($this->plugins["modules"]->forms_path . "/dashboard.xml")->vars["tabs"])
									->Render(),

				"widgets"	=> $base->htmlElements->Widget(
										array(
											"title"		=> "Available Widgets",
											"icon"		=> "settings",
											"skin"		=> "Blue",
											"height"	=> "",

											"content"	=> CTemplateStatic::Replace(
												$base->html->Table(
													$template , 
													"Widgets",
													$_orig_widgets
												),
												array(
													"options"	=> $widgets_options
												)
											),

										)
									),

				"layout"	=> $base->htmlElements->Widget(
										array(
											"title"		=> "Edit " . $main_layout["layout_name"] . "",
											"icon"		=> "cogs",
											"skin"		=> "Orange",
											"height"	=> "",

											"content"	=> $template->blockReplace("Info"),

											"buttons"	=>	array(
												"back"	=> array(
													"type"		=> "button",
													"icon"		=> "back",
													"title"		=> "Back",
													"location"		=> urldecode($_GET["returnurl"]),
												),

												"save"	=> array(
													"type"		=> "button",
													"icon"		=> "save",
													"title"		=> "Save",
													"location"	=> "#",
													"onclick"	=> "SaveLayout()",
												),
											),



										)
									),
										

				"columns"	=> $columns
				
				
			)
		);

	}

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

		$layouts = json_decode(stripslashes($_POST["data"]),true);

		if (is_array($layouts)) {
			foreach ($layouts as $key => $layout) {
				//delete all the widgets for this layout
				$this->db->Query("DELETE FROM {$this->tables['core:layouts_items']} WHERE layitem_layout={$key}");

				if (is_array($layout)) {
					foreach ($layout as $k => $v) {
						$id = $this->db->QueryInsert(
							$this->tables['core:layouts_items'],
							array(
								"layitem_layout"		=> $v["layout"],
								"layitem_widget"		=> $v["widget"],
								"layitem_column"		=> $v["colum"],
							)
						);

						$this->db->QueryUpdate(
							$this->tables["core:layouts_items"],
							array(								
								"layitem_order"			=> $id,
							),
							"layitem_id={$id}"
						);
					}
					
				}
				

				
			}
		}
		
		



		return json_encode(array(
			"status"	=> "ok",
			"redirect"	=> "xxx",
		));
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function LoadFromFile($path) {
		$layout = new CConfig($path);
		$layout = $layout->vars["layout"];

		return $this->LoadFromString($layout);
	}
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function LoadFromString($layout) {

		//some default checks

		if (!is_array($layout["block"][0])) {
			//one block layout
			$layout["block"] = array(
				0	=> $layout["block"]
			);
		}

		foreach ($layout["block"] as $key => $block) {


			if (!is_array($block["col"][0])) {
				$layout["block"][$key]["col"] = array(
					0	=> $block["col"]
				);

			}			
		}
		

		foreach ($layout["block"] as $key => $block) {
			foreach ($block["col"] as $_key => $_val) {
				if (!is_array($_val["widget"])) {
					$layout["block"][$key]["col"][$_key]["widget"] = array(
						0	=> $_val["widget"]
					);
				}
				
			}
			
		}

	
		return $layout;
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SaveLayout($layout) {

		//save the main block
		$id = $this->db->QueryInsert(
			$this->tables["core:layouts"] , 
			array(
				"layout_name" => $layout["name"],
				"layout_template"	=> $layout["template"] == "footer" ? "2" : 1,
			)
		);

		foreach ($layout["block"] as $key => $val) {

			$block = array(
				"layout_parent"		=> $id,
				"layout_columns"	=> 0,
			);

			//calculate the number of columns and the size for each
			foreach ($val["col"] as $_key => $_val) {
				$block["layout_columns"] ++;
				$block["layout_c" . $block["layout_columns"]] = $_val["size"];
			}
			
			//save the new block
			$bid = $this->db->QueryInsert(
				$this->tables['core:layouts'],
				$block
			);

			$this->db->QueryUpdate(
				$this->tables["core:layouts"],
				array(
					"layout_order" => $bid
				),
				"layout_id={$bid}"
			);

			//save the widgets to each block
			foreach ($val["col"] as $_k => $_v) {

				foreach ($_v["widget"] as $__k => $__v) {

					switch ($__v) {
						case "__CONTENT__":
							$__v = "-1";
						break;
					}
					

					$wid = $this->db->QueryInsert(
						$this->tables["core:layouts_items"],
						array(
							"layitem_layout"	=> $bid , 
							"layitem_column"	=> $_k + 1,
							"layitem_widget"	=> $__v,
						)
					);

					$this->db->QueryUpdate(
						$this->tables["core:layouts_items"] , 
						array(
							"layitem_order"	=> $wid
						),
						"layitem_id = {$wid}"
					);

				}
				

			}
			
		}

		return $id;
		
	}
	
	

}

?>