<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminNotifications extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['notification_create']))
			{
				if(isset($_POST['recipient_client'])){
					$_POST['recipient_client'] = 'T';
				}else{
					$_POST['recipient_client'] = 'F';
				}
				$id = pjNotificationModel::factory($_POST)->insert()->getInsertId();
				
				if ($id !== false && (int) $id > 0)
				{
					if(isset($_POST['department_id']))
					{
						$pjNotificationDepartmentModel = pjNotificationDepartmentModel::factory();
						$pjNotificationDepartmentModel->begin();
						foreach ($_POST['department_id'] as $department_id){
							$data = array();
							$data['notification_id'] = $id;
							$data['department_id'] = $department_id;
							$pjNotificationDepartmentModel->reset()->setAttributes($data)->insert();
						}
						$pjNotificationDepartmentModel->commit();
					}
					if(isset($_POST['user_id']))
					{
						$pjNotificationUserModel = pjNotificationUserModel::factory();
						$pjNotificationUserModel->begin();
						foreach ($_POST['user_id'] as $user_id){
							$data = array();
							$data['notification_id'] = $id;
							$data['user_id'] = $user_id;
							$pjNotificationUserModel->reset()->setAttributes($data)->insert();
						}
						$pjNotificationUserModel->commit();
					}					
					$err = 'AN03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjNotification');
					}
				} else {
					$err = 'AN04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminNotifications&action=pjActionIndex&err=$err");
			} else {
				$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));
		
				$user_arr = pjUserModel::factory()->where("t1.status = 'T'")->orderBy('t1.name ASC')->findAll()->getData();
				
				$this->set('user_arr', $user_arr);
				$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));
				
				$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('pjAdminNotifications.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteNotification()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjNotificationModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjNotification')->where('foreign_id', $_GET['id'])->eraseAll();
				pjNotificationDepartmentModel::factory()->where('notification_id', $_GET['id'])->eraseAll();
				pjNotificationUserModel::factory()->where('notification_id', $_GET['id'])->eraseAll();
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteNotificationBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjNotificationModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjNotification')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				pjNotificationDepartmentModel::factory()->whereIn('notification_id', $_POST['record'])->eraseAll();
				pjNotificationUserModel::factory()->whereIn('notification_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionGetNotification()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjNotificationModel = pjNotificationModel::factory()->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjNotification' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'subject'", 'left');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjNotificationModel->where('t2.content LIKE', "%$q%" OR 't3.content LIKE', "%$q%");
			}
			
			$column = 'id';
			$direction = 'DESC';
			$allowed_columns = array('subject', 'type');
			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 = $pjNotificationModel->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 = $pjNotificationModel->select('t1.id, t1.`type`, t2.content AS subject')
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			$data = pjSanitize::clean($data);			
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
		
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminNotifications.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveNotification()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjNotificationModel = pjNotificationModel::factory();
			if (!in_array($_POST['column'], $pjNotificationModel->i18n))
			{
				$pjNotificationModel->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'], 'pjNotification');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin())
		{
			if (isset($_POST['notification_update']))
			{
				if(isset($_POST['recipient_client'])){
					$_POST['recipient_client'] = 'T';
				}else{
					$_POST['recipient_client'] = 'F';
				}
				pjNotificationModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjNotification');
				}
				$pjNotificationDepartmentModel = pjNotificationDepartmentModel::factory();
				$pjNotificationDepartmentModel->where('notification_id', $_POST['id'])->eraseAll();
				if(isset($_POST['department_id']))
				{
					$pjNotificationDepartmentModel->begin();
					foreach ($_POST['department_id'] as $department_id){
						$data = array();
						$data['notification_id'] = $_POST['id'];
						$data['department_id'] = $department_id;
						$pjNotificationDepartmentModel->reset()->setAttributes($data)->insert();
					}
					$pjNotificationDepartmentModel->commit();
				}
				
				$pjNotificationUserModel = pjNotificationUserModel::factory();
				$pjNotificationUserModel->where('notification_id', $_POST['id'])->eraseAll();
				if(isset($_POST['user_id']))
				{
					$pjNotificationUserModel->begin();
					foreach ($_POST['user_id'] as $user_id){
						$data = array();
						$data['notification_id'] = $_POST['id'];
						$data['user_id'] = $user_id;
						$pjNotificationUserModel->reset()->setAttributes($data)->insert();
					}
					$pjNotificationUserModel->commit();
				}
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminNotifications&action=pjActionIndex&err=AN01");
				
			} else {
				$arr = pjNotificationModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminNotifications&action=pjActionIndex&err=AN08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjNotification');
				$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));
				
				$user_arr = pjUserModel::factory()->where("t1.status = 'T'")->orderBy('t1.name ASC')->findAll()->getData();
				
				$this->set('user_arr', $user_arr);
				
				$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));
						
				$pjNotificationDepartmentModel = pjNotificationDepartmentModel::factory()->where('t1.notification_id', $_GET['id']);
				$tmp_arr = $pjNotificationDepartmentModel->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);
				
				$pjNotificationUserModel = pjNotificationUserModel::factory()->where('t1.notification_id', $_GET['id']);
				$tmp_arr = $pjNotificationUserModel->findAll()->getData();
				$user_id_arr = array();
				foreach($tmp_arr as $v)
				{
					$user_id_arr[] = $v['user_id'];
				}
				$this->set('user_id_arr', $user_id_arr);
				
				$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('pjAdminNotifications.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetLocale()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_GET['locale']) && (int) $_GET['locale'] > 0)
			{
				pjAppController::setFields($_GET['locale']);
				$department_id_str = $_GET['department_id'];
				$department_id_arr = array();
				if($department_id_str != '')
				{
					$department_id_arr = explode(',', $department_id_str);
				}
				$this->set('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='".$_GET['locale']."'", 'left')
						->where('status', 'T')->orderBy('name ASC')->findAll()->getData()
					);
				$this->set('department_id_arr',$department_id_arr);
			}
		}
	}
}
?>