<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdmin extends pjAppController
{
	public $defaultUser = 'admin_user';
	
	public $requireLogin = true;
	
	public function __construct($requireLogin=null)
	{
		$this->setLayout('pjActionAdmin');
		
		if (!is_null($requireLogin) && is_bool($requireLogin))
		{
			$this->requireLogin = $requireLogin;
		}
		
		if ($this->requireLogin)
		{
			if (!$this->isLoged() && !in_array(@$_GET['action'], array('pjActionLogin', 'pjActionForgot')))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
			}
		}
	}
	
	public function beforeRender()
	{
		
	}
		
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOperator())
		{
			$pjTicketModel = pjTicketModel::factory();
			$pjReplyModel = pjReplyModel::factory();
			
			$today = date('Y-m-d');
			
			if($this->isAdmin())
			{
				$new_tickets = $pjTicketModel->where("t1.status = 'New'")->where("t1.created LIKE '%$today%'")->findCount()->getData();
				$waiting_tickets = $pjTicketModel->reset()->where("t1.status <> 'Closed' AND t1.status <> 'RepliedBySupport'")->findCount()->getData();
				$active_tickets = $pjTicketModel->reset()->where("t1.status <> 'Closed'")->findCount()->getData();
			}else{
				$new_tickets = $pjTicketModel->where('t1.user_id', $this->getUserId())->where("t1.status = 'New'")->where("t1.created LIKE '%$today%'")->findCount()->getData();
				$waiting_tickets = $pjTicketModel->reset()->where('t1.user_id', $this->getUserId())->where("t1.status <> 'Closed' AND t1.status <> 'RepliedBySupport'")->findCount()->getData();
				$active_tickets = $pjTicketModel->reset()->where('t1.user_id', $this->getUserId())->where("t1.status <> 'Closed'")->findCount()->getData();
			}
			
			$pjTicketModel->reset();
			if($this->isOperator())
			{
				$pjTicketModel->where('t1.user_id', $this->getUserId());
			}
			$ticket_arr = $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')
				->where("t1.status <> 'Closed' AND t1.status <> 'RepliedBySupport'")
				->orderBy("last_reply DESC")
				->limit(10)
				->findAll()
				->getData();
			
			$pjReplyModel->reset();
			$pjReplyModel->where("t1.client_id IS NOT NULL");
			$reply_arr = $pjReplyModel
				->select("t1.*, t2.name as user_name, t3.name as client_name, t4.ticket_id AS ticketID, t5.name AS ticket_client_name, t5.id AS clientID")
				->join('pjUser', 't2.id=t1.user_id', 'left')
				->join('pjClient', 't3.id=t1.client_id', 'left')
				->join('pjTicket', 't4.id=t1.ticket_id', 'left')
				->join('pjClient', 't5.id=t4.client_id', 'left')
				->orderBy("t1.created DESC")
				->limit(10)
				->findAll()
				->getData();
			
			$this->set('new_tickets', $new_tickets);
			$this->set('waiting_tickets', $waiting_tickets);
			$this->set('active_tickets', $active_tickets);
			
			$this->set('ticket_arr', $ticket_arr);
			$this->set('reply_arr', $reply_arr);
				
			$this->appendJs('pjAdmin.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetTimeline()
	{
		$this->checkLogin();
		if ($this->isAdmin() || $this->isOperator())
		{
			$this->setAjax(true);
			
			$selected_date = pjUtil::formatDate($_GET['date'], $this->option_arr['o_date_format']);
			
			$from = mktime(0,0,0,date('m', strtotime($selected_date)),date('d', strtotime($selected_date)),date('Y', strtotime($selected_date)));
			$to = mktime(23,59,59,date('m', strtotime($selected_date)),date('d', strtotime($selected_date)),date('Y', strtotime($selected_date)));
			
			$from_sql_date = date('Y-m-d H:i:s', $from);
			$to_sql_date = date('Y-m-d H:i:s', $to);
			
			$pjReplyModel = pjReplyModel::factory();
			$replies = $pjReplyModel->select("t1.*")
							->where("t1.created >= '$from_sql_date' AND t1.created <= '$to_sql_date'")->orderBy("t1.created DESC")->findAll()->getData();
			
			$support_tmp_arr = array();
			$customer_tmp_arr = array();
			foreach($replies as $v)
			{
				if(!empty($v['user_id'])) {
					$support_tmp_arr[date('Y-m-d H', strtotime($v['created']))][] = $v['created'];
				}
				if(!empty($v['client_id'])) {
					$customer_tmp_arr[date('Y-m-d H', strtotime($v['created']))][] = $v['created'];
				}
			}
				
			$this->set('support', $support_tmp_arr);
			$this->set('customer', $customer_tmp_arr);		
			$this->set('from', $from);
		}
	}
	
	public function pjActionForgot()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['forgot_user']))
		{
			if (!isset($_POST['forgot_email']) || !pjValidation::pjActionNotEmpty($_POST['forgot_email']) || !pjValidation::pjActionEmail($_POST['forgot_email']))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=AA10");
			}
			$pjUserModel = pjUserModel::factory();
			$user = $pjUserModel
				->where('t1.email', $_POST['forgot_email'])
				->limit(1)
				->findAll()
				->getData();
				
			if (count($user) != 1)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=AA10");
			} else {
				$user = $user[0];
				
				$Email = new pjEmail();
				$Email
					->setTo($user['email'])
					->setFrom($this->getAdminEmail())
					->setSubject(__('emailForgotSubject', 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'])
					;
				}
				
				$body = str_replace(
					array('{Name}', '{Password}'),
					array($user['name'], $user['password']),
					__('emailForgotBody', true)
				);
				$Email->setContentType('text/html');
				if ($Email->send($body))
				{
					$err = "AA11";
				} else {
					$err = "AA12";
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=$err");
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionMessages()
	{
		$this->setAjax(true);
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	public function pjActionLogin()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['login_user']))
		{
			if (!isset($_POST['login_email']) || !isset($_POST['login_password']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_email']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_password']) ||
				!pjValidation::pjActionEmail($_POST['login_email']))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
			}
			$pjUserModel = pjUserModel::factory();

			$user = $pjUserModel
				->where('t1.email', $_POST['login_email'])
				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", pjObject::escapeString($_POST['login_password']), PJ_SALT))
				->limit(1)
				->findAll()
				->getData();

			if (count($user) != 1)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=1");
			} else {
				$user = $user[0];
				unset($user['password']);
															
				if (!in_array($user['role_id'], array(1,2,3)))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=2");
				}
				
				if ($user['role_id'] == 3 && $user['is_active'] == 'F')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=2");
				}
				
				if ($user['status'] != 'T')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=3");
				}
				
				$last_login = date("Y-m-d H:i:s");
    			$_SESSION[$this->defaultUser] = $user;
    			
    			$data = array();
    			$data['last_login'] = $last_login;
    			$pjUserModel->reset()->setAttributes(array('id' => $user['id']))->modify($data);

    			if ($this->isAdmin())
    			{
	    			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
    			}
    			
				if ($this->isOperator())
    			{
	    			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
    			}
    			
				if ($this->isOwner())
    			{
	    			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
    			}
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionLogout()
	{
		if ($this->isLoged())
        {
        	unset($_SESSION[$this->defaultUser]);
        }
       	pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
	}
	
	public function pjActionProfile()
	{
		$this->checkLogin();
		
		if ($this->isOwner() || $this->isOperator())
		{
			if (isset($_POST['profile_update']))
			{
				$pjUserModel = pjUserModel::factory();
				$arr = $pjUserModel->find($this->getUserId())->getData();
				$data = array();
				$data['role_id'] = $arr['role_id'];
				$data['status'] = $arr['status'];
				$post = array_merge($_POST, $data);
				if (!$pjUserModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionProfile&err=AA14");
				}
				$pjUserModel->set('id', $this->getUserId())->modify($post);
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionProfile&err=AA13");
			} else {
				
				$arr = pjUserModel::factory()->find($this->getUserId())->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminUsers&action=pjActionIndex&err=AU08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjUser');
				$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('role_arr', pjRoleModel::factory()->orderBy('t1.id 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('department_arr', pjSanitize::clean($department_arr, array('remove_html' => true)));
				
				$tmp_arr = pjUserDepartmentModel::factory()->where('t1.user_id', $this->getUserId())->findAll()->getData();
				$department_id_arr = array();
				foreach($tmp_arr as $v)
				{
					$department_id_arr[] = $v['department_id'];
				}
				$this->set('department_id_arr', $department_id_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('pjAdmin.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>