<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}

class pjAdminTemplates extends pjAdmin
{
	public function pjActionCheckTitle()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['title']) || empty($_GET['title']))
			{
				echo 'false';
				exit;
			}
			$pjTemplateModel = pjTemplateModel::factory()->where('t1.title', $_GET['title']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjTemplateModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjTemplateModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			if (isset($_POST['template_create']))
			{
				$pjTemplateModel = pjTemplateModel::factory();
				
				$id = $pjTemplateModel->reset()->setAttributes($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'ATE03';
				} else {
					$err = 'ATE04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminTemplates&action=pjActionIndex&err=$err");
			} else {
				
				$token_arr = pjTokenModel::factory()
					->select("CONCAT(t1.token, ' - ', t1.title) AS pair")
					->findAll()
					->getDataPair(null, 'pair');
				
				$this->set('token_arr', $token_arr);
				
				$this->setFileuploaderVars();
				
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tiny_mce/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminTemplates.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteTemplate()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$response = array();
			if ($this->isAdmin())
			{
				if (pjTemplateModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
				{
					$pjDocumentModel = pjDocumentModel::factory();
					
					$doc_id_arr = $pjDocumentModel->where('template_id', $_GET['id'])->findAll()->getDataPair(null, 'id');
					if(!empty($doc_id_arr))
					{
						$pjDocumentModel->reset()->whereIn('id', $doc_id_arr)->eraseAll();
						pjHistoryModel::factory()->whereIn('document_id', $doc_id_arr)->eraseAll();
					}
					$response['code'] = 200;
				} else {
					$response['code'] = 100;
				}
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteTemplateBulk()
	{
		$this->setAjax(true);
	
		if (!$this->isXHR())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing headers.'));
		}
		
		if (!$this->isAdmin())
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Access denied.'));
		}
		
		if (!(isset($_POST['record']) && count($_POST['record']) > 0))
		{
			self::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Missing, empty or invalid parameters.'));
		}
		
		$pjDocumentModel = pjDocumentModel::factory();
		
		pjTemplateModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
		$doc_id_arr = $pjDocumentModel->whereIn('template_id', $_POST['record'])->findAll()->getDataPair(null, 'id');
		if(!empty($doc_id_arr))
		{
			$pjDocumentModel->reset()->whereIn('id', $doc_id_arr)->eraseAll();
			pjHistoryModel::factory()->whereIn('document_id', $doc_id_arr)->eraseAll();
		}
		
		self::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Templates has been deleted.'));
	}
	
	public function pjActionExportTemplate()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjTemplateModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Templates-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetTemplate()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjTemplateModel = pjTemplateModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjTemplateModel->where('t1.title LIKE', "%$q%");
				$pjTemplateModel->orWhere('t1.content LIKE', "%$q%");
			}
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjTemplateModel->where('t1.status', $_GET['status']);
			}
			$column = 'id';
			$direction = 'ASC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjTemplateModel->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 = $pjTemplateModel
				->select("t1.*, (SELECT COUNT(id) FROM `".pjDocumentModel::factory()->getTable()."` TD WHERE TD.template_id = t1.id) AS documents")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();

			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('pjAdminTemplates.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$pjTemplateModel = pjTemplateModel::factory();
			if (isset($_POST['template_update']))
			{
				$pjTemplateModel->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminTemplates&action=pjActionIndex&err=ATE01");
				
			} else {
				$arr = $pjTemplateModel
					->select("t1.*, (SELECT COUNT(id) FROM `".pjDocumentModel::factory()->getTable()."` TD WHERE TD.template_id = t1.id) AS documents")
					->find($_GET['id'])
					->getData();
					
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminTemplates&action=pjActionIndex&err=ATE08");
				}
				
				$token_arr = pjTokenModel::factory()
					->select("CONCAT(t1.token, ' - ', t1.title) AS pair")
					->findAll()
					->getDataPair(null, 'pair');
				
				$this->set('arr', $arr);
				$this->set('token_arr', $token_arr);
				
				$this->setFileuploaderVars();
				
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tiny_mce/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminTemplates.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>