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

class pjAdminDocuments extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['document_create']))
			{
				$pjDocumentModel = pjDocumentModel::factory();
				
				$id = $pjDocumentModel->reset()->setAttributes($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AD03';
				} else {
					$err = 'AD04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminDocuments&action=pjActionIndex&err=$err");
			} else {
				$pjCustomerTokenModel = pjCustomerTokenModel::factory();
				$template_arr = pjTemplateModel::factory()
					->where('t1.status', 'T')
					->findAll()
					->getData();
				$customer_arr = pjCustomerModel::factory()
					->select("t1.*,
							  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.id AND TCT.token_id=1) AS first_name,
						  	  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.id AND TCT.token_id=2) AS last_name")
					->where('t1.status', 'T')
					->orderBy("first_name ASC, last_name ASC")
					->findAll()
					->getData();
				
				$this->set('template_arr', $template_arr);
				$this->set('customer_arr', $customer_arr);
				
				$this->setFileuploaderVars();
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tiny_mce/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminDocuments.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteDocument()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$response = array();
			if ($this->isAdmin())
			{
				if (pjDocumentModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
				{
					pjHistoryModel::factory()->where('document_id', $_GET['id'])->eraseAll();
					
					$response['code'] = 200;
				} else {
					$response['code'] = 100;
				}
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteDocumentBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if ($this->isAdmin())
			{
				if (isset($_POST['record']) && count($_POST['record']) > 0)
				{
					
					pjDocument::factory()->whereIn('id', $_POST['record'])->eraseAll();
					pjHistoryModel::factory()->whereIn('document_id', $_POST['record'])->eraseAll();
				}
			}
		}
		exit;
	}
	
	public function pjActionGenerateContent()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if ($this->isAdmin() || $this->isEditor())
			{
				if(isset($_GET['template_id']) && (int) $_GET['template_id'] > 0 && isset($_GET['customer_id']) && (int) $_GET['customer_id'] > 0)
				{
					$token_arr = pjTokenModel::factory()
						->select("t1.token, (SELECT TCT.content FROM `".pjCustomerTokenModel::factory()->getTable()."` AS TCT WHERE TCT.token_id=t1.id AND TCT.customer_id='".$_GET['customer_id']."') AS content ")
						->findAll()
						->getDataPair('token', 'content');
					
					$template = pjTemplateModel::factory()
						->find($_GET['template_id'])
						->getData();
					
					$search = array();
					$replace = array();
					foreach($token_arr as $k => $v)
					{
						$search[] = $k;
						$replace[] = $v;
					}
					$message = str_replace($search, $replace, $template['content']);
					
					$this->set('status', 'OK');
					$this->set('message', $message);
				}else{
					$this->set('status', 'ERR');
				}
			}
		}
	}
	
	public function pjActionExportDocument()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjDocumentModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Documents-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetDocument()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjDocumentModel = pjDocumentModel::factory()
				->join('pjTemplate', "t1.template_id=t2.id", 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjDocumentModel->where('t1.title LIKE', "%$q%");
				$pjDocumentModel->orWhere('t1.content LIKE', "%$q%");
			}
			if (isset($_GET['customer_id']) && !empty($_GET['customer_id']))
			{
				$customer_id = pjObject::escapeString($_GET['customer_id']);
				$pjDocumentModel->where("t1.customer_id", $customer_id);
			}
			if (isset($_GET['template_id']) && !empty($_GET['template_id']))
			{
				$template_id = pjObject::escapeString($_GET['template_id']);
				$pjDocumentModel->where("t1.template_id", $template_id);
			}
			$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 = $pjDocumentModel->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;
			}

			$pjCustomerTokenModel = pjCustomerTokenModel::factory();
			$data = $pjDocumentModel
				->select("t1.*, t2.title AS template,
						  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.customer_id AND TCT.token_id=1) AS first_name,
					  	  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.customer_id AND TCT.token_id=2) AS last_name")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			foreach($data as $k => $v)
			{
				$name_arr = array();
				if(!empty($v['first_name']))
				{
					$name_arr[] = $v['first_name'];
				}
				if(!empty($v['last_name']))
				{
					$name_arr[] = $v['last_name'];
				}
				$v['name'] = join(' ', $name_arr);
				$v['hash'] = sha1($v['id'].$v['created'].PJ_SALT);
				$v['created'] = date($this->option_arr['o_date_format'], strtotime($v['created'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['created']));
				$data[$k] = $v;
			}

			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$pjCustomerTokenModel = pjCustomerTokenModel::factory();
			$template_arr = pjTemplateModel::factory()
				->where('t1.status', 'T')
				->findAll()
				->getData();
			$customer_arr = pjCustomerModel::factory()
				->select("t1.*,
						  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.id AND TCT.token_id=1) AS first_name,
					  	  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.id AND TCT.token_id=2) AS last_name")
				->where('t1.status', 'T')
				->orderBy("first_name ASC, last_name ASC")
				->findAll()
				->getData();
			
			$this->set('template_arr', $template_arr);
			$this->set('customer_arr', $customer_arr);
			
			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminDocuments.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$pjDocumentModel = pjDocumentModel::factory();
			if (isset($_POST['document_update']))
			{
				$arr = $pjDocumentModel->find($_POST['id'])->getData();
				
				$data = array();
				$data['document_id'] = $_POST['id'];
				$data['title'] = $arr['title'];
				$data['content'] = $arr['content'];
				$data['ip'] = pjUtil::getClientIp();
				$data['modified'] = date('Y-m-d H:i:s');
				$data['user_id'] = $this->getUserId();
				
				pjHistoryModel::factory($data)->insert();
				
				$pjDocumentModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, array('modified' => date('Y-m-d H:i:s'))));
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminDocuments&action=pjActionIndex&err=AD01");
				
			} else {
				$pjCustomerTokenModel = pjCustomerTokenModel::factory();
				
				$arr = $pjDocumentModel
					
					->select("t1.*, t2.title AS template, 
							(SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.customer_id AND TCT.token_id=1) AS first_name,
						  	(SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.customer_id AND TCT.token_id=2) AS last_name,
							(SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.customer_id AND TCT.token_id=3) AS email,
							(SELECT COUNT(TH.document_id) FROM `".pjHistoryModel::factory()->getTable()."` AS TH WHERE TH.document_id=t1.id) AS changes")
					->join('pjTemplate', 't1.template_id=t2.id', 'left')
					->find($_GET['id'])
					->getData();
					
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminDocuments&action=pjActionIndex&err=AD08");
				}
				
				$this->set('arr', $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('pjAdminDocuments.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionPreview()
	{
		$this->setLayout('pjActionEmpty');
			
		if (isset($_GET['hash']) && isset($_GET['id']))
		{
			$arr = pjDocumentModel::factory()
				->find($_GET['id'])
				->getData();
			if(!empty($arr))
			{
				$hash = sha1($arr['id'] . $arr['created'] . PJ_SALT);
				if ($_GET['hash'] != $hash)
				{
					$this->set('status', 3);
				}else{
					$this->set('arr', $arr);
				}
			}else{
				$this->set('status', 4);
			}
		}else{
			$this->set('status', 1);
		}
	}
	
	public function pjActionHistory()
	{
		$this->checkLogin();
	
		if ($this->isAdmin() || $this->isEditor())
		{
			$arr = pjDocumentModel::factory()
				->findAll()
				->getData();
			$this->set('arr', $arr);
			
			$template_arr = pjTemplateModel::factory()
				->where('t1.status', 'T')
				->findAll()
				->getData();
				$this->set('template_arr', $template_arr);

			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminDocuments.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetHistory()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjHistoryModel = pjHistoryModel::factory()
				->join('pjDocument', 't2.id=t1.document_id', 'left')
				->join('pjUser', 't3.id=t1.user_id', 'left');
			
			if($this->isEditor())
			{
				$pjHistoryModel->where('t1.user_id', $this->getUserId());
			}
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjHistoryModel->where('t2.title LIKE', "%$q%");
				$pjHistoryModel->orWhere('t2.content LIKE', "%$q%");
			}
			if (isset($_GET['document_id']) && !empty($_GET['document_id']))
			{
				$document_id = pjObject::escapeString($_GET['document_id']);
				$pjHistoryModel->where("t1.document_id", $document_id);
			}
			if (isset($_GET['template_id']) && !empty($_GET['template_id']))
			{
				$template_id = pjObject::escapeString($_GET['template_id']);
				$pjHistoryModel->where("(t1.document_id IN (SELECT TD.id FROM `".pjDocumentModel::factory()->getTable()."` AS TD WHERE TD.template_id='$template_id'))");
			}
	
			$column = 'modified';
			$direction = 'DESC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
	
			$total = $pjHistoryModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 20;
			$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;
			}
			$pjCustomerTokenModel = pjCustomerTokenModel::factory();
			$data = $pjHistoryModel
				->select("t1.*, t3.name AS user_name, 
						  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t2.customer_id AND TCT.token_id=1) AS first_name,
						  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t2.customer_id AND TCT.token_id=2) AS last_name")
				->orderBy("`$column` $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			foreach($data as $k => $v)
			{
				$name_arr = array();
				if(!empty($v['first_name']))
				{
					$name_arr[] = $v['first_name'];
				}
				if(!empty($v['last_name']))
				{
					$name_arr[] = $v['last_name'];
				}
				$v['name'] = join(' ', $name_arr);
				$v['modified'] = pjUtil::formatDate(date('Y-m-d', strtotime($v['modified'])), 'Y-m-d', $this->option_arr['o_date_format']) . ', ' . pjUtil::formatTime(date('H:i:s', strtotime($v['modified'])), 'H:i:s', $this->option_arr['o_time_format']);
				$data[$k] = $v;
			}
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionDeleteHistory()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			if ( pjHistoryModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteHistoryBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjHistoryModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionView()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = pjHistoryModel::factory()
				->find($_GET['id'])
				->getData();

			$this->set('arr', $arr);
		}
	}
	
	public function pjActionRestore()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if(isset($_GET['id']) && $_GET['document_id'])
			{
				$arr = pjHistoryModel::factory()->find($_GET['id'])->getData();
				pjDocumentModel::factory()->where('id', $_GET['document_id'])->limit(1)->modifyAll(array('content' => $arr['content']));
			}
		}
		exit;
	}
	
	public function pjActionSend()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if ($_POST['customer_email'] && !empty($_POST['customer_email'])
				&& $_POST['subject'] && !empty($_POST['subject'])
				&& $_POST['message'] && !empty($_POST['message']))
			{
				$Email = new pjEmail();
				$Email
					->setContentType('text/html')
					->setTo($_POST['customer_email'])
					->setFrom($this->getAdminEmail())
					->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'])
					;
				}
				
				if ($Email->send($_POST['message']))
				{
					$response['code'] = 200;
				} else {
					$response['code'] = 100;
				}
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDownload()
	{
		$this->setLayout('pjActionEmpty');
			
		if (isset($_GET['hash']) && isset($_GET['id']))
		{
			$arr = pjDocumentModel::factory()
				->find($_GET['id'])
				->getData();
			if(!empty($arr))
			{
				$hash = sha1($arr['id'] . $arr['created'] . PJ_SALT);
				if ($_GET['hash'] != $hash)
				{
					$this->set('status', 3);
				}else{
					$this->set('arr', $arr);
				}
			}else{
				$this->set('status', 4);
			}
		}else{
			$this->set('status', 1);
		}
	}
}
?>