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

	function CJobs() {
		//$this->CPlugin($db, $tables , $templates);
		$this->namd = "jobs";
	}

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

		parent::DoEvents();

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

			$this->__init();
			$this->plugins["globalhooks"]->SetModule($this->tpl_module);

			switch ($_GET["sub"]) {

				case "landing":
					return $this->Landing();
				break;

/*
				case "item":
					return $this->Item();
				break;
*/
				case "ajax.upload":
					return $this->AjaxUpload();
				break;

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

	function __init() {
		global $_CONF;

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

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

		$templates = array(
			"list"					=> "list.htm",
			"item"					=> "item.htm",
			"form"					=> "form.htm",

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

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

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



	function Widget($widget) {

		$this->__init();

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


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

		global $base;

		

		$text = $this->GetTexts();


		$this->module->plugins["seo"]->PageMeta(
			$text
		);
			
		$this->module->plugins["breadcrumb"]->Add(
			$text["text_title"],
			array(
				$this->tpl_module["link"]	=> $this->tpl_module["mod_name"]
			),
			$this->tpl_module["mod_protected"],
			$this->tpl_module
		);

		$items = $this->GetItems(array(
			"items"		=> 99999 , 
			"page"		=> $_GET["page"]
		));

		$items["records"] = $this->ProcessItems($items["records"] , $items);


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


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

		return $this->module->plugins["layouts"]->Render(
			$this->plugins["layouts"]->Detect(
				$this->tpl_module["settings"]["set_layout"],
				$this->tpl_module["mod_protected"]
			),
			$template->blockREplacE(
				"Main" , 
				array(

					"items"	=> is_array($items["records"]) ? $base->html->Table(
						$template, 
						"" , 
						$items["records"]
					) : "",


					"form"	=> $this->Form(),

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

	}

		
	

	function GetItems($params = array()) {
	
		$count	= $params["items"];
		$page	= $params["page"];

		$order		= "item_order";
		$order_mode = "ASC";

		$cond = " c.item_id=l.item_id AND l.lang_id={$this->tpl_module[lang_id]} AND c.module_id={$this->tpl_module[mod_id]} AND c.item_status = 1 ";

		$item_count = $this->db->RowCount(
			"	{$this->tables['plugin:jobs_items']} as c,
				{$this->tables['plugin:jobs_items_lang']} as l
			",
			"	WHERE {$cond}"
		);

		if (!$page && $item_count) {
			$page = 1;
		} else 
			$page = max(1,(int)$page);

		$items = $this->db->QFetchRowArray(
			"SELECT * " . 
			"FROM 
				{$this->tables['plugin:jobs_items']} as c,
				{$this->tables['plugin:jobs_items_lang']} as l
			WHERE 				
				{$cond}
			ORDER BY  {$order} {$order_mode} 
			LIMIT " . ( max(0,($page - 1 ) * $count )) . " , " . $count 
		);

		return array(
			"records"	=> $items, 
			"count"		=> $item_count , 
			"pages"		=> $item_count ? ceil($item_count / $count) : 1,
			"page"		=> $page,

			"ipp"		=> $count
		);

	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ProcessItems($items , $category) {

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


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

				if ($val["item_contact"] || $val["item_email"] || $val["item_phone"] || $val["item_fax"]) {
					$items[$key]["contact"] = $template->blockReplace(
						"Contact",
						array(
							"person"	=> $val["item_contact"] ? $template->blockREplace("person" , $val) : "",
							"email"		=> $val["item_email"] ? $template->blockREplace("email" , $val) : "",
							"phone"		=> $val["item_phone"] ? $template->blockREplace("phone" , $val) : "",
							"fax"		=> $val["item_fax"] ? $template->blockREplace("fax" , $val) : "",
							"location"	=> $val["item_location"] ? $template->blockREplace("location" , $val) : "",
						)
					);
				} else {
					$items[$key]["contact"] = "";
				}
				

				$val["link"] = $items[$key]["link"] = $this->tpl_module["link"] . $val["item_id"] . "-" . $val["item_url"] ;				
				$items[$key]["date"] = date($this->tpl_module["settings"]["set_date_item"] , $val["item_date"]);
				$items[$key]["status"] = "{LANG_STATUS_{$val[item_status]}}";
				
			}
			
		}
		

		return $items;
	}


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

		$item = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['plugin:jobs_items']} as i,
				{$this->tables['plugin:jobs_items_lang']} as il
			WHERE
				i.item_id = il.item_id AND 
				il.lang_id = {$this->tpl_module[lang_id]} AND 
				i.item_id = {$_GET[item_id]} AND 
				i.item_status < 3
			"
		);

		if (!is_array($item)) {
			return $this->module->plugins["redirects"]->ErrorPage("404" , true);
		}

		$this->module->plugins["modules"]->SetSeo(
			$item
		);

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

		//process extra fields
		$fields = array(
			"item_person"	=> "contact",
			"item_fax"		=> "fax",
			"item_phone"	=> "phone",
			"item_email"	=> "email",
		);

		$item["status"] = "{LANG_STATUS_{$item[item_status]}}";

		foreach ($fields as $key => $val) {
			if ($item[$key]) {
				$item[$val] = $template->blockReplace($val , $item);
			} else {
				$item[$val] = "";
			}			
		}
		

		$this->module->plugins["breadcrumb"]->Add(
			$item["item_title"],
			array(
				$this->tpl_module["link"]	=> $this->tpl_module["mod_name"],
				$this->tpl_module["link"] . "{$item[item_id]}-{$item[item_url]}"	=> $item["item_title"],
			)
		);


		$item["link"] = $this->tpl_module["link"] . $item["item_id"] . "-" . $item["item_url"];
		$item["date"] = date($this->tpl_module["settings"]["set_date_item"] , $item["item_date"]);


		$item["next_link"] = $this->ItemLink($item , "next");
		$item["back_link"] = $this->ItemLink($item , "back");


		$item["form"] = $this->Form($item);

		return $this->module->plugins["layouts"]->Render(
			$this->plugins["layouts"]->Detect(
				$this->tpl_module["settings"]["set_layout_item"],
				$this->tpl_module["mod_protected"]
			),
			CTemplateStatic::Replace(
				$template->blockREplacE(
					"Main" , 
					$item
				),
				$this->tpl_module["settings"]
			),
			$this->tpl_module["settings"]["set_widgets"]
		);	
	}

	
	function ItemLink($parent , $type) {

		switch ($type) {
			case "next":

				$item = $this->db->QFetchArray(
					"SELECT * FROM 
						{$this->tables['plugin:jobs_items']} as i,
						{$this->tables['plugin:jobs_items_lang']} as il
					WHERE
						i.item_id = il.item_id AND 
						il.lang_id = {$this->tpl_module[lang_id]} AND
						i.item_id > {$parent[item_id]} AND 
						i.item_status < 3 
					ORDER BY 
						i.item_date ASC 
					LIMIT 1
					"
				);

				if (!is_array($item)) {			
					return $this->tpl_module["link"] ;
				} else {
					return $this->tpl_module["link"] . $item["item_id"] . "-" . $item["item_url"] ;
				}				
			break;

			case "back":

				$item = $this->db->QFetchArray(
					"SELECT * FROM 
						{$this->tables['plugin:jobs_items']} as i,
						{$this->tables['plugin:jobs_items_lang']} as il
					WHERE
						i.item_id = il.item_id AND 
						il.lang_id = {$this->tpl_module[lang_id]} AND
						i.item_id < {$parent[item_id]} AND 
						i.item_status < 3 

					ORDER BY 
						i.item_date DESC
					LIMIT 1
					"
				);

				if (!is_array($item)) {			
					return $this->tpl_module["link"] ;
				} else {
					return $this->tpl_module["link"] . $item["item_id"] . "-" . $item["item_url"] ;
				}				

			break;
		}
		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Form($job = null) {

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

		$template = $this->private->templates["form"];
		$module = &$this->tpl_module;
		
		//prepare the fields
		$fields = $this->db->QFetchRowArray(
			"SELECT * FROM 
				{$this->tables['plugin:jobs_fields']} as f,
				{$this->tables['plugin:jobs_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) : "";

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

					case "userjobs":

						$jobs = $this->GetItems(array(
							"items"		=> 99999 , 
							"page"		=> $_GET["page"]
						));

						if (is_array($jobs["records"])) {
							foreach ($jobs["records"] as $_key => $_val) {
								$val["options"] .= "<option value=\"{$_val[item_id]}\">{$_val[item_title]}</option>";
							}							
						}

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

						$fields[$key]["content"] = $template->blockReplace(
							$widget ? "Full" : ucwords($val["item_size"]),
							$val
						);
						
					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;
				}
				
			}


			$capcha = $this->plugins["captcha"]->GetCaptchaField($module["settings"]["set_post_capcha"]);

			return CTemplateStatic::Replace(
				$template->blockReplace(
					"Form", 
					array(
						"script"	=> $this->plugins["modules"]->ScriptLink("ajax.jobs-send.php" , array("module_id" => $module["mod_id"] )),
						"JOB_ID"	=> $job["item_id"],
						"fields"	=> $base->html->table(
							$template , 
							"" , 
							$fields
						),

						"upload"	=> $module["settings"]["set_uploader"] ? $template->blockReplace("Upload" , $module["settings"]): "",

						"capcha"	=> $capcha

					)
				),
				array(
					"token"		=> md5($_SERVER["REMOTE_ADDR"]),
					"MOD_ID"	=> $module["mod_id"],

				)
			);

		}
	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxUpload() {
		global $_CONF;

		$this->__init();

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

		$types = $this->tpl_module["settings"]["set_uploader_extensions"];

		if (!$types) {
			return "Please configure the allowed extensions!";
		}

		$types = explode("," , $types);

		if (count($types)) {
			foreach ($types as $key => $val) {
				$fileTypes[] = trim($val);
			}			
		}
		
		$verifyToken = md5($_SERVER["REMOTE_ADDR"]);

		if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
				$tempFile   = $_FILES['Filedata']['tmp_name'];
				$uploadDir  = $_CONF["upload"] . "tmp/";
				$targetFile = $uploadDir . $_POST["token"] . "_" . $_FILES['Filedata']['name'];

				// Validate the filetype
				$fileParts = pathinfo($_FILES['Filedata']['name']);
		
				if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
					// Save the file
					move_uploaded_file($tempFile, $targetFile);
					return 1;
			} else {

					return 'Invalid file type.';

			}
		}
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxSend() {
		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:jobs_fields']} as f,
				{$this->tables['plugin:jobs_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_required"] && !$_POST[$val["item_field"]]) {
					return $this->module->plugins["common"]->ErrorMSG(
						$val["item_error_msg"]
					);
				}
			}			
		}


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

		
		$vars = $_POST;



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

		if (!$vars["message"]) {
			$vars["message"] = $message;
		}
		
		


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

				"item_job"		=> $_POST["job"],
				"item_message"	=> $message,

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

			)
		);


		if ((int)$_POST["job"]) {
			$job = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['plugin:jobs_items']} as i,
					{$this->tables['plugin:jobs_items_lang']} as il
				WHERE
					i.item_id = il.item_id AND 
					il.lang_id = {$this->tpl_module[lang_id]} AND 
					i.item_id = {$_POST[job]}
				"
			);

		}
		
		if ($vars["ff"]) {
			$file = $_CONF["upload"] . "tmp/" . $_POST["token"] . "_" . $_POST["ff"];

			if (file_exists($file)) {
				rename (
					$file , 
					$_CONF["upload"] . "jobs/files/" . $id . ".file"
				);

				//update the file
				$this->db->QueryUpdate(
					$this->tables["plugin:jobs_resumes"],
					array(
						"item_file"			=> "1",
						"item_file_file"	=> $_POST["ff"],
					),
					"item_id={$id}"
				);
			}


			if ($this->tpl_module["settings"]["set_attach"] == "1") {
				$attach[$_POST["ff"]] = $_CONF["upload"] . "jobs/files/" . $id . ".file";
			}
			
			
		}
		

		$mail_template = $this->module->plugins["mail"]->GetMail(
			$this->tpl_module["settings"]["set_mail_admin"],
			array_merge(
				$vars,
				(array)$job
			)
		);

		$mail_template["attachments"] = $attach;

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

		}
		
		//check if it is an anonymouse message and do nothing if that is the case
		if ($this->tpl_module["settings"]["set_anonymous"]) {

		} else {		

			$responder_template = $this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_client"],
				array_merge(
					$vars,
					(array)$job
				)
			);

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

		//clear captcha
		$_SESS["XML_verify_key"] = "";

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

	}
	


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

}

?>