<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminMessages extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['message_create']))
			{
				
				$id = pjMessageModel::factory($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$pjMessageCategoryModel = pjMessageCategoryModel::factory();
					$pjMessageCategoryModel->begin();
					foreach ($_POST['category_id'] as $category_id){
						$data = array();
						$data['message_id'] = $id;
						$data['category_id'] = $category_id;
						$pjMessageCategoryModel->reset()->setAttributes($data)->insert();
					}
					$pjMessageCategoryModel->commit();
					
					$err = 'AM03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjMessage');
					}
				} else {
					$err = 'AM04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminMessages&action=pjActionIndex&err=$err");
			} else {
				$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('status', 'T')
					->orderBy('category_name ASC')
					->findAll()->getData();
				$this->set('category_arr', pjSanitize::clean($category_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.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('pjAdminMessages.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeleteMessage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjMessageModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjMessage')->where('foreign_id', $_GET['id'])->eraseAll();
				pjMessageCategoryModel::factory()->where('message_id', $_GET['id'])->eraseAll();
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteMessageBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjMessageModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjMessage')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				pjMessageCategoryModel::factory()->whereIn('message_id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionGetMessage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjMessageModel = pjMessageModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjMessageModel->where('t1.message LIKE', "%$q%");
			}

			$column = 'id';
			$direction = 'DESC';
			$allowed_columns = array('message', 'categories');
			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 = $pjMessageModel->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 = $pjMessageModel->select("t1.id, t1.status, t1.message")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()->getData();
			
			$message_id_arr = $pjMessageModel->findAll()->getDataPair(null, 'id');
			$category_arr = array();
			if(!empty($message_id_arr))
			{
				$temp_category_arr = pjMessageCategoryModel::factory()
					->select('t1.*, t2.content as category')
					->join('pjMultiLang', "t2.foreign_id = t1.category_id AND t2.model = 'pjCategory' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
					->whereIn('t1.message_id', $message_id_arr)
					->orderBy('category ASC')
					->findAll()->getData();
				
				foreach($temp_category_arr as $k => $v)
				{
					$category_arr[$v['message_id']][] = $v['category'];
				}	
			}
			
			foreach($data as $k => $v)
			{
				$v['message'] = pjUtil::truncateDescription(pjUtil::html2txt($v['message']), 100, ' ');
				$v['categories'] = '';
				if(isset($category_arr[$v['id']]))
				{
					$v['categories'] = join("</br>", $category_arr[$v['id']]);
				}
				$data[$k] = $v;
			}		
			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('pjAdminMessages.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveMessage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjMessageModel = pjMessageModel::factory();
			if (!in_array($_POST['column'], $pjMessageModel->i18n))
			{
				$pjMessageModel->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'], 'pjMessage');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin())
		{
			if (isset($_POST['message_update']))
			{
				pjMessageModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjMessage');
				}
				$pjMessageCategoryModel = pjMessageCategoryModel::factory();
				$pjMessageCategoryModel->where('message_id', $_POST['id'])->eraseAll();
				if(isset($_POST['category_id']))
				{
					$pjMessageCategoryModel->begin();
					foreach ($_POST['category_id'] as $category_id){
						$data = array();
						$data['message_id'] = $_POST['id'];
						$data['category_id'] = $category_id;
						$pjMessageCategoryModel->reset()->setAttributes($data)->insert();
					}
					$pjMessageCategoryModel->commit();
				}
								
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminMessages&action=pjActionIndex&err=AM01");
				
			} else {
				$arr = pjMessageModel::factory()->find($_GET['id'])->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminMessages&action=pjActionIndex&err=AM08");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjMessage');
				$this->set('arr', $arr);
				
				$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('status', 'T')
					->orderBy('category_name ASC')
					->findAll()->getData();
				$this->set('category_arr', pjSanitize::clean($category_arr, array('remove_html' => true)));
				
				$pjMessageCategoryModel = pjMessageCategoryModel::factory()->where('t1.message_id', $_GET['id']);
				$tmp_arr = $pjMessageCategoryModel->findAll()->getData();
				$category_id_arr = array();
				foreach($tmp_arr as $v)
				{
					$category_id_arr[] = $v['category_id'];
				}
				$this->set('category_id_arr', $category_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.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('pjAdminMessages.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>