<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminClients extends pjAdmin
{
	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 pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			if (isset($_POST['client_create']))
			{
				$data = array();
				$data['is_active'] = 'T';
				if(!empty($_POST['client_since']))
				{
					$data['client_since'] = pjUtil::formatDate($_POST['client_since'], $this->option_arr['o_date_format']);
				}
				unset($_POST['client_since']);
				$id = pjClientModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					$this->sendNewClientEmail($id, $this->getAdminEmail(), $this->getLocaleId(), $this->option_arr);
					
					$err = 'ACL03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjClient');
					}
				} else {
					$err = 'ACL04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminClients&action=pjActionIndex&err=$err");
			} else {
				$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();
				$this->set('country_arr', pjSanitize::clean($country_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->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$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('pjAdminClients.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteClient()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjClientModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjClient')->where('foreign_id', $_GET['id'])->eraseAll();
				
				$pjTicketModel = pjTicketModel::factory();
				$pjFileModel = pjFileModel::factory();
				$pjReplyModel = pjReplyModel::factory();
				
				$pjTicketModel->where('client_id', $_GET['id']);
				$ticket_arr = $pjTicketModel->findAll()->getData();
				
				foreach($ticket_arr as $v)
				{
					$ticket_id = $v['id'];
					 
					$pjFileModel->reset()->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();
					$pjTicketModel->reset()->setAttributes(array('id' => $ticket_id))->erase();
				}
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteClientBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjClientModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjClient')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				
				$pjTicketModel = pjTicketModel::factory();
				$pjFileModel = pjFileModel::factory();
				$pjReplyModel = pjReplyModel::factory();
				
				$pjTicketModel->whereIn('client_id', $_POST['record']);
				$ticket_arr = $pjTicketModel->findAll()->getData();
				foreach($ticket_arr as $v)
				{
					$ticket_id = $v['id'];
					$pjFileModel->reset()->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();
					$pjTicketModel->reset()->setAttributes(array('id' => $ticket_id))->erase();
				}
			}
		}
		exit;
	}
	
	public function pjActionExportClient()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjClientModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Clients-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetClient()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjClientModel = pjClientModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjClientModel->where('t1.email LIKE', "%$q%");
				$pjClientModel->orWhere('t1.name LIKE', "%$q%");
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjClientModel->where('t1.status', $_GET['status']);
			}
				
			$column = 'name';
			$direction = 'ASC';
			$allowed_columns = array('name', 'email', 'last_login', 'tickets', '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 = $pjClientModel->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;
			}
			$sub_query = "(SELECT COUNT(*) FROM " . pjTicketModel::factory()->getTable() . " AS t2 WHERE t1.id = t2.client_id) as tickets";
			$data = $pjClientModel->select("t1.id, t1.email, t1.name, t1.last_login, t1.status, $sub_query")
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			
			foreach($data as $k => $v)
			{
				$v['name'] = stripslashes(htmlspecialchars($v['name']));
				$v['last_login'] = !empty($v['last_login']) ? date($this->option_arr['o_date_format'], strtotime($v['last_login'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['last_login'])) : __('lblNA', true);
				$data[$k] = $v;
			}
			
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminClients.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveClient()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjClientModel = pjClientModel::factory();
	
			if (!in_array($_POST['column'], $pjClientModel->i18n))
			{
				$pjClientModel->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'], 'pjClient');
			}
		}
		exit;
	}
	
	public function pjActionStatusClient()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjClientModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
				
			if (isset($_POST['client_update']))
			{
				if(!empty($_POST['client_since']))
				{
					$_POST['client_since'] = pjUtil::formatDate($_POST['client_since'], $this->option_arr['o_date_format']);
				}
				
				pjClientModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjClient');
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminClients&action=pjActionIndex&err=ACL01");
				
			} else {
				
				$tbl_reply = pjReplyModel::factory()->getTable();
				$tbl_ticket = pjTicketModel::factory()->getTable();
				$arr = pjClientModel::factory()
					->select("t1.*, 
							(SELECT TR.ticket_id FROM `".$tbl_reply."` AS TR WHERE TR.ticket_id IN (SELECT TK.id FROM `".$tbl_ticket."` AS TK WHERE TK.client_id=t1.id) ORDER BY TR.created LIMIT 1) AS tkid,
							(SELECT TR.created FROM `".$tbl_reply."` AS TR WHERE TR.ticket_id IN (SELECT TK.id FROM `".$tbl_ticket."` AS TK WHERE TK.client_id=t1.id) ORDER BY TR.created LIMIT 1) AS last_reply,
							(SELECT TK.ticket_id FROM `".$tbl_ticket."` AS TK WHERE TK.id=(SELECT TR.ticket_id FROM `".$tbl_reply."` AS TR WHERE TR.ticket_id IN (SELECT TK2.id FROM `".$tbl_ticket."` AS TK2 WHERE TK2.client_id=t1.id) ORDER BY TR.created LIMIT 1) ) ticket_id")
					->find($_GET['id'])
					->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminClients&action=pjActionIndex&err=ACL08");
				}
				$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));
				
				$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();
				$this->set('country_arr', pjSanitize::clean($country_arr));

				$cnt_tickets = pjTicketModel::factory()->where("client_id=" . $_GET['id'])->findCount()->getData();
				$this->set('cnt_tickets', $cnt_tickets);
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$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('pjAdminClients.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	public function pjActionGetContent()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$notification_arr = pjNotificationModel::factory()
				->select('t1.*, t2.content AS subject, t3.content AS message')
				->join('pjMultiLang', "t2.model='pjNotification' AND t2.foreign_id=t1.id AND t2.field='subject' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t3.model='pjNotification' AND t3.foreign_id=t1.id AND t3.field='message' AND t3.locale='".$this->getLocaleId()."'", 'left')
				->where("`type`", 'AccountActivation')->orderBy("t1.id DESC")->findAll()->getData();
			
			$notification_arr = $notification_arr[0];
			
			$client = pjClientModel::factory()->find($_GET['id'])->getData();
			$search = array('{ClientName}', '{ClientEmail}', '{ClientPassword}');
			$replace = array($client['name'], $client['email'], $client['password']);
			$tokens = compact('search', 'replace');
			
			$subject = $notification_arr['subject'];
			$message = str_replace($tokens['search'], $tokens['replace'], $notification_arr['message']);
			
			$response = array(
					'email' => $client['email'],
					'subject' => $subject,
					'body' => $message
			);
			$this->set('response', $response);
		}
	}
	
	public function pjActionSendMessage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$Email = new pjEmail();
			pjAppController::setFields($this->getLocaleId());
			$Email
			->setContentType('text/html')
			->setTo($_POST['email'])
			->setFrom($_SESSION[$this->defaultUser]['email'])
			->setSubject($_POST['subject'])
			;
				
			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->send($_POST['message']);
		}
		exit;
	}
}
?>