<?php

class AKB_RATING extends AdminView {

	/**
	* @var string $query The sql used to display the list of ratings
	*/
	var $query = "";

	/**
	* @var string $countQuery The sql used to work out the number of
	* ratings that running $this->query is going to display
	*/
	var $countQuery = "";
	var $defaultTableSort = "ratedat";
	
	function AKB_RATING() {
	
	}
	
	function HandlePage() {
		
		$todo = $_GET['ToDo'];
		
		switch ($todo) {
			default:
				if ($_SESSION['user']->verify('rating', 'edit')
				|| $_SESSION['user']->verify('rating', 'delete')) {
					if (isset($_POST['bulkaction'])) {
						$this->BulkAction();
					} else {
						$this->ShowRatingsList();
					}
				} else {
					$this->NoPermission();
				}				
		}
	}
	
	function ShowRatingsList() {
		// Check they have permission to be here
		if (!$_SESSION['user']->verify('rating', 'edit')
		&& !$_SESSION['user']->verify('rating', 'delete')) {
			$this->NoPermission();
			return;
		}
		
		$GLOBALS['RatingBulkOptions'] = "";
		
		if ($_SESSION['user']->verify('rating', 'delete')) {
			$GLOBALS['RatingBulkOptions'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('RatingBulkDeleteOptions');		
		}
		
		$this->BuildListQueries();
		$result = $GLOBALS['AKB_DB']->Query($this->countQuery);
		$this->numRecords = $GLOBALS['AKB_DB']->FetchOne($result);
		
		if ($this->numRecords == 0) {
			$GLOBALS['HideBulk'] = "none";	
			$GLOBALS['Message'] = MessageBox(GetLang('NoRatings'));
		} else {
		
		}
		
		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('rating.table');
		$GLOBALS['mainData'] = $GLOBALS['AKB_CLASS_TEMPLATE']->LoadTemplateFile(true);
		
		$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('rating.manage');
		$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
	}
	
	function ShowRatingsListRemote() {

		// Check they have permission to be here
		if (!$_SESSION['user']->verify('rating', 'edit')
		&& !$_SESSION['user']->verify('rating', 'delete')) {
			$this->NoPermission();
			return;
		}
		
		$page = 0;
		$start = 0;
		$numComments = 0;
		$numpages = 0;
		
		$todo = $_GET['todo'];
		$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
		
		$sortVars = array("ratedat","ratingmessage","ratingemail");
		
		$sortTableArray = $this->SetupSortingParams($sortVars,$todo,$page);
		
		$this->InitAdvancedSearch();

		$GLOBALS['SearchQuery'] = @$_SESSION['rating_search']['q'];

		$this->BuildListQueries();
		
		$ratingResult = $GLOBALS['AKB_DB']->Query($this->query);
		
		//Set pagination information.
		$this->SetupPaginationLink("ShowRatingsListRemote","d","ratedat");
		$this->SetupPagination($this->countQuery,$page,AKB_RATING_PER_PAGE);

		
		
		if ($GLOBALS['AKB_DB']->CountResult($this->query)) {
			$adminTable = new AKB_AdminTable();

			$GLOBALS['TableIconImagePath'] = "images/unhelpful.gif";

			$adminTable->headingArray['ratingmessage'] 	= GetLang("RatingMessage");
			$adminTable->headingArray['ratingemail'] 	= GetLang("RatingEmail");
			$adminTable->headingArray['title'] 			= GetLang("Question");
			$adminTable->headingArray['ip'] 			= GetLang("IPAddress");
			$adminTable->headingArray['ratedat'] 		= GetLang("RatingDate");
			$adminTable->headingArray['action'] 		= GetLang("Action");
			
			$adminTable->sizeArray						= array("15%","15%","20%","10%","10%");
			$adminTable->sortArray 						= $sortTableArray;
			
			$adminTable->prependDataID 					= "rateid";
			
			$adminTable->addCallback("url",			"GetUrl",array("question","__questionid__"));
			$adminTable->addCallback("unixdate",	"strtotime",array("__ratedat__"));
			$adminTable->addCallback("ratedat",		"date",array("jS F Y","__unixdate__"));
			$adminTable->addCallback("action",		"","");
			$adminTable->addCallback("ratingmessage","htmlspecialchars",array("__ratingmessage__",ENT_QUOTES,$GLOBALS['charset']));
//			$adminTable->addCallback("ratingemail","htmlspecialchars",array("__ratingemail__",ENT_QUOTES,$GLOBALS['charset']));
			$adminTable->addCallback("title","htmlspecialchars",array("__title__",ENT_QUOTES,$GLOBALS['charset']));
			$adminTable->addCallback("ratingemail", array($this, "ReturnEmailCell"), array("__ratingemail__", "__title__"));

			
			$adminTable->tableIdent = "ShowRatingsListRemote";
			
			$adminTable->addTemplateOverride("title","admintable.cell.link",array("__url__","__title__"));
			$adminTable->addTemplateOverride("action","rating.cell.delete",array("__rateid__",GetLang("RatingDeleteConfirm"),GetLang('Delete')));
			
			$adminTable->rsData = $ratingResult;
			
			echo $adminTable->ReturnTable();
			return;
		}

		if (isset($_SESSION['rating_search']['searching'])) {
			// No comments found when searching
			$GLOBALS['Title'] = GetLang('ManageQuestions');
			$GLOBALS['ManageQuestMessage'] = GetLang('ManageQuestMessage');
			$GLOBALS['ButtonText'] = GetLang('CreateQuestion');
			$GLOBALS['ButtonClass'] = 'Field150';
			$GLOBALS['Message'] = MessageBox(GetLang('NoCommentSearch'), MSG_WARNING);
			$GLOBALS['URL'] = 'index.php?ToDo=createQuestion';
			$GLOBALS['HideHeading'] = 'style="display:none"';
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('rating.manage');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		} else {
			$GLOBALS["Title"] = GetLang("ManageComments");
			$GLOBALS["Style"] = "display:none";
			$GLOBALS["ButtonClass"] = "Field150";
			$GLOBALS["Message"] = MessageBox(GetLang("NoComments"), MSG_SUCCESS);
			$GLOBALS["URL"] = "index.php?ToDo=createQuestion";
		}
	}
	
	function BulkAction() {
		if (!isset($_POST['bulkaction'])) {
			return false;
		}

		if (!isset($_POST['item']) || !is_array($_POST['item'])) {
			return false;
		}
		
		$rAPI = new API_RATING();
		switch (strtolower($_POST['bulkaction'])) {
			case "delete":
				if ($_SESSION['user']->verify('rating', 'delete')) {
					//Delete them all.
					if ($rAPI->multiDelete($_POST['item'])) {
						$GLOBALS['Message'] = MessageBox(GetLang('RatingDeleteOk'), MSG_SUCCESS);
					} else {
						$GLOBALS['Message'] = MessageBox(GetLang('RatingDeleteNotOk'), MSG_ERROR);
					}
					
					$this->ShowRatingsList();
				} else {
					$this->NoPermission();
				}
				
				break;
		
			default:
				trigger_error("Fatal Error: No Bulk Action.");
		}
	}
	
	function InitAdvancedSearch() {
	
	}
	
	function BuildListQueries() {

		$page = isset($_GET['page'])? (int) $_GET['page'] : 1;
		$start = ($page == 1) ? 0 : ($page * AKB_RATING_PER_PAGE) - (AKB_RATING_PER_PAGE-1) -1;
		
		$rating_table = $GLOBALS['tablePrefix']."ratings";
		$question_table = $GLOBALS['tablePrefix']."questions";

		$this->countQuery = "SELECT COUNT(rateid) as ratecount FROM ".$rating_table." ";

		$this->query = "SELECT r.rateid, q.title, q.questionid, r.ip, r.ratedat, r.ratingemail, r.ratingmessage ";
		$this->query .= "FROM ".$rating_table." r,".$question_table." q";
		
		$this->query .= " WHERE r.questionid = q.questionid ";
		
		//Init the search
		if (!empty($_SESSION['rating_search']['q'])) {
			$this->countQuery .= "AND (ratingemail like '%".$GLOBALS['AKB_DB']->Quote($_SESSION['rating_search']['q'])."%'";
			$this->countQuery .= " OR ratingmessage like '%".$GLOBALS['AKB_DB']->Quote($_SESSION['rating_search']['q'])."%')\n";
			$this->query .= "AND (ratingemail like '%".$GLOBALS['AKB_DB']->Quote($_SESSION['rating_search']['q'])."%'";
			$this->query .= " OR ratingmessage like '%".$GLOBALS['AKB_DB']->Quote($_SESSION['rating_search']['q'])."%')\n";
		}
		
		$this->query .= "ORDER BY r.".$this->sortField." ".$this->sortDirection."\n";
		$this->query .= $GLOBALS['AKB_DB']->AddLimit($start, AKB_RATING_PER_PAGE);
	}
	
	function ReturnEmailCell ($email, $articleTitle) {
		return '<a href="mailto:'.$email.'?subject='.sprintf(GetLang('FeedbackReplySubject').'">'.$email.'</a>', $articleTitle);
	}
}



?>