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

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CContact extends CPlugin{
	
	var $tplvars; 
	var $depfields = array("email" , "fax" , "phone");

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

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

		parent::DoEvents();


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

			$this->__init();

			$this->plugins["seo"]->Canonical($this->tpl_module["link"]);		
			$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",
		);

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

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

	} 

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

		$text = $this->pageTitleBlock();

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

		$this->SetComments($this->tpl_module["settings"]["set_comments"] , array("link" => $this->tpl_module["link"]));

		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;
			$sizes = array("small"	=> "6" , "big"	=> "9" , "full" => 12);
			$types = array(
				"departments"	=> "select",
				"userdroplist"	=> "select",
				"userradio"		=> "radiolist",
				"usercheck"		=> "checklist",
				"usertext"		=> "textbox",
				"useremail"		=> "textbox",
				"usermessage"	=> "textarea",
				"calendar"		=> "calendar",
				"calendartime"	=> "calendar",
				"time"			=> "calendar",
				"subtitle"		=> "title",
			);

			foreach ($fields as $key => $val) {
				$field = array(
					"icon"		=> $val["item_icon"],
					"type"		=> $types[$val["item_type"]],
					"title"		=> $val["item_title"],
					"name"		=> $val["item_field"],
					"required"	=> $val["item_required"],
					"default"	=> $_GET[$val["item_field"]],
					"size"		=> array(
						"xl"		=> $val["item_size"],
						"lg"		=> $val["item_size_lg"],
						"md"		=> $val["item_size_md"],
						"sm"		=> $val["item_size_sm"],
						"xs"		=> $val["item_size_xs"],
					)
				);

				//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")) && !$field["default"]) {
					switch ($val["item_field"]) {
						case "name":		$field["default"] = $_SESS["client"]["user_first_name"] . " " . $_SESS["client"]["user_last_name"]; break;
						case "first_name":	$field["default"] = $_SESS["client"]["user_first_name"]; break;
						case "last_name":	$field["default"] = $_SESS["client"]["user_last_name"];	break;
						case "email":		$field["default"] = $_SESS["client"]["user_email"];	break;
					}					
				}
				

				switch ($val["item_type"]) {
					case "calendar":
						$field["calendar"]	= array("type" => "date");
					break;

					case "calendartime":
						$field["calendar"]	= array("type" => "full");
					break;

					case "time":
						$field["calendar"]	= array("type" => "time");
					break;

					case "departments":
						$field["name"] = "department";

						if ($widget && $module["settings"]["set_department"]) {
							$field["type"] = "hidden";
							$field["default"] = $module["settings"]["set_department"];
						} 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) {
									$field["options"][$v["item_id"]] = $v["item_name"];
								}

							} else {
								$field = null;
							}
						}						
					break;

					case "userradio":
					case "usercheck":
					case "userdroplist":
							$tmp = @explode("\n" , $val["item_options"]);
							foreach ($tmp as $k => $v) {
								$v = explode("|" , $v);
								$v[0] = trim($v[0]);

								if ($v[0]) {									
									$field["options"][$v[0]] = $v[0];

									if ($v[1] == "1") {
										$field["default"] = $v[0];
									}
								}
							}

							if ($val["item_radio_new"]) {
								$field[$field["type"]] = array("newline" => true);							
							}
							
					break;
				}		
				

				if (is_array($field)) {
					$_fields[] = $field;
				}
				
			}
					
			return $template->blockReplace(
				"Form", 
				array(
					"form"	=> 	formBuilder::newInstance()
						-> setFields($_fields)
						-> setCaptcha(array(
							"type"	=> $module[$widget ? "mod_settings" : "settings"]["set_post_capcha"] ,
							"name"	=> "contact",
						))
						-> buildFields(),

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

		}
	}
	


	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"
		);


		$response = CFormError::newInstance()
			->SetErrorStyle($this->tpl_module["settings"]["set_form_validate"])
			->SetSuccessStyle($this->tpl_module["settings"]["set_form_success"])
			->SetSuccessRedirect($this->plugins["modules"]->BuildLink(array(
					"type"	=> $this->tpl_module["settings"]["set_form_link_type"],
					"link"	=> $this->tpl_module["settings"]["set_form_link_link"],
					"module"=> $this->tpl_module["settings"]["set_form_link_module"],
					"global"=> $this->tpl_module["settings"]["set_form_link_global"]
			)))
			->SetPopupBtn($this->tpl_module["settings"]["lang_popup_close"])
			->SetPopupBg($this->tpl_module["settings"]["set_form_popup_bg"]);


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

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

				switch ($val["item_type"]) {
					case "useremail":
						if ($val["item_required"] && !Validate::Email($_POST[$val["item_field"]])) {
							$response->AddField($val["item_field"] , $val["item_error_msg"]);
						} else {
							if (!$this->plugins["antispam"]->ValidateEmail($this->tpl_module , $_POST[$val["item_field"]])) {
								$response->AddField($val["item_field"] , $this->plugins["antispam"]->EmailError());
							}							
						}
					break;

					case "usercheck":
						if ($val["item_required"] && !is_array($_POST[$val["item_field"]])) {
							$response->AddField($val["item_field"] , $val["item_error_msg"]);
						} else {
							$_POST[$val["item_field"]] = implode(", " , $_POST[$val["item_field"]]);
						}
					break;

					default:
						if ($val["item_required"] && !$_POST[$val["item_field"]]) {
							$response->AddField($val["item_field"] , $val["item_error_msg"]);
						}
					break;
				}
				


				
			}			
		}

		if (!$this->plugins["antispam"]->ValidateClient($this->tpl_module)) {
			$response->AddField("__global" , $this->plugins["antispam"]->ClientError());
		}

		if (!$this->plugins["antispam"]->ValidateCaptcha($this->tpl_module["settings"]["set_post_capcha"] , "contact")) {
			$response->AddField("image_code" , $this->plugins["antispam"]->CaptchaError());
		}

		if ($response->HasErrors()) {
			return $response->GetJson();
		}
		
		$vars = $_POST;
		

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

		foreach ($vars as $key => $val) {
			if (!in_array($key , array("image_code" , "department" , "departments"))) {
				$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()),

				"item_vars"		=> serialize($vars),



				"log_ip"			=> $_SERVER["REMOTE_ADDR"],
				"log_domain"		=> $_SERVER["REMOTE_HOST"],
				"log_agent"			=> $_SERVER["HTTP_USER_AGENT"],


			)
		);


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


		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

		//validate the spam
		$isSpam = $this->plugins["antispam"]->isSpam(
			$this->tpl_module,
			array(
				"type"		=> "message",
				"author"	=> $contact["item_name"],
				"email"		=> $contact["item_email"],
				"message"	=> $contact["item_message"],
			)
		);


		if (!$isSpam) {

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

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

			//mark as spam
			$this->db->QueryUpdateById(
				$this->tables["plugin:contact_messages"],
				array(
					"item_spam"	=> 1,
				),
				$id
			);

		}
		
		return $response->SetReset()
			->SetSuccess($this->tpl_module["settings"]["lang_success"])
			->GetJson();
	}

		
	/**
	* 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 
				
			);
		}
		

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SitemapGetMaps($module , $lang) {

		if ($module["mod_id"]) {
			return array($module["mod_id"] => true);
		} else {
			return array($module["module_code"] => true);
		}
		
	}

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

}
