<?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 CWidgets extends CPlugin{
	
	var $tplvars; 

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

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

		parent::DoEvents();

		if ($_GET["mod"] == "widgets") {
			$sub = $_GET["sub"];
			$action = $_GET["action"];

			//read the module
			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("widgets");			

			switch ($sub) {

				case "landing":					
				case "widgets.mod":					
				case "widgets.module":										

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

					$data->functions = array( 
//							"onstore_prepare" => array(&$this , "StoreUser"),
							"onstore" => array(&$this , "StoreWidget" ),
							//"list" => array(&$this , "Bubu" ),
					);					

					return $data->DoEvents();

				break;


				default:

					$file = $this->forms_path  . $sub . ".xml";

					if (file_exists($file)) {
						$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
						$this->PrepareFields($data->forms["forms"]);
						return $data->DoEvents();
					}
				break;
					

				case "add-widget":

					if (!$_GET["action"]) {
						$_GET["action"] = "edit";
					}


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

					if ($data->Done()) {

						$this->SaveWidget();

					}					
					return $data->Show($_GET);

				break;
			}
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/

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

		if (!$_GET["module_code"]) {

			if ($_GET["mod_id"]) {
				$cond = "m.mod_id={$_GET[mod_id]} AND " ;
			}
			

			$modules = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['core:languages']} as l,
					{$this->tables['core:user_modules']} as m,
					{$this->tables['core:user_modules_lang']} as ml
				WHERE
					{$cond}
					ml.lang_id = l.lang_id AND 
					l.lang_default = 1 AND 
					m.mod_id = ml.mod_id 
				");


			if (is_array($modules)) {
				foreach ($modules as $key => $val) {

					if (method_exists($this->module->plugins[$val["mod_module_code"]] , "adminGetWidgets")) {
						$tmp_widgets = $this->module->plugins[$val["mod_module_code"]]->adminGetWidgets($val);

						if (is_array($tmp_widgets)) {
							foreach ($tmp_widgets as $k => $v) {
								$widgets[] = $v;
							}						
						}
						
					}
					
				}			
			}

			if ($_GET["mod_id"]) {
				return $widgets;
			}

		}
		

		if ($_GET["module_code"]) {
			$cond2 = " r.module_code LIKE '{$_GET[module_code]}' AND ";
		}
		
		
		//process the core modules
		$core = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:modules']} as r,
				{$this->tables['core:modules_lang']} as l,
				{$this->tables['core:languages']} as ml
			WHERE 
				{$cond2}
				r.module_id = l.module_id AND 
				ml.lang_id = l.lang_id AND 
				ml.lang_default=1 AND 
				module_status=1 AND 
				module_type=2 
			");

		if (is_array($core)) {
			foreach ($core as $key => $val) {

				if (method_exists($this->module->plugins[$val["module_code"]] , "adminGetWidgets")) {
					$tmp_widgets = $this->module->plugins[$val["module_code"]]->adminGetWidgets($val);

					if (is_array($tmp_widgets)) {
						foreach ($tmp_widgets as $k => $v) {
							$widgets[] = $v;
						}						
					}
					
				}
				
			}			
		}


		return $widgets;

	}

	
	function PrepareAddForm(&$form) {

		$widgets = $this->GetWidgets();



		if (is_array($widgets)) {
			foreach ($widgets as $key => $val) {
				$form["fields"]["type"]["options"][$val["type"] . "-" . $val["module"]] = $val["module_name"] . " - " . $val["name"];
			}
			
		}
		
	}


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

		$widgets = $this->GetWidgets();

		$tmp = explode("-" , $_POST["type"]);

		if (is_array($widgets)) {
			foreach ($widgets as $key => $val) {
				if (($val["type"] == $tmp[0]) && ($val["module"] == $tmp[1])) {
					$widget = $val;
				}				
			}
		}
		

		$id = $this->db->QueryInsert(
			$this->tables["core:widgets"],
			array(
				"widget_type"			=> $widget["type"],
				"widget_type_name"		=> $widget["name"],
				"widget_module"			=> $widget["module"] , 
				"widget_module_type"	=> $widget["module_type"] , 
				"widget_name"			=> $_POST["name"],
				"widget_status"			=> "1", //disabled				
				"widget_show_title"		=> "1", //disabled				
				"widget_device"			=> "1,2,3",

			)
		);


		if ($_GET["mod_id"]) {
			urlredirect(
				"index.php?mod=widgets&sub=widgets.mod&action=edit&widget_id={$id}&t=u&returnurl=" . 
				urlencode("index.php?mod=widgets&sub=landing&action=details&widget_id={$id}&t=u&returnurl=" . 
					urlencode("index.php?mod=widgets&sub=widgets.mod&module_id={$_GET[mod_id]}")
				)
			);		
		} else {	


			if ($_GET["module_code"]) {

				urlredirect(
					"index.php?mod=widgets&sub=landing&action=edit&widget_id={$id}&t=u&returnurl=" . 
					urlencode("index.php?mod=widgets&sub=widgets.module&action=details&widget_id={$id}&t=u&returnurl=" . 
						urlencode("index.php?mod=widgets&sub=widgets.module&module_code={$_GET[module_code]}")
					)
				);	

			}
			

			urlredirect(
				"index.php?mod=widgets&sub=landing&action=edit&widget_id={$id}&returnurl=" . 
				urlencode("index.php?mod=widgets&sub=landing&action=details&widget_id={$id}&returnurl=" . 
					urlencode("index.php?mod=widgets&sub=landing")
				)
			);	
		}
	}



	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareWidgetFields(&$forms) {
		
		//debug($forms);

		if ($_REQUEST["widget_id"]) {			
			$widget = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets']} WHERE widget_id={$_REQUEST[widget_id]}");
			$_GET["module_id"] = $widget["widget_module"];

			//$module = $this-
			switch ($widget["widget_module_type"]) {
				case "1":
					$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:user_modules']} WHERE mod_id={$widget[widget_module]}");
					$_GET["module_id"] = $module["mod_id"];
					$path = $this->module->plugins[$module["mod_module_code"]]->forms_path . "widgets/" . $widget["widget_type"] . ".xml";
				break;

				case "2":
					$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules']} WHERE module_id={$widget[widget_module]}");
					$_GET["module_id"] = $module["module_id"];
					$path = $this->module->plugins[$module["module_code"]]->forms_path . "widgets/" . $widget["widget_type"] . ".xml";
				break;
			}			

			if (file_exists($path)) {
				$fields = new CConfig($path);
			}
			
			

			if (!is_array($fields->vars["widget"]) && is_Array($fields->vars["fields"])) {
				$fields->vars = array(
					"widget"	=> array(
						"fields" => $fields->vars["fields"]
					) 
				);
			}

			if (is_array($fields->vars["widget"]["fields"])) {

				foreach ($fields->vars["widget"]["fields"] as $key => $val) {

					//debug($fields->vars["widget"]["fields"]["box"],1);
					
					if (is_array($fields->vars["widget"]["fields"]["box"])) {
						
						foreach ($fields->vars["widget"]["fields"]["box"] as $k => $v) {
							$forms["forms"]["edit"]["fields"]["box"][] =$v;						
							if ($key != "box") $val["editable"] = "false";
							$forms["forms"]["details"]["fields"][$key] =$val;						
						}
						
					} else {
						$forms["forms"]["edit"]["fields"]["box"][0]["fields"][$key] = $val;						
						if ($key != "box") $val["editable"] = "false";
						$forms["forms"]["details"]["fields"]["box"][0]["fields"][$key] =$val;
					}
										

				}
			}

			if (is_Array($fields->vars["widget"]["after"])) {
				$forms["after"] = $fields->vars["widget"]["after"];
			}		

			
			if (is_Array($fields->vars["widget"]["javascript"])) {
				$forms["forms"]["edit"]["javascript"] = $fields->vars["widget"]["javascript"];
			}		

			if (is_array($fields->vars["widget"]["settings"])) {

				if ($fields->vars["widget"]["settings"]["permissions"] == "false") {

					$remove = array("subtitle_persmissions" , "widget_perm" , "widget_perm_groups" , "widget_perm_memberships" );

					CForm::DeleteFields($forms["forms"]["edit"] , $remove);
					CForm::DeleteFields($forms["forms"]["details"] , $remove);
				}				
			}
		

		}
	}

	function PrepareWidgetValues(&$forms) {

		if (!$_REQUEST["lang_id"]) {
			$lang = $this->module->plugins["languages"]->DefaultLang();
			$_REQUEST["lang_id"] = $lang["lang_id"];

		}		


		if ($_REQUEST["widget_id"]) {			
			$widget = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets']} WHERE widget_id={$_REQUEST[widget_id]}");
			$lwidget = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets_lang']} WHERE widget_id={$_REQUEST[widget_id]} AND lang_id={$_REQUEST[lang_id]}");

			//$module = $this-

			switch ($widget["widget_module_type"]) {
				case "1":
					$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:user_modules']} WHERE mod_id={$widget[widget_module]}");
				break;

				case "2":
					$module = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:modules']} WHERE module_id={$widget[widget_module]}");
				break;
			}

			
			//just changed
			$values = /*RemoveArraySlashes*/(unserialize(base64_decode($widget["widget_settings"])));
			$lvalues = /*RemoveArraySlashes*/(unserialize(base64_decode($lwidget["widget_set_lang"])));

			if (is_array($lvalues)) {
				foreach ($lvalues as $key => $val) {
					$values[$key] = $val;
				}
				
			}						

			if (is_array($forms["edit"]["fields"])) {
				foreach ($forms["edit"]["fields"] as $key => $val) {

					if ($key == "box") {
						foreach ($val as $k => $v) {
							foreach ($v["fields"] as $_k => $_v) {
								$forms["edit"]["fields"][$key][$k]["fields"][$_k]["default"] = $values[$_k];
								$forms["details"]["fields"][$key][$k]["fields"][$_k]["default"] = $values[$_k];
							}
						}
						
					} else {				
						$forms["edit"]["fields"][$key]["default"] = $values[$key];
						$forms["details"]["fields"][$key]["default"] = $values[$key];
					}
				}
			}

		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function StoreWidget($record , $form) {

		if ($record["widget_id"]) {

			//fields
			$old = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets']} WHERE widget_id={$record[widget_id]}");
			if ($old["widget_settings"]) {
				$old["widget_settings"] = unserialize(base64_decode($old["widget_settings"]));
			}

			//process for image fields
			$fields = CForm::AllFields($form["forms"]["edit"]);
		
			if (is_array($fields)) {
				foreach ($fields as $key => $val) {
					switch ($val["type"]) {
						case "image":

							if ($old["widget_settings"][$key] && !$_POST[$key] && !$_POST[$key . "_tmp"]) {
								$_POST[$key] = $old["widget_settings"][$key];
							}							
						break;
					}					
				}				
			}
					


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

				//ignore image processing fields
				if (
					stristr($key , "_temp") || 
					stristr($key , "_temp_file") ||  
					stristr($key , "_radio_type") || 
					stristr($key , "_crop_oxbc"))    
				{

				} else {

					if (stristr($key , "set_")) {
						$data[$key] = $val;
					}

					if (stristr($key , "lang_")) {
						$ldata[$key] = $val;
					}
				}

			}

			if (is_array($ldata)) {
				
/*				$lang = $this->db->QFetchArray(
					"SELECT * FROM {$this->tables['core:widgets_lang']} WHERE lang_id={$_POST[lang_id]} AND widget_id={$record[widget_id]}"
				);

				if (is_array($lang)) {*/
					$this->db->QueryUpdate(
						$this->tables['core:widgets_lang'],
						array(
							"widget_set_lang"	=> base64_encode(serialize($ldata)),
						),
						"widget_id={$record[widget_id]} AND lang_id={$_POST[lang_id]}"
					);
/*				} else {				
					$this->db->QueryInsert(
						$this->tables["core:widgets_lang"],
						array(
							"widget_settings"	=> base64_encode(serialize($data)),
						),
						"widget_id={$record[widget_id]}"
					);
				}*/

			}						

			if (is_array($data)) {
				$this->db->QueryUpdate(
					$this->tables["core:widgets"],
					array(
						"widget_settings"	=> base64_encode(serialize($data)),
					),
					"widget_id={$record[widget_id]}"
				);
			}						
		}
		
	}

	

	function adminGetWidgets($module) {

		$module["module_name"] = "Static Widgets";

		$widgets = array(
			array(
				"type"				=> "1",
				"name"				=> "Text Widget",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),
/*
			array(
				"type"				=> "15",
				"name"				=> "Image Widget",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),
*/
			array(
				"type"				=> "2",
				"name"				=> "Facebook Like Box",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),


			array(
				"type"				=> "3",
				"name"				=> "Links",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),
/*
			array(
				"type"				=> "7",
				"name"				=> "Links with Icons",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),
*/
			array(
				"type"				=> "5",
				"name"				=> "Link to Dropdown Menu",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "4",
				"name"				=> "Accordion",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),


			array(
				"type"				=> "6",
					"name"				=> "Raw HTML",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),


			array(
				"type"				=> "7",
				"name"				=> "Tabs",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "8",
				"name"				=> "Progress",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "9",
				"name"				=> "Countdown",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "11",
				"name"				=> "Flipbox Set",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "16",
				"name"				=> "Card Set",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),


			array(
				"type"				=> "12",
				"name"				=> "Counter",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "13",
				"name"				=> "Twitter Feed",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

		);

		return $widgets;

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AddWidget($widget) {

		$id = $this->db->QueryInsert(
			$this->tables['core:widgets'],
			array(
				"widget_type"			=> $widget["type"],
				"widget_type_name"		=> $widget["type_name"] ,
				"widget_settings"		=> base64_encode(serialize($widget["settings"])),
				"widget_status"			=> "1",
				"widget_module"			=> $widget["module"],

				"widget_module_type"	=> "1",
				"widget_show_title"		=> isset($widget["show_title"]) ? $widget["show_title"] : 1,

				"widget_perm"			=> "1",
				"widget_device"			=> "1,2,3",
			)
		);

		//get all the languages, its up to the user to translate them
		$langs = $this->plugins["languages"]->GetLanguages();

		if (is_array($langs)) {
			foreach ($langs as $key => $lang) {
				$this->db->QueryInsert(
					$this->tables['core:widgets_lang'],
					array(
						"widget_id"				=> $id,
						"lang_id"				=> $lang["lang_id"],
						"widget_settings"		=> base64_encode(serialize($widget["language"])),
						"widget_name"			=> $widget["title"],
					)
				);
			}			
		}

		//return the widget id
		return $id;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareModuleTabs(&$forms) {
		global $_TSM;

		if (($_GET["t"] == "u") && ($_GET["sub"] == "landing")) {
			//get widget 
			if ($_REQUEST["widget_id"]) {
				$widget = $this->db->QFetchArray("SELECT * FROM {$this->tables['core:widgets']} WHERE widget_id={$_REQUEST[widget_id]}");

				switch ($widget["widget_module_type"]) {
					case "1":
						$_GET["sub"] = "widgets.mod";
					break;

					case "2":
						$_GET["sub"] = "widgets.module";
					break;

				}
								
			}
			
		}
		

		switch ($_GET["sub"]) {
			case "widgets.mod":
				$module = $this->plugins["modules"]->GetModuleInfo($_GET["module_id"] , false);
				$tabs_file = $this->module->plugins[$module["mod_module_code"]]->forms_path . "dashboard.xml";

				$_TSM["PUB:MODULE_NAME"]= $module["mod_name"];
			break;

			case "widgets.module":
			
				if (!$_GET["module_code"] && $_GET["module_id"]) {
					$module = $this->module->plugins["modules"]->LoadDefaultModule($_GET["module_id"] , "id"); 
				} else {
					$module = $this->module->plugins["modules"]->LoadDefaultModule($_GET["module_code"]);
				}

				$_GET["module_id"] = $module["module_id"];

				$tabs_file = $this->module->plugins[$module["module_code"]]->forms_path . "dashboard.xml";

				$_TSM["PUB:MODULE_NAME"]= $module["module_name"] ? $module["module_name"]  : $module["module_type_name"] ;
			break;

		}


		if (file_exists($tabs_file)) {
			$tabs = new CConfig($tabs_file);
			$tabs = $tabs->vars["tabs"];

			$forms["forms"]["details"]["tabs"] = $tabs;
			$forms["forms"]["edit"]["tabs"] = $tabs;
			$forms["forms"]["list"]["tabs"] = $tabs;

		}			

		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareDashboard(&$form) {
		global $_TSM;

		parent::PrepareDashboard($form);

		if ($_GET["module_code"]) {

			$module = $this->module->plugins["modules"]->LoadDefaultModule($_GET["module_code"]);
			$_GET["module_id"] = $module["module_id"];
			$tabs_file = $this->module->plugins[$module["module_code"]]->forms_path . "dashboard.xml";

			$_TSM["PUB:MODULE_NAME"]= $module["module_name"] ? $module["module_name"]  : $module["module_type_name"] ;

		}

		if ($_GET["mod_id"]) {

			$_GET["module_id"] = $_GET["mod_id"];
			$module = $this->plugins["modules"]->GetModuleInfo($_GET["mod_id"] , false);
			$tabs_file = $this->module->plugins[$module["mod_module_code"]]->forms_path . "dashboard.xml";
			$_TSM["PUB:MODULE_NAME"]= $module["mod_name"];
		}
		

		if (file_exists($tabs_file)) {
			$tabs = new CConfig($tabs_file);
			$tabs = $tabs->vars["tabs"];

			$form["tabs"] = $tabs;
		}
		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function FormatLocalWidgets($items , $items_count) {

		debug($items,1);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Bubu(&$items , &$items_count) {
		debug($items);
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ShortcodesBrowser() {
		global $_LANG_ID , $base;

		$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("widgets");			


		$widgets = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:widgets']} as r,
				{$this->tables['core:widgets_lang']} as l

			WHERE
				r.widget_id = l.widget_id AND 
				l.lang_id = {$_LANG_ID} AND
				r.widget_id != -1 
			ORDER BY widget_type_name
			"
		);

		if (is_array($widgets)) {
			foreach ($widgets as $key => $val) {
				$widgets[$key]["cnt"] = ++$cnt;

				$tmp = explode("," , $val["widget_device"]);
				$data = "";


				if (in_array("1" , $tmp))
					$data[] = '<span class="f16 sign sign-desktop"></span>';

				if (in_array("2" , $tmp))
					$data[] = '<span class="f16 sign sign-tablet"></span>';

				if (in_array("3" , $tmp))
					$data[] = '<span class="f16 sign sign-phone"></span>';

				
				if (is_Array($data)) {
					$widgets[$key]["devices"] = implode(", " , $data);
				} else {
					$widgets[$key]["devices"] = "";
				}

			}
			
		}
		

		$tpl = new CTEmplateDynamic($this->tpl_path . "admin.shortcodes.htm");

		return array(
			"title"				=> $this->tpl_module["module_name"] , 
			"html"				=> $base->html->Table(
				$tpl, 
				"" , 
				$widgets			
			)
		);
	}
	
}

?>