<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminQuestions 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('pjAdminQuestions.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetQuestion()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjQuestionModel = pjQuestionModel::factory()
				->join('pjUser', "t2.id=t1.user_id", 'left outer')
				->join('pjCategory', "t3.id=t1.category_id", 'left outer');
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjQuestionModel->where('t1.question LIKE', "%$q%");
				$pjQuestionModel->orWhere('t1.description LIKE', "%$q%");
			}
			if (isset($_GET['category_id']) && !empty($_GET['category_id']))
			{
				$category_id = pjObject::escapeString($_GET['category_id']);
				$pjQuestionModel->where('t1.category_id', $category_id);
			}
			if (isset($_GET['user_id']) && !empty($_GET['user_id']))
			{
				$user_id = pjObject::escapeString($_GET['user_id']);
				$pjQuestionModel->where('t1.user_id', $user_id);
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('New','Approved','Banned')))
			{
				$pjQuestionModel->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 = $pjQuestionModel->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 = $pjQuestionModel
				->select("
							t1.id, t3.name AS category, t1.user_id,  
							IF(user_id IS NULL, t1.name, t2.name) as name,
							IF(user_id IS NULL, t1.email, t2.email) as email,
							t1.question, t1.counts, t1.created, t1.status,
							(SELECT COUNT(TR.id) FROM `".pjReplyModel::factory()->getTable()."` AS TR WHERE TR.question_id=t1.id) AS cnt_replies						
						")
				->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']));
				$v['counts'] = floatval($v['counts']);
				$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['question_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['email'] = ':NULL';
					unset($_POST['name']);
					unset($_POST['email']);
				}else if($_POST['posted_by'] == 'unregistered'){
					$data['user_id'] = ':NULL';
					unset($_POST['user_id']);
				}
				$id = pjQuestionModel::factory()->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AQ03';
				} else {
					$err = 'AQ04';
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminQuestions&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('pjAdminQuestions.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteQuestion()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			if (pjQuestionModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$pjReplyModel = pjReplyModel::factory();
				
				$reply_id_arr = $pjReplyModel->where('t1.question_id', $_GET['id'])->findAll()->getDataPair(null, 'id');
				
				if(!empty($reply_id_arr))
				{
					$pjReplyModel->reset()->whereIn('id', $reply_id_arr)->eraseAll();
					pjVoteModel::factory()->whereIn('reply_id', $reply_id_arr)->eraseAll();
				}
				
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteQuestionBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjQuestionModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				
				$pjReplyModel = pjReplyModel::factory();
				$reply_id_arr = $pjReplyModel->whereIn('t1.question_id', $_POST['record'])->findAll()->getDataPair(null, 'id');
				
				if(!empty($reply_id_arr))
				{
					$pjReplyModel->reset()->whereIn('id', $reply_id_arr)->eraseAll();
					pjVoteModel::factory()->whereIn('reply_id', $reply_id_arr)->eraseAll();
				}
			}
		}
		exit;
	}
	
	public function pjActionExportQuestion()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjQuestionModel::factory()
				->select("
							t1.id, t3.name AS category, 
							IF(user_id IS NULL, t1.name, t2.name) as name,
							IF(user_id IS NULL, t1.email, t2.email) as email,
							t1.question, t1.counts, t1.created, t1.status						
						")
				->join('pjUser', "t2.id=t1.user_id", 'left outer')
				->join('pjCategory', "t3.id=t1.category_id", 'left outer')
				->whereIn('t1.id', $_POST['record'])
				->findAll()
				->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Questions-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionSaveQuestion()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			pjQuestionModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionStatusQuestion()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjQuestionModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$pjQuestionModel = pjQuestionModel::factory();
			
			if (isset($_POST['question_update']))
			{
				$arr = $pjQuestionModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminQuestions&action=pjActionIndex&err=AQ08");
				}
				$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']);
				}
				$pjQuestionModel->reset()->set('id', $_POST['id'])->modify(array_merge($_POST, $data));
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminQuestions&action=pjActionIndex&err=AQ01");
			} else {
				
				$arr = $pjQuestionModel
					->select("t1.*, (SELECT COUNT(TR.id) FROM `".pjReplyModel::factory()->getTable()."` AS TR WHERE TR.question_id=t1.id) AS cnt_replies")
					->find($_GET['id'])
					->getData();
				
				if (count($arr) === 0)
				{
					pjUtil::redirect(sprintf("%s?controller=pjAdminQuestions&action=pjActionIndex&err=%s", $_SERVER['PHP_SELF'], 'AQ08'));
				}
				$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('pjAdminQuestions.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionView()
	{
		$this->setLayout('pjActionConfirm');
		
		if (isset($_GET['hash']) && isset($_GET['id']))
		{
			$arr = pjQuestionModel::factory()
				->select("
							t1.id, t3.name AS category, t1.user_id,
							IF(user_id IS NULL, t1.name, t2.name) as name,
							IF(user_id IS NULL, t1.email, t2.email) as email,
							t1.question, t1.description, t1.created, t1.status
						")
				->join('pjUser', "t2.id=t1.user_id", 'left outer')
				->join('pjCategory', "t3.id=t1.category_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']))
		{
			$pjQuestionModel = pjQuestionModel::factory();
			$question_arr = $pjQuestionModel->find($_POST['id'])->getData();
			if (count($question_arr) > 0)
			{
				$sql = "UPDATE `".$pjQuestionModel->getTable()."` SET status = 'Approved' WHERE SHA1(CONCAT(`id`, '".PJ_SALT."')) = '" . $_POST['hash'] . "'";
					
				$pjQuestionModel->reset()->execute($sql);
			
				$arr = $pjQuestionModel
					->reset()
					->find($_POST['id'])
					->getData();
			
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjAdminQuestions&action=pjActionApprove&err=200');
			}
		}else{
			if (isset($_GET['hash']) && isset($_GET['id']))
			{
				$arr = pjQuestionModel::factory()
					->select("
								t1.id, t3.name AS category, t1.user_id,
								IF(user_id IS NULL, t1.name, t2.name) as name,
								IF(user_id IS NULL, t1.email, t2.email) as email,
								t1.question, t1.description, t1.created, t1.status
							")
					->join('pjUser', "t2.id=t1.user_id", 'left outer')
					->join('pjCategory', "t3.id=t1.category_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);
			}
		}
	}
}
?>