<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminTickets extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminTickets&action=pjActionIndex&err=AT05");
			}
			if (isset($_POST['ticket_create']))
			{
				$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($_POST['client_type'] == 'new'){
					$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'] = $_POST['email'];
						$client_data['password'] = pjToolkit::getRandomPassword();
						$data['client_id'] = $pjClientModel->reset()->setAttributes($client_data)->insert()->getInsertId();
						
						if(pjValidation::pjActionEmail($client_data['email']) == true)
						{
							$this->sendNewClientEmail($data['client_id'], $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);
						}
					}
					unset($_POST['client_id']);
				}
								
				$id = pjTicketModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AT03';
					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;
						 	}
						}
						$has_error = false;
						foreach ($files as $file)
						{
							if($file['error'] != 4 && $file['error'] != 0)
							{
								$has_error = true;
								$err = 'AF11';
							}
							if(!empty($file['tmp_name']))
							{
								$path = $file['name'];
								$extension = pathinfo($path, PATHINFO_EXTENSION);
								$allowed_arr = explode("|", strtolower($this->option_arr['o_file_allowed']));
								if(!in_array($extension, $allowed_arr))
								{
									$has_error = true;
									$err = 'AT12';
								}
							}
						}
						if($has_error == false)
						{
							$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($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();
									}
								}
							}
						}
					}
					
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjTicket');
					}
					
					if($_POST['status'] == 'New')
					{
						$this->sendEmail($id, 'NewTicket', null, $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);
					}
				} else {
					$err = 'AT04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminTickets&action=pjActionIndex&err=$err");
			} else {
				$user_arr = pjUserModel::factory()->where("t1.status = 'T'")->orderBy('t1.name ASC')->findAll()->getData();
				$client_arr = pjClientModel::factory()->where("t1.status = 'T'")->orderBy('t1.name ASC')->findAll()->getData();
				$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('user_arr', pjSanitize::clean($user_arr));
				$this->set('client_arr', pjSanitize::clean($client_arr));
				$this->set('department_arr', pjSanitize::clean($department_arr, array('remove_html' => true)));
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminTickets.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteTicket()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjTicketModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjTicket')->where('foreign_id', $_GET['id'])->eraseAll();
				
				$ticket_id = $_GET['id'];
				
				$pjFileModel = pjFileModel::factory();
				$pjReplyModel = pjReplyModel::factory();
				
				$pjFileModel->where('ticket_id', $ticket_id);
				$file_arr = $pjFileModel->findAll()->getData();
				foreach($file_arr as $f)
				{
					$file_path = $f['file_path'];
					if (file_exists(PJ_INSTALL_PATH . $file_path)) {
						if(unlink(PJ_INSTALL_PATH . $file_path)){
						}
					}
				}
				$pjFileModel->reset()->where('ticket_id', $ticket_id)->eraseAll();
				$pjReplyModel->where('ticket_id', $ticket_id)->eraseAll();
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteTicketBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjTicketModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjTicket')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				
				$pjFileModel = pjFileModel::factory();
				$pjReplyModel = pjReplyModel::factory();
				
				$pjFileModel->whereIn('ticket_id', $_POST['record']);
				$file_arr = $pjFileModel->findAll()->getData();
				foreach($file_arr as $f)
				{
					$file_path = $f['file_path'];
					if (file_exists(PJ_INSTALL_PATH . $file_path)) {
						if(unlink(PJ_INSTALL_PATH . $file_path)){
						}
					}
				}
				$pjFileModel->reset()->whereIn('ticket_id', $_POST['record'])->eraseAll();
				$pjReplyModel->whereIn('ticket_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportTicket()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjTicketModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Tickets-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetTicket()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjTicketModel = pjTicketModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = trim(pjObject::escapeString($_GET['q']));
				$pjTicketModel->where("t1.ticket_id LIKE '%$q%' OR t1.client_id IN(SELECT t6.id FROM " . pjClientModel::factory()->getTable() . " AS t6 WHERE t6.name LIKE '%$q%' OR t6.email LIKE '%$q%')");
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('New', 'RepliedByClient', 'RepliedBySupport', 'InProgress', 'Closed')))
			{
				$pjTicketModel->where('t1.status', $_GET['status']);
			}
			if (isset($_GET['client_id']) && (int) $_GET['client_id'] > 0)
			{
				$pjTicketModel->where('t1.client_id', $_GET['client_id']);
			}
			if (isset($_GET['user_id']) && !empty($_GET['user_id']))
			{
				$pjTicketModel->where('t1.user_id', $_GET['user_id']);
			}
			if (isset($_GET['ticket_id']))
			{
				if($_GET['ticket_id'] != '')
				{
					$ticket_id = trim(pjObject::escapeString($_GET['ticket_id']));
					$pjTicketModel->where("t1.ticket_id LIKE '%$ticket_id%'");
				}
			}
			if (isset($_GET['department_id']))
			{
				if($_GET['department_id'] != '')
				{
					$department_id = $_GET['department_id'];
					$pjTicketModel->where("t1.department_id", $department_id);
				}
			}
			if (isset($_GET['client_name']))
			{
				if($_GET['client_name'] != '')
				{
					$client_name = pjObject::escapeString($_GET['client_name']);
					$pjTicketModel->where("t1.client_id IN(SELECT t7.id FROM " . pjClientModel::factory()->getTable() . " AS t7 WHERE t7.name LIKE '%$client_name%')");
				}
			}
			if (isset($_GET['client_email']))
			{
				if($_GET['client_email'] != '')
				{
					$client_email = pjObject::escapeString($_GET['client_email']);
					$pjTicketModel->where("t1.client_id IN(SELECT t8.id FROM " . pjClientModel::factory()->getTable() . " AS t8 WHERE t8.email LIKE '%$client_email%')");
				}
			}
			if (isset($_GET['adv_status']) && !empty($_GET['adv_status']) && in_array($_GET['adv_status'], array('New', 'RepliedByClient', 'RepliedBySupport', 'InProgress', 'Closed')))
			{
				if($_GET['adv_status'] != '')
				{
					$pjTicketModel->where('t1.status', $_GET['adv_status']);
				}
			}
			if (isset($_GET['received_after']))
			{
				if($_GET['received_after'] != '')
				{
					$received_after = pjUtil::formatDate($_GET['received_after'], $this->option_arr['o_date_format']);
					$pjTicketModel->where("t1.id IN(SELECT t10.ticket_id FROM " . pjReplyModel::factory()->getTable() . " AS t10 WHERE t10.created <= '$received_after')");
				}
			}
			if (isset($_GET['received_before']))
			{
				if($_GET['received_before'] != '')
				{
					$received_before = pjUtil::formatDate($_GET['received_before'], $this->option_arr['o_date_format']);
					$pjTicketModel->where("t1.id IN(SELECT t11.ticket_id FROM " . pjReplyModel::factory()->getTable() . " AS t11 WHERE t11.created >= '$received_before')");
				}
			}
			if (isset($_GET['message']) && !empty($_GET['message']))
			{
				$message = pjObject::escapeString($_GET['message']);
				$pjTicketModel->where("t1.id IN(SELECT t9.ticket_id FROM " . pjReplyModel::factory()->getTable() . " AS t9 WHERE t9.reply_text LIKE '%$message%')");
			}
			
			$column = 't1.created';
			$direction = 'DESC';
			$allowed_columns = array('ticket_id', 'client', 'department', 'last_reply', 'status');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
			$total = $pjTicketModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$pages = ceil($total / $rowCount);
			$page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['page']) : 1;
			$offset = ((int) $page - 1) * $rowCount;
			if ($page > $pages)
			{
				$page = $pages;
			}
			$data = $pjTicketModel->select("t1.id, t1.ticket_id, t1.status, t2.name AS assigned_to, t3.name AS client, t3.id AS client_id, t5.content AS department, (SELECT t6.created FROM `" . pjReplyModel::factory()->getTable() . "` as t6 WHERE t6.ticket_id = t1.id ORDER BY t6.created DESC LIMIT 1) AS last_reply")
				->join('pjUser', 't2.id=t1.user_id', 'left')
				->join('pjClient', 't3.id=t1.client_id', 'left')
				->join('pjDepartment', 't4.id=t1.department_id', 'left')
				->join('pjMultiLang', "t5.model='pjDepartment' AND t5.foreign_id=t4.id AND t5.field='name' AND t5.locale='".$this->getLocaleId()."'", 'left')
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			
			foreach($data as $k => $v)
			{
				if(!empty($v['last_reply']))
				{
					$v['last_reply'] = pjUtil::formatDate(date('Y-m-d', strtotime($v['last_reply'])), "Y-m-d", $this->option_arr['o_date_format']) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['last_reply']));
				}else{
					$v['last_reply'] = __('lblNA', true);
				}
				$data[$k] = $v;
			}
			$data = pjSanitize::clean($data);
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			$user_arr = pjUserModel::factory()->where("t1.status = 'T'")->orderBy('t1.name ASC')->findAll()->getData();
			$client_arr = pjClientModel::factory()->where("t1.status = 'T'")->orderBy('t1.name ASC')->findAll()->getData();
			$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('user_arr', pjSanitize::clean($user_arr));
			$this->set('client_arr', pjSanitize::clean($client_arr));
			$this->set('department_arr', pjSanitize::clean($department_arr, array('remove_html' => true)));
				
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminTickets.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveTicket()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjTicketModel = pjTicketModel::factory();
	
			if (!in_array($_POST['column'], $pjTicketModel->i18n))
			{
				$pjTicketModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjTicket');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			if (isset($_POST['ticket_update']))
			{
				$data = array();
				$data['ip'] = $_SERVER['REMOTE_ADDR'];
								
				pjTicketModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjTicket');
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminTickets&action=pjActionIndex&err=AT01");
				
			} else {
				$pjReplyModel = pjReplyModel::factory();
				$pjFileModel = pjFileModel::factory();
				
				$arr = pjTicketModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminTickets&action=pjActionIndex&err=AT08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjTicket');
				$this->set('arr', $arr);
				
				$user_arr = pjUserModel::factory()->where("t1.status = 'T'")->orderBy('t1.name ASC')->findAll()->getData();
				$client_arr = pjClientModel::factory()->where("t1.status = 'T'")->orderBy('t1.name ASC')->findAll()->getData();
				$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('user_arr', pjSanitize::clean($user_arr));
				$this->set('client_arr', pjSanitize::clean($client_arr));
				$this->set('department_arr', pjSanitize::clean($department_arr, array('remove_html' => true)));

				$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=".$_GET['id'])
					->orderBy("t1.created ASC")
					->findAll()
					->getData();

				$this->set('reply_arr', $reply_arr);
				
				$last_rating = $pjReplyModel
					->reset()
					->where("ticket_id=".$_GET['id'])
					->where("(t1.user_id IS NOT NULL)")
					->where("t1.rate IS NOT NULL")
					->orderBy("t1.rate_dt DESC")
					->limit(1)
					->findAll()
					->getData();
				$this->set('last_rating', $last_rating);
				
				$ticket_file_arr = $pjFileModel->where("ticket_id", $_GET['id'])->where("`type`", 'ticket')->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'] . " AND t1.`type` = 'reply'")->findAll()->getData();
				
				$reply_file_arr = array();
				foreach($temp_arr as $v)
				{
					$reply_file_arr[$v['reply_id']][] = $v;
				}
				
				$category_arr = pjCategoryModel::factory()
					->select('t1.*, t2.content as category_name')
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjCategory' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->where('t1.status', 'T')
					->orderBy("category_name ASC")
					->findAll()->getData();
						
				$this->set('ticket_file_arr', $ticket_file_arr);
				$this->set('reply_file_arr', $reply_file_arr);
				$this->set('category_arr', $category_arr);
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('jquery.ui.dialog.min.js', PJ_THIRD_PARTY_PATH . 'jquery_ui/js/');
				$this->appendCss('jquery.ui.dialog.min.css', PJ_THIRD_PARTY_PATH . 'jquery_ui/css/smoothness/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('pjAdminTickets.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionPostReply()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminTickets&action=pjActionIndex&err=AT05");
			}
			
			$ticket_id = $_POST['ticket_id'];
			$user_id = $_POST['user_id'];
			
			$pjFileModel = pjFileModel::factory();
			$pjReplyModel = pjReplyModel::factory();
			$pjTicketModel = pjTicketModel::factory();
			$pjNotificationModel = pjNotificationModel::factory();
			$pjClientModel = pjClientModel::factory();
			
			$reply_id = $pjReplyModel->setAttributes($_POST)->insert()->getInsertId();
			if ($reply_id !== false && (int) $reply_id > 0)
			{
				$err = 'AT09';
				
				if (isset($_FILES['files']))
				{
					$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;
					 	}
					}
					$has_error = false;
					
					foreach ($files as $file)
					{
						if($file['error'] != 4 && $file['error'] != 0)
						{
							$has_error = true;
							$err = 'AF11';
						}
						if(!empty($file['tmp_name']))
						{
							$path = $file['name'];
							$extension = pathinfo($path, PATHINFO_EXTENSION);
							$allowed_arr = explode("|", strtolower($this->option_arr['o_file_allowed']));
							if(!in_array($extension, $allowed_arr))
							{
								$has_error = true;
								$err = 'AT12';
							}
						}
					}
					
					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($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();
							}
						}
					}
					
				}
				
				$data = array();
				$data['status'] = 'RepliedBySupport';
				$pjTicketModel->where('id', $ticket_id)->limit(1)->modifyAll($data);
				
				$reply_arr = $pjReplyModel->reset()->find($reply_id)->getData();
				
				$this->sendEmail($ticket_id, 'NewSupportReply', $reply_arr, $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);
						
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminTickets&action=pjActionUpdate&id=$ticket_id&err=$err");
			}else{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminTickets&action=pjActionUpdate&id=$ticket_id&err=AT10");
			}
			
		}
	}
	
	public function pjActionUpdateReply()
	{
		$this->setAjax(true);
		
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			$pjReplyModel = pjReplyModel::factory();
			
			$pjReplyModel->where('id', $_POST['reply_id'])->limit(1)->modifyAll($_POST);
			
			$arr = $pjReplyModel->reset()->find($_POST['reply_id'])->getData();
			
			$this->set('arr', $arr);
		}
	}
	
	public function pjActionDeleteReply()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjReplyModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$reply_id = $_GET['id'];
				$pjFileModel = pjFileModel::factory();
				$pjFileModel->where('reply_id', $reply_id);
				$file_arr = $pjFileModel->findAll()->getData();
				foreach($file_arr as $f)
				{
					$file_path = $f['file_path'];
					if (file_exists(PJ_INSTALL_PATH . $file_path)) {
						if(unlink(PJ_INSTALL_PATH . $file_path)){
						}
					}
				}
				$pjFileModel->reset()->where('reply_id', $reply_id)->eraseAll();
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionGetMessages()
	{
		$this->setAjax(true);
		
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			$category_id = $_GET['cat_id'];
			$message_arr = pjMessageModel::factory()->select('t1.*')
								->join('pjMessageCategory',"t2.message_id = t1.id", 'left')
								->where("t2.category_id = $category_id")->findAll()->getData();
			$this->set('message_arr', pjSanitize::clean($message_arr));
		}
	}
	
	public function pjActionDownloadFile()
	{
		$id = $_GET['id'];
		$arr = pjFileModel::factory()->find($id)->getData();
		if(!empty($arr))
		{
			pjToolkit::download(@file_get_contents(PJ_INSTALL_PATH . $arr['file_path']), $arr['file_name'], $arr['mime_type']);
			exit;
		}
	}
}
?>