<?php

class CMaintenance extends CPlugin{
	
	var $tplvars; 

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

		$this->name = "maintenance";
	}

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


		if ($_GET["mod"] == $this->name) {
			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("maintenance");

			parent::DoEvents();

			$sub = $_GET["sub"];
			$action = $_GET["action"];

			//read the module
			global $_MAINTENANCE_MODULE;
			$_MAINTENANCE_MODULE  = $this->tpl_module;

			switch ($sub) {

				case "landing":
					$sub = "messages";
				case "messages":
					$this->plugins["dashboard"]->UpdateModuleAction($this->tpl_module["module_id"]);

					if ($_GET["item_id"]) {
						$this->db->QueryUpdate(
							$this->tables["plugin:maintenance_messages"],
							array(
								"item_new" => 0,
							),
							"item_id='{$_GET[item_id]}'"
						);
					}

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

					$data->functions = array( 
							"onstore_prepare"		=> array(&$this , "SendMail"),
					);					

					return $data->DoEvents();

				break;


				case "settings":

					switch ($_GET["a"]) {
						case "language":
							urlredirect("index.php?mod=modules&sub=default-language&action=details&module_code={$this->tpl_module['module_code']}&t=u");
						break;

						case "advanced":
							urlredirect("index.php?mod=modules&sub=default-settings&action=details&module_code={$this->tpl_module['module_code']}&t=u");
						break;

						default:
							urlredirect("index.php?mod=modules&sub=default&action=details&module_code={$this->tpl_module['module_code']}&t=u");
						break;

					}
					
				break;

				case "texts":
					$_GET["module_id"] = $this->tpl_module["module_id"];
					return $this->__adminTexts();
				break;

//				default:
//					$sub = "users";
				case "users":
					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($this->tpl_module);
					$this->PrepareFields($data->forms["forms"]);


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

					return $data->DoEvents();
				break;

				case "messages-delete":
					return $this->MessagesDelete();
				break;

			}
		}
	}

	
	function StoreUser($record) {
		global $_CONF;

		//check if is a new user
		if (!$record["user_id"]) {

			$_POST["user_date"]				= time();
			$_POST["user_key"]				= md5($_POST["user_email"] . time());

			//update the record
			$record = $_POST;			
		}

		//notification emails if the status was changed
		if ($record["user_id"] && $_POST["send_mail"]) {


			if (!$record["user_key"]) {

				$data = $this->db->QFetchArray("SELECT user_key FROM {$this->tables['plugin:maintenance_users']} WHERE user_id={$record[user_id]}");

				$record = array_merge(
					$record , 
					$data
				);
			}
			
			$id = $this->module->plugins["mail"]->SendMail(
				$this->module->plugins["mail"]->GetMail(
					$this->tpl_module["settings"]["set_notification_mail"],
					array(
						"first_name"		=> $record["user_first_name"],
						"last_name"			=> $record["user_last_name"],
						"email"				=> $record["user_email"],
						"invite_link"		=> $_CONF["url"] . "?invite={$record[user_key]}"
					)
				)
			);			

			//hell knows why this happends
			$_POST["send_mail"] = 0;



		}
		

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function NoticeBar() {
		$tpl = $this->module->plugins["modules"]->LoadDefaultModule("maintenance");

		if ($tpl["settings"]["set_active"]) {

			$who = array(
				"1"		=> "everyone",
				"2"		=> "admins only",
				"3"		=> "visitors only",
			);

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

			return $template->blockReplace(
				"Main" , 
				array(
					"module"	=> $tpl["module_id"] , 
					"who"		=> $who[$tpl["settings"]["set_active"]]
				)
			);
		}	
	}


	function SendMail() {


		$message = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:maintenance_messages']} WHERE item_id={$_POST[item_id]}");

		$this->module->plugins["mail"]->SendMail(
			$this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_reply"],
				array(
					"name"				=> $message["item_name"],
					"email"				=> $message["item_email"],
					"subtitle"			=> $message["item_subject"],
					"message"			=> $message["item_message"],
					"reply"				=> $_POST["reply_body"],
				)
			)
		);

		$this->db->QueryUpdate(
			$this->tables['plugin:maintenance_messages'],
			array(
				"item_replied"	=> "1",
				"item_replied_date"	=> time(),
				"item_reply"		=> $_POST["reply_body"],
			),
			"item_id={$message[item_id]}"
		);

		urlredirect("index.php?mod=maintenance&sub=messages");
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DashboardNumbers($mod_id=null) {
		global $_SESS , $base;
		$module = $this->module->plugins["modules"]->LoadDefaultModule("maintenance");

		if (!$module["settings"]["set_active"]) {
			return "";	
		}

		if (!$base->acl->checkModRule($module , "msg.list")) {
			return "";
		}

		

		if (is_array($module)) {
			return array(
				array(
					"skin"		=> "Teal",
					"icon"		=> "email",
					"link"		=> "index.php?mod=maintenance&sub=messages",
					"count"		=> $this->db->RowCount($this->tables['plugin:maintenance_messages'], "WHERE item_new=1 AND item_date > " . $this->plugins["dashboard"]->GetAccessDate($module["module_id"])),
					"title"		=> "New Messages",
					"subtitle"	=> $module["module_name"],
				),
			);

		}
	}


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

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

		if (!$module["settings"]["set_active"]) {
			return "";
		}
	
			if (!$base->acl->checkModRule($module , "msg.list")) {
			return "";
		}


		if (is_array($module)) {		
			$_CONF["forms"]["adminpath"] = _MODPATH . "maintenance/forms/";

			$latest = new CSQLAdmin("dashboard/latest", $this->__parent_templates,$this->db,$this->tables,$extra);
			$content = $latest->DoEvents();

			if (!(stristr($content , "No available records.") && !$_GET["showempty"])) {

				return array(
					array(
						"width"	=> "6",
						"type"	=> "widget",
						"pos"	=> "1",
						"body"	=> $content
					),
				);
			}
		}			

	}




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

		if (is_array($_POST["item_id"])) {
			$this->db->Query(
				"DELETE FROM {$this->tables['plugin:maintenance_messages']} WHERE item_id IN (" . implode("," , $_POST["item_id"]). ")"
			);
		}
		
		die("1");
	}



	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function PrepareMSGFields(&$forms , $sub) {
		if (($_GET["action"] == "edit") || ($_GET["action"] == "store")) {

			$message = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:maintenance_messages']} WHERE item_id={$_REQUEST[item_id]}");

			if ($message["item_replied"]) {

				$forms["edit"]["fields"]["box"]["1"] = $forms["edit"]["fields"]["box"]["2"];
				unset($forms["edit"]["fields"]["box"]["2"]);
			} else {

				unset($forms["edit"]["fields"]["box"]["2"]);
			}
		}		
	}


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

	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function mailTemplateVars($module , $operation = "list" , $template = "") {

		switch ($operation) {
			case "list":
				//return the list of possible templates for this 
				return array(
					"generic"	=> "Notification",
					"reply"		=> "CMS Reply",
					"invite"	=> "Invitation",
				);
			break;

			case "vars":
				return $this->MailTemplateVarsList($template , $module);
			break;
		}		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function mailTemplateVarsList($template) {

		switch ($template) {
			case "generic":
				$misc = array(
					"set"		=> "Visitor",
					"fields"	=> array(
						"name"		=> "Name",
						"email"		=> "Email Address",
						"message"	=> "Message",
					),
				);
			break;

			case "reply":
				$misc = array(
					"set"		=> "Visitor",
					"fields"	=> array(
						"name"		=> "Name",
						"email"		=> "Email Address",
						"reply"		=> "Reply Message",
						"message"	=> "Original Message",
					),
				);
			break;

			case "invite":
				$misc = array(
					"set"		=> "Client",
					"fields"	=> array(
						"first_name"	=> "First Name",
						"last_name"		=> "Last Name",
						"email"			=> "Email Address",
						"invite_link"	=> "Invitation Link",
					),
				);
			break;

		}
		
		$sets[] = $misc;

		return $sets;
	}


}

?>