<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjLoad extends pjFront
{
	private $isoDatePattern = '/\d{4}-\d{2}-\d{2}/';
	
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 'false';
				exit;
			}
			$pjClientModel = pjClientModel::factory()->where('t1.email', $_GET['email']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjClientModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjClientModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionProfile()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$current_client = $_SESSION[$this->defaultClient];
			
			if(isset($_POST['update_profile']))
			{
				$error_messages = __('front_profile', true);
				
				$_POST = pjSanitize::clean($_POST, array('remove_html' => true));
				if($_POST['password'] == 'password')
				{
					unset($_POST['password']);
				}
				pjClientModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjClient');
				}
				pjAppController::jsonResponse(array('status' => 'OK', 'text' => $error_messages['FP01'], 'code' => 200));
			}else{
				$arr = pjClientModel::factory()->find($current_client['id'])->getData();
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjClient');
				$this->set('arr', $arr);
				
				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')->findAll()->getData();
				
				$lp_arr = array();
				foreach ($locale_arr as $item)
				{
					$lp_arr[$item['id']."_"] = $item['file'];
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
				
				$this->set('country_arr', pjCountryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData()
				);

				$cnt_tickets = pjTicketModel::factory()->where("client_id" , $current_client['id'])->findCount()->getData();
				$this->set('cnt_tickets', $cnt_tickets);
			}
		}
	}
	public function pjActionRegister()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_POST['register']))
			{
				$error_messages = __('front_register', true);
	
				$data = array();
				$code = 200;
				if($this->option_arr['o_confirm_account'] == 'auto')
				{
					$data['status'] = 'T';
				}else{
					$data['status'] = 'F';
					$code = 201;
				}
				$data['client_since'] = date('Y-m-d H:i:s');
				
				$_POST = pjSanitize::clean($_POST, array('remove_html' => true));
				
				$id = pjClientModel::factory()->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$this->sendNewClientEmail($id, $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);
				} else {
					$code = 100;
				}
				pjAppController::jsonResponse(array('text' => $error_messages[$code], 'code' => $code));
			}else{
				
				$this->set('country_arr', pjCountryModel::factory()->select('t1.*, t2.content AS name')
						->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
						->where('status', 'T')->orderBy('name ASC')->findAll()->getData()
				);

			}
		}
	}
	public function pjActionContact()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$error_messages = __('front_sys', true);
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => str_replace("{SIZE}", ini_get('post_max_size'), $error_messages['file_size']), 'code' => 105));
			}
				
			if($this->option_arr['o_post_ticket'] == 'registered_clients')
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100));
			}
			
			if(isset($_POST['contact']))
			{
				$post_messages = __('front_contact', true);
				
				if (!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['message']) ||
					!pjValidation::pjActionNotEmpty($_POST['name']) ||
					!pjValidation::pjActionNotEmpty($_POST['email']) ||
					!pjValidation::pjActionEmail($_POST['email']) ||
					!pjValidation::pjActionNotEmpty($_POST['message']))
				{
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $post_messages['data_inv'], 'code' => 101));
				}
				
				if (isset($_FILES['files']) && !empty($_FILES['files']['tmp_name']))
				{
					$files = pjUtil::getArrayOfFiles($_FILES['files']);
					foreach ($files as $file) {
						if($file['error'] === UPLOAD_ERR_INI_SIZE){
							$_SESSION[$this->previousPost] = $_POST;
							pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $post_messages['max_size'], 'code' => 102));
						}
					}
				}
				
				$pjClientModel = pjClientModel::factory();
				
				$data = array();
				$data['ticket_id'] =  pjUtil::getRandomChars() .  pjUtil::getRandomDigits();
				$data['ip'] = $_SERVER['REMOTE_ADDR'];
				$data['created'] = date('Y-m-d H:i:s');
				if(!isset($_POST['department_id'])){
					$data['department_id'] = ':NULL';
				}
				$email = $_POST['email'];
				$client_arr = $pjClientModel->where("t1.email", $email)->findAll()->getData();
				
				if(count($client_arr) > 0)
				{
					$data['client_id'] = $client_arr[0]['id'];
				}else{
					$client_data = array();
					$client_data['name'] = $_POST['name'];
					$client_data['email'] = $email;
					$client_data['password'] = pjToolkit::getRandomPassword();
					if($this->option_arr['o_confirm_account'] == 'auto')
					{
						$client_data['status'] = 'T';
					}else{
						$client_data['status'] = 'F';
					}
					$data['client_id'] = $pjClientModel->reset()->setAttributes($client_data)->insert()->getInsertId();
					if(pjValidation::pjActionEmail($email) == true)
					{
						$this->sendNewClientEmail($data['client_id'], $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);
					}
				}
				
				$id = pjTicketModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					if (isset($files))
					{
						$pjFileModel = pjFileModel::factory();
						foreach ($files as $file) {
							$data = array();
							$data['ticket_id'] = $id;
							$handle = new pjUpload();
							
							if ($handle->load($file)) {
								$hash = md5(uniqid(rand(), true));
								$file_ext = $handle->getExtension();
								$file_path = PJ_UPLOAD_PATH . 'files/tickets/' . $id . "_" . $hash . '.' . $file_ext;
								if($handle->save(PJ_INSTALL_PATH . $file_path))
								{
									$data['file_path'] = $file_path;
									$data['file_name'] = $file['name'];
									$data['mime_type'] = $file['type'];
									$data['hash'] = $hash;
									$data['type'] = 'ticket';
									
									$pjFileModel->reset()->setAttributes($data)->insert();
								}
							}
						}
						
					}
					
					$this->sendEmail($id, 'NewTicket', null, $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);	
					
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjTicket');
					}
					pjAppController::jsonResponse(array('status' => 'OK', 'text' => $post_messages['FC01'], 'code' => 200));
				} else {
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $post_messages['FC02'], 'code' => 103));
				}
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjLoad&action=pjActionContact&err=' . $err . (isset($_POST['iframe']) ? '&iframe' : NULL));
			}else{
				if(isset($_SESSION[$this->previousPost]))
				{
					$this->set('previousPost', $_SESSION[$this->previousPost]);
					unset($_SESSION[$this->previousPost]);
				}
				$department_arr = pjDepartmentModel::factory()->select('t1.*, t2.content AS name')
							->join('pjMultiLang', "t2.model='pjDepartment' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
							->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('department_arr', pjSanitize::clean($department_arr, array('remove_html' => true)));
				
			}
		}
	}
	
	public function pjActionLogin()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			if(isset($_POST['login']))
			{
				$error_messages = __('front_sys', true);
				
				if (!isset($_POST['login_email']) || !isset($_POST['login_password']) ||
					!pjValidation::pjActionNotEmpty($_POST['login_email']) ||
					!pjValidation::pjActionNotEmpty($_POST['login_password']) ||
					!pjValidation::pjActionEmail($_POST['login_email']))
				{
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['data_inv'], 'code' => 100));
				}
				
				$client = pjClientModel::factory()
					->where('t1.email', $_POST['login_email'])
					->where('t1.password', $_POST['login_password'])
					->limit(1)
					->findAll()
					->getData();
				
				if (count($client) != 1)
				{
					# Login failed
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['log_err1'], 'code' => 101));
				}else{
					$client = $client[0];
					
					if ($client['status'] == 'F')
					{
						# Login denied
						pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['log_err2'], 'code' => 102));
					}
					if(isset($_POST['login_remember_me']))
					{
						$key_var = md5(implode('', array($client['id'], $client['email'], $client['password'], PJ_SALT)));
						setcookie($this->userKey, $key_var, time()+60*60*24*30, '/');
					}
					unset($client['password']);
					$_SESSION[$this->defaultClient] = $client;
					
					$data = array();
					$data['last_login'] = date("Y-m-d H:i:s");
					pjClientModel::factory()->setAttributes(array('id' => $client['id']))->modify($data);
					
					pjAppController::jsonResponse(array('status' => 'OK', 'text' => '', 'code' => 200));
				}
			}else{
				if(isset($_COOKIE[$this->userKey]))
				{
					$key_var = $_COOKIE[$this->userKey];
					$client = array();
					$client_arr = pjClientModel::factory()
							 ->select("t1.*, MD5(CONCAT(t1.id, t1.email, t1.password, '".PJ_SALT."')) AS `key_var`")
							 ->having("key_var = '".$key_var."'", false)
						     ->offset(0)->limit(1)
						     ->findAll()->getData();
					if(count($client_arr) > 0)
					{
						$client = $client_arr[0];
						$key_var = md5(implode('', array($client['id'], $client['email'], $client['password'], PJ_SALT)));
						setcookie($this->userKey, $key_var, time()+60*60*24*30, '/');
					}
				}
			}
		}
	}
	
	public function pjActionIndex()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$current_client = $_SESSION[$this->defaultClient];
				
			$tbl_reply = pjReplyModel::factory()->getTable();
			
			$pjTicketModel = pjTicketModel::factory();
			if (isset($_GET['keyword']) && !empty($_GET['keyword']))
			{
				$q = pjObject::escapeString($_GET['keyword']);
				$pjTicketModel->where("( t1.message LIKE '%$q%' OR (t1.id IN(SELECT `TR`.`ticket_id` FROM `".pjReplyModel::factory()->getTable()."` AS `TR` WHERE `TR`.`reply_text` LIKE '%$q%')) )");
			}
			$ticket_arr =  $pjTicketModel
				->select('t1.*,
						(SELECT COUNT(t2.id) FROM `' . $tbl_reply . '` as t2 WHERE t2.ticket_id = t1.id ) AS cnt_replies,
						(SELECT t2.created FROM `' . $tbl_reply . '` as t2 WHERE t2.ticket_id = t1.id ORDER BY t2.created DESC LIMIT 1) AS last_reply')
				->where("t1.client_id", $current_client['id'])
				->orderBy("created DESC")
				->findAll()
				->getData();
				
			$this->set('ticket_arr', $ticket_arr);
		}
	}
	
	public function pjActionAddTicket()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$current_client = $_SESSION[$this->defaultClient];
			
			$error_messages = __('front_sys', true);
			
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => str_replace("{SIZE}", ini_get('post_max_size'), $error_messages['file_size']), 'code' => 105));
			}
			
			if(isset($_POST['add_ticket']))
			{	
				$post_messages = __('front_contact', true);
				$ticket_messages = __('front_tickets', true);
				
				if (!isset($_POST['message']) || !pjValidation::pjActionNotEmpty($_POST['message']))
				{
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['data_inv'], 'code' => 100));
				}
				
				$client_arr = pjClientModel::factory()->find($current_client['id'])->getData();
				if(empty($client_arr))
				{
					unset($_SESSION[$this->defaultClient]);
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $post_messages['FC03'], 'code' => 101));
				}else{
					if($client_arr['status'] == 'F')
					{
						unset($_SESSION[$this->defaultClient]);
						pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $post_messages['FC03'], 'code' => 102));
					}
				}
				
				if (isset($_FILES['files']) && !empty($_FILES['files']['tmp_name']))
				{
					$files = pjUtil::getArrayOfFiles($_FILES['files']);
					
					foreach ($files as $file) {
						if($file['error'] === UPLOAD_ERR_INI_SIZE)
						{
							$_SESSION[$this->previousPost] = $_POST;
							$message = str_replace('{maxsize}', ini_get('post_max_size'), $error_messages['max_size']);
							pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $message, 'code' => 103));
						}
					}
				}
				
				$data = array();
				$data['ticket_id'] =  pjUtil::getRandomChars() .  pjUtil::getRandomDigits();
				$data['ip'] = $_SERVER['REMOTE_ADDR'];
				$data['created'] = date('Y-m-d H:i:s');
				$data['client_id'] = $current_client['id'];
				if(!isset($_POST['department_id'])){
					$data['department_id'] = ':NULL';
				}
				$pjTicketModel  = pjTicketModel::factory();
				
				$id = $pjTicketModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					if (isset($files))
					{
						$pjFileModel = pjFileModel::factory();
						foreach ($files as $file) {
							$data = array();
							$data['ticket_id'] = $id;
							$handle = new pjUpload();
							
							if ($handle->load($file)) {
								$hash = md5(uniqid(rand(), true));
								$file_ext = $handle->getExtension();
								$file_path = PJ_UPLOAD_PATH . 'files/tickets/' . $id . "_" . $hash . '.' . $file_ext;
								if($handle->save(PJ_INSTALL_PATH . $file_path))
								{
									$data['file_path'] = $file_path;
									$data['file_name'] = $file['name'];
									$data['mime_type'] = $file['type'];
									$data['hash'] = $hash;
									$data['type'] = 'ticket';
									
									$pjFileModel->reset()->setAttributes($data)->insert();
								}
							}
						}
					}
					$this->sendEmail($id, 'NewTicket', null, $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);		
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjTicket');
					}
					pjAppController::jsonResponse(array('status' => 'OK', 'text' => $ticket_messages['FA01'], 'code' => 200));
				}else{
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $ticket_messages['FA02'], 'code' => 104));
				}
			}else{
				if(isset($_SESSION[$this->previousPost]))
				{
					$this->set('previousPost', $_SESSION[$this->previousPost]);
					unset($_SESSION[$this->previousPost]);
				}
				$department_arr = pjDepartmentModel::factory()
						->select('t1.*, t2.content AS name')
						->join('pjMultiLang', "t2.model='pjDepartment' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
						->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('department_arr', pjSanitize::clean($department_arr, array('remove_html' => true)));
			}
		}
	}
	
	public function pjActionTicketDetail()
	{
		$this->setAjax(true);
		
		if($this->isXHR())
		{
			$current_client = $_SESSION[$this->defaultClient];
			
			$pjReplyModel = pjReplyModel::factory();
			$pjFileModel = pjFileModel::factory();
			$pjTicketModel = pjTicketModel::factory();
			
			$ticket_id = $_GET['id'];
			
			$arr = $pjTicketModel
				->select('t1.*, t2.name as client_name')
				->join('pjClient', 't2.id=t1.client_id', 'left')
				->find($_GET['id'])->getData();
			
			if($current_client['id'] == $arr['client_id'])
			{
				if(!empty($arr))
				{
					$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjTicket');
								
					$ticket_file_arr = $pjFileModel->where("ticket_id", $ticket_id)->where("`type`" ,'ticket')->findAll()->getData();
					
					$total = $pjReplyModel->where("ticket_id", $ticket_id)->findCount()->getData();
					
					$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 5;
					$pages = ceil($total / $rowCount);
					$page = isset($_GET['pjPage']) && (int) $_GET['pjPage'] > 0 ? intval($_GET['pjPage']) : ($pages == 0 ? 1 : $pages);
					$offset = ((int) $page - 1) * $rowCount;
					if ($page > $pages)
					{
						$page = $pages;
					}
					
					$reply_arr = $pjReplyModel
						->select("t1.*, t2.name as user_name, t3.name as client_name")
						->join('pjUser', 't2.id=t1.user_id', 'left')
						->join('pjClient', 't3.id=t1.client_id', 'left')
						->where("ticket_id", $ticket_id)
						->orderBy("t1.created ASC")
						->limit($rowCount, $offset)
						->findAll()
						->getData();
		
					$temp_arr = $pjFileModel
						->reset()
						->select('t1.*')
						->join('pjReply',"t2.id = t1.reply_id AND t1.`type` = 'reply'", 'left')
						->where("t1.ticket_id", $_GET['id'])
						->where("`type`", 'reply')
						->findAll()
						->getData();
					
					$reply_file_arr = array();
					foreach($temp_arr as $v)
					{
						$reply_file_arr[$v['reply_id']][] = $v;
					}
					
					$this->set('arr', $arr);
					$this->set('ticket_file_arr', $ticket_file_arr);
					$this->set('reply_arr', $reply_arr);
					$this->set('reply_file_arr', $reply_file_arr);
					$this->set('paginator', array('pages' => $pages, 'total' => $total));
				}
			}				
		}
	}
	
	public function pjActionPostReply()
	{
		$this->setAjax(true);
		
		if($this->isXHR())
		{
			$this->checkLogin();
			
			$error_messages = __('front_sys', true);
			$post_messages = __('front_post_reply', true);
			
			$ticket_id = $_POST['ticket_id'];
			if (!isset($_POST['reply_text']) || !pjValidation::pjActionNotEmpty($_POST['reply_text']))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['data_inv'], 'code' => 100));
			}
			
			$current_client = $_SESSION[$this->defaultClient];
			$client_arr = pjClientModel::factory()->find($current_client['id'])->getData();
			if(empty($client_arr))
			{
				unset($_SESSION[$this->defaultClient]);
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['FC03'], 'code' => 101));
			}else{
				if($client_arr['status'] == 'F')
				{
					unset($_SESSION[$this->defaultClient]);
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['FC03'], 'code' => 102));
				}
			}
			
			$ticket_arr = pjTicketModel::factory()->find($ticket_id)->getData();
			
			if(empty($ticket_arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['noticket'], 'code' => 103));
			}
			
			$pjReplyModel = pjReplyModel::factory();
			
			$reply_id = $pjReplyModel->setAttributes($_POST)->insert()->getInsertId();
			
			if ($reply_id !== false && (int) $reply_id > 0)
			{
				if (isset($_FILES['files']) && !empty($_FILES['files']['tmp_name']))
				{
					
					$files = array();
					foreach ($_FILES['files'] as $k => $l) {
						foreach ($l as $i => $v) {
					 		if (!array_key_exists($i, $files))
					 		{
					   			$files[$i] = array();
					 		}
					   		$files[$i][$k] = $v;
					 	}
					}
					$pjFileModel = pjFileModel::factory();
					foreach ($files as $file) {
						$data = array();
						$data['ticket_id'] = $ticket_id;
						$data['reply_id'] = $reply_id;
						$handle = new pjUpload();
						
						if ($handle->load($file)) {
							$hash = md5(uniqid(rand(), true));
							$file_ext = $handle->getExtension();
							$file_path = PJ_UPLOAD_PATH . 'files/replies/' . $reply_id . "_" . $hash . '.' . $file_ext;
							if($handle->save(PJ_INSTALL_PATH . $file_path))
							{
								$data['file_path'] = $file_path;
								$data['file_name'] = $file['name'];
								$data['mime_type'] = $file['type'];
								$data['hash'] = $hash;
								$data['type'] = 'reply';
								
								$pjFileModel->reset()->setAttributes($data)->insert();
							}
						}
					}
					
				}
				
				$pjTicketModel = pjTicketModel::factory();
				$pjClientModel = pjClientModel::factory();
				$pjUserModel = pjUserModel::factory();
				
				$data = array();
				$data['status'] = 'RepliedByClient';
				$pjTicketModel->where('id', $ticket_id)->limit(1)->modifyAll($data);
				
				$reply_arr = $pjReplyModel->reset()->find($reply_id)->getData();
				
				$this->sendEmail($ticket_id, 'NewClientReply', $reply_arr, $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);
				
				pjAppController::jsonResponse(array('status' => 'OK', 'text' => $post_messages['FR01'], 'code' => 200));
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $post_messages['FR01'], 'code' => 104));
			}
		}
	}
	
	public function pjActionForgotPassword()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			if(isset($_POST['forgot_password']))
			{
				$error_messages = __('front_forgot', true);
				if (!isset($_POST['email']) ||
					!pjValidation::pjActionNotEmpty($_POST['email']) ||
					!pjValidation::pjActionEmail($_POST['email']))
				{					
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['data_inv'], 'code' => 100));
				}
				
				$pjClientModel = pjClientModel::factory();
				$client = $pjClientModel
					->where('t1.email', $_POST['email'])
					->limit(1)
					->findAll()
					->getData();
				if(count($client) > 0)
				{
					$client = $client[0];
					if($client['status'] == 'F')
					{
						pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['FF02'], 'code' => 101));
					}else{
						$Email = new pjEmail();
						
						if(pjValidation::pjActionEmail($_POST['email']) == true)
						{
							$to = $_POST['email'];
							$subject = __('emailForgotSubject', true);
							$from = $this->getAdminEmail();
							$message = str_replace(
								array('{Name}', '{Password}'),
								array($client['name'], $client['password']),
								__('emailForgotBody', true)
							);
							
							if ($this->option_arr['o_send_email'] == 'smtp')
							{
								$Email->setTransport('smtp')
										->setSmtpHost($this->option_arr['o_smtp_host'])
										->setSmtpPort($this->option_arr['o_smtp_port'])
										->setSmtpUser($this->option_arr['o_smtp_user'])
										->setSmtpPass($this->option_arr['o_smtp_pass'])
										->setSender($this->option_arr['o_smtp_user']);
							}
							
							$Email->setContentType('text/html');
							$Email->setTo($to);
							$Email->setFrom($from);
							$Email->setSubject($subject);
							$Email->send($message);
						}
						pjAppController::jsonResponse(array('status' => 'OK', 'text' => $error_messages['FF03'], 'code' => 200));
					}
				}else{
					pjAppController::jsonResponse(array('status' => 'ERR', 'text' => $error_messages['FF01'], 'code' => 102));
				}
			}
		}
	}
	
	public function pjActionLogout()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			unset($_SESSION[$this->defaultClient]);
			setcookie($this->userKey, NULL, 0, '/');
			if($this->option_arr['o_post_ticket'] == 'registered_clients'){
				pjAppController::jsonResponse(array('hash' => 'Login'));
			}else{
				pjAppController::jsonResponse(array('hash' => 'Contact'));
			}
		}
	}
	
	public function pjActionRate()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			$this->checkLogin();
				
			if(isset($_GET['reply_id']) && (int) $_GET['reply_id'] > 0 && isset($_GET['rate']) && (int) $_GET['rate'] > 0)
			{
				$pjReplyModel = pjReplyModel::factory();
				$pjReplyModel->where('id', $_GET['reply_id'])->limit(1)->modifyAll(array('rate' => $_GET['rate'], 'rate_dt' => date('Y-m-d H:i:s')));
				
				$arr = $pjReplyModel
					->reset()
					->select("t1.*, t2.name as user_name, t3.name as client_name")
					->join('pjUser', 't2.id=t1.user_id', 'left')
					->join('pjClient', 't3.id=t1.client_id', 'left')
					->find($_GET['reply_id'])->getData();
				
				$file_arr = pjFileModel::factory()
					->select('t1.*')
					->join('pjReply',"t2.id = t1.reply_id AND t1.`type` = 'reply'", 'left')
					->where("t1.reply_id", $_GET['reply_id'])
					->where("`type`", 'reply')
					->findAll()
					->getData();
				$this->set('arr', $arr);
				$this->set('file_arr', $file_arr);
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR'));
			}
		}
	}
}
?>