<?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 CContact extends CPlugin{
	
	var $tplvars; 
	var $depfields = array("email" , "fax" , "phone");

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

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

		parent::DoEvents();


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

			$this->__init();
		
			$this->tpl_module = $this->module->plugins["modules"]->LoadModuleInfo();
			$this->plugins["globalhooks"]->SetModule($this->tpl_module);

			switch ($_GET["sub"]) {
				default:					
					return $this->Landing();
				break;

				case "ajax.send":
					return $this->AjaxSendMessage();
				break;
			}
			

		}
	}


	function __init() {
		global $_CONF;

		if ($this->__inited) {
			return "";
		}

		$this->__inited = true;
		
		$path = $this->tpl_path;

		$templates = array(
			"main"						=> "main.htm",
			"form"						=> "form.htm",
			"departments"				=> "departments.htm",

			"widget.departments"		=> "widget.departments.htm",
			"widget.form"				=> "widget.form.htm",
		);

		foreach ($templates as $key => $val) {
			$this->private->templates[$key] = new CTemplateDynamic(
				$path . $val
			);
		}
	} 

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

		$text = $this->getTexts();

		$this->module->plugins["seo"]->PageMeta(
			$text
		);

		$this->module->plugins["breadcrumb"]->Add(
			array(
				"title"		=> $text["text_title"],
				"subtitle"	=> $text["text_subtitle"],
				"show"		=> $text["text_status"],

			),
			array(
				$this->tpl_module["link"]	=> $this->tpl_module["mod_name"],
			),
			$this->tpl_module["mod_protected"],
			$this->tpl_module

		);
	
	
		if ($this->plugins["comments"]) {
			$text["comments"] = $this->module->plugins["comments"]->Comments(
				$this->tpl_module["link"],
				$this->tpl_module["settings"]["set_comments"]
			);
		} else {
			$text["comments"] = "";
		}


		return $this->module->plugins["layouts"]->Render(
			$this->plugins["layouts"]->Detect(
				$this->tpl_module["settings"]["set_layout"],
				$this->tpl_module["mod_protected"]
			),
			
			$this->private->templates["main"]->blockREplacE(
				"Main" , 
				array(
					"form"			=> $this->Form($this->tpl_module),
					"title"			=> $text["text_title"] ? $this->private->templates["main"]->BlockReplace("Title" , $text ) : "",
					"departments"	=> $this->Departments(),
				),

				$this->tpl_module["settings"],
				$this->tpl_module,
				$text
			)			
		);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Form($module , $widget = false) {

		global $_LANG_ID , $_SESS , $_LANG_CODE , $base;

		$template = $this->private->templates["form"];

		if ($module["settings"]["set_fields"] == "2") {
			$cond = " AND item_required=1 ";
		}
		
		//prepare the fields
		$fields = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['plugin:contact_fields']} as f,
				{$this->tables['plugin:contact_fields_lang']} as l
			WHERE 
				f.module_id={$module[mod_id]} AND
				f.item_id = l.item_id AND 
				l.lang_id = {$_LANG_ID} {$cond}
			ORDER BY 
				item_order ASC"
		);

		if (is_array($fields)) {
			$cnt = 1;
			foreach ($fields as $key => $val) {

				$fields[$key]["field_required"] = $val["field_required"] = $val["item_required"] ? $template->blockReplace("field_required" , $val) : "";
				$fields[$key]["holder_required"] = $val["holder_required"] = $val["item_required"] ? $template->blockReplace("holder_required" , $val) : "";

				$val["value"] = $_GET[$val["item_field"]] ? $_GET[$val["item_field"]] : "";

				//prefill couple values from uyser if logged in 
				if (is_array($_SESS["client"]) && in_array($val["item_field"] , array("name" , "email" , "first_name" , "last_name"))) {

					switch ($val["item_field"]) {
						case "name":
							$val["value"] = $_SESS["client"]["user_first_name"] . " " . $_SESS["client"]["user_last_name"];
						break;

						case "first_name":
							$val["value"] = $_SESS["client"]["user_first_name"] ;
						break;

						case "last_name":
							$val["value"] = $_SESS["client"]["user_last_name"] ;
						break;

						case "email":
							$val["value"] = $_SESS["client"]["user_email"] ;
						break;

					}
					
				}
				

				switch ($val["item_type"]) {
					case "separator":
						$fields[$key]["content"] = $template->blockReplace(
							"separator",
							$val
						);
					break;

					case "departments":

						if ($widget && $module["settings"]["set_department"]) {
							$extra = $template->blockReplace(
								"department",
								$module["settings"]["set_department"]
							);

							unset($fields[$key]);
						} else {
						
							$deps = $this->db->QFetchRowArray(
								"SELECT * FROM 
									{$this->tables['plugin:contact_departments']} as r , 
									{$this->tables['plugin:contact_departments_lang']} as l
								WHERE
									r.module_id = {$module[mod_id]} AND
									r.item_id = l.item_id AND 
									item_email != '' AND
									l.lang_id = {$_LANG_ID}				

								ORDER BY item_order ASC
								"
							);

							if (is_array($deps)) {
								foreach ($deps as $k => $v) {
									$val["options"] .= "<option value='{$v[item_id]}' " . ($_GET["department"] == $v["item_id"] ? "selected" : "" ) . ">" . $v["item_name"] . "</option>";
								}

								$val["field"] = $template->blockreplace(
									$val["item_type"], 
									$val
								);

								$fields[$key]["content"] = $template->blockReplace(
									$widget ? "Full" : ucwords($val["item_size"]),
									$val
								);

							} else {
								unset($fields[$key]);
							}
						}

						
					break;

					default:				
						if ($val["item_type"] == "userdroplist") {
							$tmp = @explode("\n" , $val["item_options"]);
							foreach ($tmp as $k => $v) {
								$v = explode("|" , $v);
								if (trim($v[0])) {
									
									$val["options"] .= "<option " . ( trim($v[1]) == "1" ? "selected" : "" ) . ">" . trim($v[0]) . "</option>";
								}
							}
						}

						//size
						$val["field"] = $template->blockreplace(
							$val["item_type"], 
							$val
						);
						

						$fields[$key]["content"] = $template->blockReplace(
							$widget ? "Full" : ucwords($val["item_size"]),
							$val
						);
					break;
				}
				
			}

			if ($widget) {
				$capcha_type = $module["mod_settings"]["set_post_capcha"];
			} else {
				$capcha_type = $module["settings"]["set_post_capcha"];
			}

			
			$capcha = $this->plugins["captcha"]->GetCaptchaField($capcha_type);

			return $template->blockReplace(
				"Form", 
				array(
					"_LANG"		=> $_LANG_CODE,
					"MOD_ID"	=> $module["mod_id"],
					"fields"	=> $extra . $base->html->table(
						$template , 
						"" , 
						$fields
					),

					"script"	=> $this->plugins["modules"]->ScriptLink(
						"ajax.contact-send.php" ,
						array(
							"module_id"	=> $module["mod_id"],
							"_LANG"		=> $_LANG_CODE
						)
					),

					"capcha"	=> $capcha

				)
			);

		}
	}
	


	function AjaxSendMessage() {
		global $_CONF , $_NO_HTACCESS , $_SESS , $_LANG_ID;

		$this->__init();

		if (!is_array($this->tpl_module)) {
			return "Unknown error";
		}
		

		//prepare the fields
		$fields = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['plugin:contact_fields']} as f,
				{$this->tables['plugin:contact_fields_lang']} as l
			WHERE 
				f.module_id={$this->tpl_module[mod_id]} AND
				f.item_id = l.item_id AND 
				l.lang_id = {$_LANG_ID}
			ORDER BY 
				item_order ASC"
		);

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

				if ($val["item_type"] == "departments") {
					$_POST[$val["item_field"]] = $_POST["department"];
				}


				if ($val["item_required"] && !$_POST[$val["item_field"]]) {
					$errors[] = $val["item_error_msg"];
				}
				
			}			
		}

		if (is_array($errors)) {
			return $this->module->plugins["common"]->ErrorMsg($errors);
		}


		if (!$this->plugins["captcha"]->Validate($this->tpl_module["settings"]["set_post_capcha"])) {
			return $this->plugins["captcha"]->ErrorMSG();
		}
		

		
		$vars = $_POST;
		

		foreach ($vars as $key => $val) {
			$vars[$key] = nl2br(trim($val));
		}

		foreach ($vars as $key => $val) {
			if (!in_array($key , array("image_code"))) {
				$message .= "<b>" . ucwords(str_replace("_" , " " , $key)) . "</b>: {$val}<br>";
			}			
		}

		//save the email to database
		$id = $this->db->QueryInsert(
			$this->tables["plugin:contact_messages"],
			$contact = array(
				"module_id"		=> $this->tpl_module["mod_id"],
				"item_new"		=> 1,
				"item_date"		=> time(),
				"item_email"	=> $vars["email"],

				"item_department"	=> $vars["department"],

				//autodetect if is firstname + lastname , name or anonymous.
				"item_name"		=> ($vars["name"] ? $vars["name"] : $vars["first_name"] . " " . $vars["last_name"] ),
				"item_subject"	=> $vars["subject"],
				"item_message"	=> $message,

				"item_code"		=> md5(microtime_float()),

			)
		);



		if (
			$vars["department"] && 
			is_array(
				$department = $this->db->QFetchArray("
					SELECT * FROM 
						{$this->tables['plugin:contact_departments']} as d, 
						{$this->tables['plugin:contact_departments_lang']} as l 
					WHERE 
						d.item_id=%d AND 
						d.item_id=l.item_id AND 
						l.lang_id = %d" , 
					array(
						$vars["department"],
						$this->tpl_module["lang_id"]
					)
				)
			)
		) {

			//load the mail to client
			if (is_array($department) && $department["item_email_autoresponder"]) {
				$responder_template = $this->module->plugins["mail"]->GetMail(
					$department["item_email_autoresponder"],
					$vars
				);
			}

			
			$mail_template = $this->module->plugins["mail"]->GetMail(
				$department["item_email_template"],
				$vars
			);

			//load mail to admin
			if (is_array($department) && $department["item_email_template"]) {
				$mail_template = $this->module->plugins["mail"]->GetMail(
					$department["item_email_template"],
					$vars
				);

			}			
		}

		//load the fallback templates
		if (!is_array($mail_template)) {
			$mail_template = $this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_admin"],
				$vars
			);

			if (is_array($department) && $department["item_email"]) {
				//overwrite the "to address from template"

				$mail_template["email_to"] = $department["item_email"];
				$mail_template["email_to_name"] = ($department["item_contact_pers"] ? $department["item_contact_pers"] : $department["item_name"]);
			}
			
		}




		if (!is_array($responder_template)) {
			$responder_template = $this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_client"],
				$vars
			);
		}

				 
		//if i have an admin message then overwrite the subject and the body with the ones generated by the email template
		if (is_array($mail_template)) {
			/*
			$this->db->QueryUpdate(
				$this->tables["plugin:contact_messages"],
				array(
					"item_message" => $mail_template["email_body"],
					"item_subject"	=> $mail_template["email_subject"],

					//overwrite the name with the one from email ? is this a good ideea ?
//					"item_name"		=> $mail_template["email_from_name"],
//					"item_email"	=> $mail_template["email_from"],
				),
				"item_id={$id}"
			);*/

			$email = $this->module->plugins["mail"]->SendMail(
				$mail_template
			);			

		}
		

		if (is_array($responder_template)) {
			$email = $this->module->plugins["mail"]->SendMail(
				$responder_template
			);			
		}			

		//reset capcha
		$_SESS["XML_verify_key"] = "";

		return $this->module->plugins["common"]->SuccessMSG(
			"reset:" . $this->tpl_module["settings"]["lang_success"] . 
			$this->private->templates["form"]->blockReplace("Success")
		);

	}


	function GetAllLinks($module , &$links) {		
		$links[] = array(
			"url" => $module["link"],
		);
	}

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

		$items = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['plugin:contact_departments']} as r , 
				{$this->tables['plugin:contact_departments_lang']} as l
			WHERE
				r.module_id = {$this->tpl_module[mod_id]} AND
				r.item_id = l.item_id AND 
				r.item_show = 1 AND
				l.lang_id = {$_LANG_ID}				

			ORDER BY item_order ASC
			"
		);

		if (is_Array($items)) {

			$cnt = 0;
			$template = $this->private->templates["departments"];
			foreach ($items as $key => $val) {

				$items[$key]["set_items_size"] = $this->tpl_module["settings"]["set_size"];

				$cnt ++;	
				
				$items[$key]["extra"] = "";

				switch ($this->tpl_module["settings"]["set_size"]) {
					default: 
					case "12":
						if ($cnt == 1) {
							$cnt = 0;
							$items[$key]["extra"] = $template->blockReplace("Extra");
						}						
					break;

					case "6":
						if ($cnt == 2) {
							$cnt = 0;
							$items[$key]["extra"] = $template->blockReplace("Extra");
						}						
					break;
				}


				//process extra fieds				
				foreach ($this->dep_fields as $_k => $_v) {
					if ($val["item_" . $_v] && $template->blockExists($_v)) {
						$items[$key][$_v] = $template->blockReplace($_v , $val);
					} else {
						$items[$key][$_v] = "";
					}					
				}
			

			}
			



			return $base->html->Table(
				$template , 
				"",
				$items 
				
			);
		}
		

	}

	
	function Widget($widget) {

		$this->__init();

		switch ($widget["widget_type"]) {
			case "1":
				return $this->widgetQuickForm($widget);
			break;

			case "2":
				return $this->widgetDepartments($widget);
			break;
		}
	}


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

	function widgetDepartments($widget) {

		global $base;

		if ($widget["settings"]["set_department"]) {
			$cond = " AND r.item_id IN (" . $widget["settings"]["set_department"] . ")";
		}
		

		$items = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['plugin:contact_departments']} as r , 
				{$this->tables['plugin:contact_departments_lang']} as l
			WHERE
				r.module_id = {$widget[mod_id]} AND
				r.item_id = l.item_id AND 
				r.item_show = 1 AND
				l.lang_id = {$widget[lang_id]}				
				{$cond}

			ORDER BY item_order ASC
			"
		);

		$fields = array(
			"item_phone"			=> "phone",
			"item_fax"				=> "fax",
			"item_email"			=> "email",
			"item_address"			=> "address",
			"item_contact_pers"		=> "contact_pers",
			"item_webpage"			=> "webpage",
		);

		if (is_Array($items)) {

			$template = $this->private->templates["widget.departments"];

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

				foreach ($fields as $k => $v) {

					if ($val[$k]) {
						$items[$key][$v] = $template->blockreplace($v , $val);
					} else {
						$items[$key][$v] = "";
					}					
				}
				
			}

			if (count($items) == 1 ) {
				$items[0]["item_name"] = $widget["widget_name"];
			}
			
			


			return $template->blockReplace(
				"Main" , 
				array(
					"items"	=> $base->html->Table(
						$template , 
						"",
						$items 
					),
				),
				$widget["mod_settings"],
				$widget["settings"]
			);
		}

	}

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

		$this->__init();

		return $this->private->templates["widget.form"]->blockreplace(
			"Widget", 
			array(
				"title"	=> $widget["widget_name"],
				"form"	=> $this->Form($widget , true),
			),
			$widget,
			$widget["settings"],
			$widget["mod_settings"]
		);
	}
	

}

?>