<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminReplies extends pjAdmin
{
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$this->set('category_arr', pjCategoryModel::factory()->where('t1.status', 'T')->orderBy("name ASC")->findAll()->getData());
			
			$this->appendJs('chosen.jquery.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('pjAdminReplies.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetReply()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjReplyModel = pjReplyModel::factory()
				->join('pjUser', "t2.id=t1.user_id", 'left outer')
				->join('pjCategory', "t3.id=t1.category_id", 'left outer')
				->join('pjQuestion', "t4.id=t1.question_id", 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjReplyModel->where('t1.reply LIKE', "%$q%");
				$pjReplyModel->orWhere('t1.description LIKE', "%$q%");
			}
			if (isset($_GET['category_id']) && !empty($_GET['category_id']))
			{
				$category_id = pjObject::escapeString($_GET['category_id']);
				$pjReplyModel->where('t1.category_id', $category_id);
			}
			if (isset($_GET['question_id']) && !empty($_GET['question_id']))
			{
				$question_id = pjObject::escapeString($_GET['question_id']);
				$pjReplyModel->where('t1.question_id', $question_id);
			}
			if (isset($_GET['user_id']) && !empty($_GET['user_id']))
			{
				$user_id = pjObject::escapeString($_GET['user_id']);
				$pjReplyModel->where('t1.user_id', $user_id);
			}
			
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('New','Approved','Banned','Reported')))
			{
				if($_GET['status'] == 'Reported')
				{
					$pjReplyModel->where('t1.report', '1');
				}else{
					$pjReplyModel->where('t1.status', $_GET['status']);
				}
			}
				
			$column = 'created';
			$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 = $pjReplyModel->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 = array();
			
			$data = $pjReplyModel
				->select("
							t1.id, t1.question_id, t3.name AS category, t4.question, 
							IF(t1.user_id IS NULL, t1.name, t2.name) as name,
							IF(t1.user_id IS NULL, t1.email, t2.email) as email,
							t1.likes, t1.dislikes, t1.created, t1.status, t1.report,
							(IF(CHAR_LENGTH(t1.description) >= 60, CONCAT(SUBSTRING(t1.description, 1, 60), ' ...'), t1.description)) as description
						")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()->getData();
			foreach($data as $k => $v)
			{
				$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 pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['reply_create']))
			{
				$data = array();
				$data['created'] = date('Y-m-d H:i:s');
				$data['ip'] = pjUtil::getClientIp();
				if($_POST['posted_by'] == 'registered')
				{
					$data['name'] = ':NULL';
					$data['name'] = ':NULL';
					unset($_POST['name']);
					unset($_POST['email']);
				}else if($_POST['posted_by'] == 'unregistered'){
					$data['user_id'] = ':NULL';
					unset($_POST['user_id']);
				}
				
				$id = pjReplyModel::factory()->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AR03';
				} else {
					$err = 'AR04';
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminReplies&action=pjActionIndex&id=" . $id . "&err=$err");
			} else {
				
				$this->set('category_arr', pjCategoryModel::factory()->where('t1.status', 'T')->orderBy("name ASC")->findAll()->getData());
				$this->set('user_arr', pjUserModel::factory()->where('t1.status', 'T')->orderBy("name ASC")->findAll()->getData());
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminReplies.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteReply()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			if (pjReplyModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjVoteModel::factory()->where("reply_id", $_GET['id'])->eraseAll();
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteReplyBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjReplyModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjVoteModel::factory()->whereIn("reply_id", $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionSaveReply()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			pjReplyModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionStatusReply()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjReplyModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$pjReplyModel = pjReplyModel::factory();
			
			if (isset($_POST['reply_update']))
			{
				$arr = $pjReplyModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminReplies&action=pjActionIndex&err=AR08");
				}
				$data = array();
				$data['ip'] = pjUtil::getClientIp();
				$data['modified'] = date('Y-m-d H:i:s');
				if($_POST['posted_by'] == 'registered')
				{
					$data['name'] = ':NULL';
					$data['name'] = ':NULL';
					unset($_POST['name']);
					unset($_POST['email']);
				}else if($_POST['posted_by'] == 'unregistered'){
					$data['user_id'] = ':NULL';
					unset($_POST['user_id']);
				}
				if(!isset($_POST['report']))
				{
					$data['report'] = '0';
				}
				$pjReplyModel->reset()->set('id', $_POST['id'])->modify(array_merge($_POST, $data));
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminReplies&action=pjActionIndex&err=AR01");
			} else {
				
				$arr = $pjReplyModel
					->select("t1.*, t3.name AS category, t4.question")
					->join('pjUser', "t2.id=t1.user_id", 'left outer')
					->join('pjCategory', "t3.id=t1.category_id", 'left outer')
					->join('pjQuestion', "t4.id=t1.question_id", 'left outer')
					->find($_GET['id'])
					->getData();
				
				if (count($arr) === 0)
				{
					pjUtil::redirect(sprintf("%s?controller=pjAdminReplies&action=pjActionIndex&err=%s", $_SERVER['PHP_SELF'], 'AR08'));
				}
				
				if(!empty($arr['category_id']))
				{
					$question_arr = pjQuestionModel::factory()
						->where('t1.category_id', $arr['category_id'])
						->where('t1.status <>', 'Banned')
						->orderBy("t1.created DESC")
						->findAll()
						->getData();
					$this->set('question_arr', $question_arr);
				}
				if(!empty($arr['question_id']))
				{
					$reply_arr = $pjReplyModel
						->reset()
						->select("t1.id, (IF(CHAR_LENGTH(t1.description) >= 60, CONCAT(SUBSTRING(t1.description, 1, 60), ' ...'), t1.description)) as description")
						->where('t1.question_id', $arr['question_id'])
						->where('t1.status <>', 'Banned')
						->where('t1.id <>', $arr['id'])
						->orderBy("t1.created DESC")
						->findAll()
						->getData();
					$this->set('reply_arr', $reply_arr);
				}
				
				$this->set('arr', $arr);
				
				$this->set('category_arr', pjCategoryModel::factory()->where('t1.status', 'T')->orderBy("name ASC")->findAll()->getData());
				$this->set('user_arr', pjUserModel::factory()->where('t1.status', 'T')->orderBy("name ASC")->findAll()->getData());
				
				$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminReplies.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetQuestions()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$question_arr = pjQuestionModel::factory()
				->where('t1.category_id', $_GET['category_id'])
				->where('t1.status <>', 'Banned')
				->orderBy("t1.created DESC")
				->findAll()
				->getData();
			$this->set('question_arr', $question_arr);
		}
	}
	
	public function pjActionGetReplies()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$reply_arr = pjReplyModel::factory()
				->select("t1.id, (IF(CHAR_LENGTH(t1.description) >= 60, CONCAT(SUBSTRING(t1.description, 1, 60), ' ...'), t1.description)) as description")
				->where('t1.question_id', $_GET['question_id'])
				->where('t1.status <>', 'Banned')
				->orderBy("t1.created DESC")
				->findAll()
				->getData();
			$this->set('reply_arr', $reply_arr);
		}
	}
	
	public function pjActionReset()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() && $this->isLoged())
		{
			$response = array();
			
			pjVoteModel::factory()->where("reply_id", $_GET['id'])->eraseAll();
			$response['code'] = 200;
			
			pjAppController::jsonResponse($response);
		}
	}
	
	public function pjActionView()
	{
		$this->setLayout('pjActionConfirm');
	
		if (isset($_GET['hash']) && isset($_GET['id']))
		{
			$arr = pjReplyModel::factory()
				->select("
							t1.id, t1.question_id, t3.name AS category, t4.question,
							IF(t1.user_id IS NULL, t1.name, t2.name) as name,
							IF(t1.user_id IS NULL, t1.email, t2.email) as email,
							t1.likes, t1.dislikes, t1.created, t1.status, t1.report, t1.description
						")
				->join('pjUser', "t2.id=t1.user_id", 'left outer')
				->join('pjCategory', "t3.id=t1.category_id", 'left outer')
				->join('pjQuestion', "t4.id=t1.question_id", 'left outer')
				->find($_GET['id'])
				->getData();
			if (count($arr) == 0)
			{
				$this->set('status', 2);
			}else{
				$hash = sha1($arr['id'] . PJ_SALT);
				if ($_GET['hash'] != $hash)
				{
					$this->set('status', 3);
				}else{
	
					$this->set('arr', $arr);
				}
			}
		}else if (!isset($_GET['err'])) {
			$this->set('status', 1);
		}
	}
	
	public function pjActionApprove()
	{
		$this->setLayout('pjActionConfirm');
	
		if (isset($_POST['approve']))
		{
			$pjReplyModel = pjReplyModel::factory();
			$reply_arr = $pjReplyModel->find($_POST['id'])->getData();
			if (count($reply_arr) > 0)
			{
				$sql = "UPDATE `".$pjReplyModel->getTable()."` SET status = 'Approved' WHERE SHA1(CONCAT(`id`, '".PJ_SALT."')) = '" . $_POST['hash'] . "'";
					
				$pjReplyModel->reset()->execute($sql);
					
				$arr = $pjReplyModel
					->reset()
					->find($_POST['id'])
					->getData();
					
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjAdminReplies&action=pjActionApprove&err=200');
			}
		}else{
			if (isset($_GET['hash']) && isset($_GET['id']))
			{
				$arr = pjReplyModel::factory()
					->select("
								t1.id, t1.question_id, t3.name AS category, t4.question,
								IF(t1.user_id IS NULL, t1.name, t2.name) as name,
								IF(t1.user_id IS NULL, t1.email, t2.email) as email,
								t1.likes, t1.dislikes, t1.created, t1.status, t1.report, t1.description
							")
					->join('pjUser', "t2.id=t1.user_id", 'left outer')
					->join('pjCategory', "t3.id=t1.category_id", 'left outer')
					->join('pjQuestion', "t4.id=t1.question_id", 'left outer')
					->find($_GET['id'])
					->getData();
				if (count($arr) == 0)
				{
					$this->set('status', 2);
				}else{
					if ($arr['status'] == 'Approved')
					{
						$this->set('status', 4);
					}else{
						$hash = sha1($arr['id'] . PJ_SALT);
						if ($_GET['hash'] != $hash)
						{
							$this->set('status', 3);
						}else{
							$this->set('arr', $arr);
						}
					}
				}
			}else if (!isset($_GET['err'])) {
				$this->set('status', 1);
			}
		}
	}
}
?>