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

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}
// dependencies

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

	function __construct() {
		$this->name = "contact";
	}

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

		if ($_GET["mod"] == $this->name) {
			//read the module
			$this->tpl_module = $this->module->plugins["modules"]->getModuleInfo($_GET["module_id"]);
			$this->plugins["modules"]->ValidateModule($this->tpl_module);

			parent::DoEvents();

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


			global $_CONTACT_MODULE;
			$_CONTACT_MODULE = $this->tpl_module;

			switch ($sub) {

				case "texts":
					return $this->__adminTexts();
				break;
	
				case "landing":
					$sub = "messages";
				case "messages":
					$this->plugins["dashboard"]->UpdateModuleAction($this->tpl_module["mod_id"]);

					//force lower fields code
					if ($_POST["item_field"]) 
						$_POST["item_field"] = strtolower($_POST["item_field"]);

					if ($_GET["item_id"]) {
						$this->db->QueryUpdate(
							$this->tables["plugin:contact_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 "departments":
				case "fields":
					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($this->tpl_module);
					$this->PrepareFields($data->forms["forms"]);
					return $data->DoEvents();
				break;

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

			}
		}
	}

	function SendMail() {

		$message = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:contact_messages']} WHERE item_id={$_POST[item_id]}");
		$vars = unserialize($message["item_vars"]);
		$vars["reply_message"] = $_POST["reply_body"];

		$this->module->plugins["mail"]->SendMail(
			$this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_reply"],
				$vars
			)
		);

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


		urlredirect("index.php?mod=contact&sub=landing&module_id={$_GET[module_id]}");

	}



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

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


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

		$module = $this->module->plugins["modules"]->getModuleInfo($mod_id);		

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

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

		if (is_array($module)) {		
			$_GET["module_name"] = $module["mod_name"] ;
			$_GET["module_id"] = $mod_id;
			$_CONF["forms"]["adminpath"] = _MODPATH . "contact/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
					),
				);
			}
		}			

	}


	function DashboardNumbers($module) {
		global $_SESS , $base;

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

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


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

		if (is_array($module)) {

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

		}
	}




	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function onCreate($module_data) {
		global $_LANG_ID;

		$fields = array(

			array(
				"module_id"		=> $module_data["mod_id"],
				"lang_id"		=> $_LANG_ID,
				"item_field"	=> "first_name",
				"item_type"		=> "usertext",
				"item_required"	=> "1",
				"item_size"		=> "6",
				"item_size_xs"	=> "12",
				"item_title"	=> "First Name",

				"item_error_msg"=> "Enter your first name!",
			),

			array(
				"module_id"		=> $module_data["mod_id"],
				"lang_id"		=> $_LANG_ID,
				"item_field"	=> "last_name",
				"item_type"		=> "usertext",
				"item_required"	=> "1",
				"item_size"		=> "6",
				"item_size_xs"	=> "12",
				"item_title"	=> "Last Name",
				"item_error_msg"=> "Enter your last name!",
			),

			array(
				"module_id"		=> $module_data["mod_id"],
				"lang_id"		=> $_LANG_ID,
				"item_field"	=> "email",
				"item_type"		=> "useremail",
				"item_required"	=> "1",
				"item_size_xs"	=> "12",
				"item_system"	=> "1",
				"item_title"	=> "Email",
				"item_error_msg"=> "Enter your email!",
			),

			array(
				"module_id"		=> $module_data["mod_id"],
				"lang_id"		=> $_LANG_ID,
				"item_field"	=> "departments",
				"item_type"		=> "departments",
				"item_required"	=> "",
				"item_size_xs"	=> "12",
				"item_title"	=> "Department",
			),

			array(
				"module_id"		=> $module_data["mod_id"],
				"lang_id"		=> $_LANG_ID,
				"item_field"	=> "message",
				"item_type"		=> "usermessage",
				"item_required"	=> "1",
				"item_size_xs"	=> "12",
				"item_title"	=> "Message",
				"item_error_msg"=> "Enter your message!",

			),
		);


		//generate default form structure
		foreach ($fields as $key => $val) {

			$val["item_id"] = $this->db->QueryInsert(
				$this->tables["plugin:contact_fields"] , 
				$val
			);

			$this->db->QueryUpdate(
				$this->tables["plugin:contact_fields"] , 
				array(
					"item_order"	=> $val["item_id"]
				),
				"item_id ={$val[item_id]}"
			);

			$this->db->QueryInsert(
				$this->tables["plugin:contact_fields_lang"] ,
				$val
			);
		}

		$this->CreatePageTitleBlock(array(
			"module_id"	=> $module_data["mod_id"],
			"title"		=> $module_data["mod_name"],
			"subtitle"	=> "You can edit this section in the Module Head tab",
			"show"		=> 1,
		));


		$widgets = array("__CONTENT__");

		if (is_object($this->plugins["comments"])) {
			$widgets[] = $this->plugins["comments"]->GetCommentsWidget();
		}
		

		$layout = $this->plugins["layouts"]->SaveLayout(
			array(
				"name"			=> $module_data["mod_name"],
				"block"			=> array(
					"col"	=> array(
						0 => array(
							"size"	=> 6 , 
							"widget"	=> $widgets
						),					
						1 => array(
							"size"	=> 1 , 
							"widget"	=> array( 
							)
						),					
						2 => array(
							"size"	=> 5 , 
							"widget"	=> array( 
								$this->plugins["widgets"]->AddWidget(array(
										"type"			=> "ccontactwidgetcontactform",
										"type_name"		=> "Contact Form",
										"title"			=> "Contact Us",
										"note"			=> "Auto-Generated",
										"settings"		=> array( 
											"set_fields"		=> "1" , 
											"set_form_style"	=> "",
											"set_button_size" => "btn-small" , 
											"set_button_style" => ""
										),

										"module"		=> $module_data["mod_id"],
								))
							),
						)
					)
				)				
			)
		);

		//update the layout id
		$this->plugins["modules"]->UpdateModuleSettings(
			$module_data["mod_id"] , 
			array(
				"set_layout"=> $layout,
			)
		);

		
	}

	function onDelete($module_data) {

		$tables  = array(
			"plugin:contact_messages" , 
			"plugin:contact_fields",
			"plugin:contact_fields_lang",
			"plugin:contact_departments",
			"plugin:contact_departments_lang",
		);

		foreach ($tables as $key => $val) {
			$this->db->Query(
				"DELETE FROM " . $this->tables[$val] . " WHERE module_id={$module_data[mod_id]}"
			);
		}

		parent::onDelete($module_data);	
	}


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

			$message = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:contact_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 mailTemplateVars($module , $operation = "list" , $template = "") {

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

			case "vars":
				return $this->MailTemplateVarsList($template , $module);
			break;
		}		
	}
	
	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function mailTemplateVarsList($template , $module) {
		//get all custom fields
		$fields = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['core:languages']} as l,
				{$this->tables['plugin:contact_fields']} as f,
				{$this->tables['plugin:contact_fields_lang']} as fl
			WHERE 
				f.module_id={$module[mod_id]} AND
				f.item_id = fl.item_id AND 
				fl.lang_id = l.lang_id AND 
				l.lang_default = 1
			ORDER BY 
				item_order ASC"
		);


		$set = array(
			"set"	=> "Form Fields",
			"fields"	=> array(),
		);
		

		if (is_array($fields)) {
			foreach ($fields as $key => $val) {
				if ($val["item_type"] != "subtitle") {
					$set["fields"][$val["item_field"]] = $val["item_title"];
				}				
			}			
		}
		
		$sets[] = $set;

		if ($template == "reply") {
			$sets[] = array(
				"set"	=> "CMS Reply",
				"fields"	=> array(
					"reply_message"		=> "Reply text from CMS"
				)
			);
		}


		return $sets;

		//debug($fields);


	}

}


?>