<?php
	require_once(dirname(__FILE__).'/../../../lib/api/class.glossary.php');
	require_once(dirname(__FILE__).'/class.adminview.php');

	class AKB_GLOSSARY extends AdminView
	{
		/**
		* HandlePage
		*
		* Handles page routing based on the current ToDo get string
		* @return void
		*/
		function HandlePage()
		{
			if (isset($_GET['ToDo'])) {
				switch (strtolower($_GET['ToDo'])) {
					case 'saveupdatedglossaryterm':
						if ($_SESSION['user']->verify('glossary', 'edit')) {
							$this->SaveUpdatedTerm();
						} else {
							$GLOBALS['AKB_CLASS_ENGINE']->NoPermission();
						}
						break;
					case 'editglossaryterm':
						if ($_SESSION['user']->verify('glossary', 'edit')) {
							$this->EditTerm();
						} else {
							$GLOBALS['AKB_CLASS_ENGINE']->NoPermission();
						}
						break;
					case 'deleteglossaryterm':
						if ($_SESSION['user']->verify('glossary', 'delete')) {
							$this->DeleteTerm();
						} else {
							$GLOBALS['AKB_CLASS_ENGINE']->NoPermission();
						}
						break;
					case 'savenewglossaryterm':
						if ($_SESSION['user']->verify('glossary', 'edit')) {
							$this->SaveNewTerm();
						} else {
							$GLOBALS['AKB_CLASS_ENGINE']->NoPermission();
						}
						break;
					case 'createglossaryterm':
						if ($_SESSION['user']->verify('glossary', 'edit')) {
							$this->ShowNewTerm();
						} else {
							$GLOBALS['AKB_CLASS_ENGINE']->NoPermission();
						}
						break;
					case 'viewglossary':
					default:
						if (isset($_POST['bulkaction'])) {
							$this->BulkAction();
						} else {
							$this->ShowTermList();
						}
				}
			}
		}

		/**
		* BulkAction
		*
		* The handler for performing an action to multiple items
		* @return void
		*/
		function BulkAction()
		{
			if (!isset($_POST['bulkaction'])) {
				$this->ShowTermList();
				return false;
			}

			if (!isset($_POST['item']) || !is_array($_POST['item'])) {
				$this->ShowTermList();
				return false;
			}

			if (empty($_POST['item'])) {
				$this->ShowTermList();
				return false;
			}

			$g = new API_GLOSSARY();
			switch (strtolower($_POST['bulkaction'])) {
				case 'delete':
					if ($_SESSION['user']->verify('glossary', 'delete')) {
						if ($g->multiDelete($_POST['item'])) {
							$this->ShowTermList(GetLang('GlossaryMultiDeleteOk'), MSG_SUCCESS);
						} else {
							$this->ShowTermList(GetLang('GlossaryMultiDeleteFail'), MSG_ERROR);
						}
					} else {
						$this->ShowTermList();
						return false;
					}
				break;
			}
		}
		/**
		* ShowNewTerm
		* Show the page to create a new glossary term
		*
		* @return void
		*/
		function ShowNewTerm()
		{
			if (!$_SESSION['user']->verify('glossary', 'edit')) {
				$this->NoPermission();
				return;
			}

			$GLOBALS['BreadcrumEntries'][GetLang("ManageGlossary")] = "index.php?ToDo=viewGlossary";
			$GLOBALS['BreadcrumEntries'][GetLang("AddGlossaryTitle")] = "";				

			
			$GLOBALS['FormAction'] = 'saveNewGlossaryTerm';
			$GLOBALS['GlossaryTitle'] = GetLang('AddGlossaryTitle');
			$GLOBALS['GlossaryIntro'] = GetLang('AddGlossaryIntro');
			$GLOBALS['GlossaryTerm'] = '';
			$GLOBALS['GlossaryDesc'] = '';
			$GLOBALS['hiddenFields'] = '';

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('glossary.form');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* SaveNewTerm
		* Save a new glossary term to the database
		*
		* @reutrn void
		*/
		function SaveNewTerm()
		{
			if (!$_SESSION['user']->verify('glossary', 'edit')) {
				$this->NoPermission();
				return;
			}

			$g = new API_GLOSSARY();

			if ($g->create()) {
				$this->ShowTermList(sprintf(GetLang('TermCreatedSuccessfully'), $_POST['word']), MSG_SUCCESS);
			} else {
				switch (mysql_errno()) {
					case '1062':
						$this->ShowTermList(sprintf(GetLang('TermAlreadyExists'), $_POST['word']), MSG_ERROR);
					break;
					default:
						$this->ShowTermList(sprintf(GetLang('TermNotCreated'), $_POST['word']), MSG_ERROR);
				}
			}
		}

		// {{{ ShowTermList($MsgDesc, $MsgStatus)
		/**
		* ShowTermList
		* Prints the list of glossary terms, paging them if necessary
		*
		* @param string MsgDesc
		* @param string MsgStatus
		*
		* @return void
		*/
		function ShowTermList($MsgDesc = "", $MsgStatus = "")
		{
			if (!$_SESSION['user']->verify('glossary', 'edit')
			&& !$_SESSION['user']->verify('glossary', 'delete')) {
				$this->NoPermission();
				return;
			}
			
			//Do the breadcrumbs
			$GLOBALS['BreadcrumEntries'][GetLang("ManageGlossary")] = "index.php?ToDo=viewGlossary";

			// Show a list of glossary terms that have been created
			// Show a list of users to edit/delete
			$GLOBALS["Grid"] = "";

			if ($_SESSION['user']->verify('glossary', 'edit')) {
				$GLOBALS['ShowCreateButton'] = 'inline';
			} else {
				$GLOBALS['ShowCreateButton'] = 'none';
			}

			if ($_SESSION['user']->verify('glossary', 'delete')) {
				$GLOBALS['ShowDeleteButton'] = 'inline';
			} else {
				$GLOBALS['ShowDeleteButton'] = 'none';
			}

			// {{{ Setup our paging
			// What page are we on ?
			$page = isset($_GET['page'])? (int) $_GET['page'] : 1;

			// What is our offset in the results for the start ?
			$start = ($page == 1) ? 0 : ($page * AKB_GLOSSARY_PER_PAGE) - (AKB_GLOSSARY_PER_PAGE-1) -1;

			// How many search terms do we have in total ?
			if (isset($_GET["letter"])) {
				$fromStartWith = $_GET["letter"];
				$toStartWith = $_GET["letter"];
				$startWithHelper = explode('-', $_GET["letter"]);
				if (sizeof($startWithHelper) > 1) {
					$fromStartWith = $startWithHelper[0];
					$toStartWith = $startWithHelper[1];
				}
				$query = "SELECT COUNT(*)"
				. " FROM ".$GLOBALS["tablePrefix"]."glossary"
				. " WHERE ".$GLOBALS['AKB_DB']->SubString('word', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'";
				
				$link = 'index.php?ToDo=viewGlossary&letter='.$_GET['letter'];
			} else {
				$query = "SELECT COUNT(*)
				FROM ".$GLOBALS["tablePrefix"]."glossary";
				$link = 'index.php?ToDo=viewGlossary';
			}
			$total = $GLOBALS['AKB_DB']->FetchOne($query);
			$numpages = ceil($total / AKB_GLOSSARY_PER_PAGE);

			$GLOBALS['Nav'] = BuildNav($link, $numpages, $page);
			// }}}

			// {{{ Build the alpha list (A-Z box list)
			$GLOBALS['FormAction'] = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=viewGlossary';
			$GLOBALS['AlphaList'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListHeader');
			$GLOBALS["Item"] = 'glossary';
			$letters = GetAlphaList();
			foreach ($letters as $letter) {
				$GLOBALS['Letter'] = $letter;
				$GLOBALS['TermClickLetter'] = sprintf(GetLang("TermClickLetter"), strtolower(GetLang('GlossaryTerms')), $letter);
				if (isset($_GET['letter']) && $letter == $_GET['letter']) {
					$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListRowCurrent');
				} else {
					$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListRow');
				}
			}
			$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListFooter');
			// }}

			if (isset($_GET["letter"])) {
				
				$fromStartWith = $_GET["letter"];
				$toStartWith = $_GET["letter"];
				$startWithHelper = explode('-', $_GET["letter"]);
				if (sizeof($startWithHelper) > 1) {
					$fromStartWith = $startWithHelper[0];
					$toStartWith = $startWithHelper[1];
				}
				
				$query = "SELECT *
					FROM ".$GLOBALS["tablePrefix"]."glossary"
					. " WHERE ".$GLOBALS['AKB_DB']->SubString('word', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'"
					. " ORDER BY word ASC "
					.$GLOBALS['AKB_DB']->AddLimit($start, AKB_GLOSSARY_PER_PAGE);
			} else {
				$query = "SELECT *
				FROM ".$GLOBALS["tablePrefix"]."glossary
				ORDER BY word ASC
				".$GLOBALS['AKB_DB']->AddLimit($start, AKB_GLOSSARY_PER_PAGE);
			}

			$termResult = $GLOBALS['AKB_DB']->Query($query);

			if ($MsgDesc != '') {
				$GLOBALS["Message"] = MessageBox($MsgDesc, $MsgStatus);
			} else {
				$GLOBALS['Message'] = '';
			}

			if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
				while ($termRow = $GLOBALS['AKB_DB']->Fetch($termResult)) {
					$GLOBALS['TermId'] = $termRow['glossaryid'];
					$GLOBALS['Term'] = $termRow['word'];

					if ($_SESSION['user']->verify('glossary', 'edit')) {
						$GLOBALS['EditLink'] =  '<a href="index.php?ToDo=editGlossaryTerm&amp;termId='.$termRow['glossaryid'].'" class="bodylink">'.GetLang('Edit').'</a>';
					} else {
						$GLOBALS['EditLink'] = '<span class="Disabled">'.GetLang('Edit').'</span>';
					}

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('glossary.row');
					$GLOBALS['Grid'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
				}

				$GLOBALS['HideIntro'] = 'block';
				$GLOBALS['FormAction'] = 'index.php?ToDo=viewGlossary';
				$GLOBALS['HideList'] = 'block';

				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('glossary.manage');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			} else {
				if ($start == '') {
					// There aren't any terms, show a message so they can create some
					$GLOBALS['Title'] = GetLang('ManageGlossary');
					$GLOBALS['ButtonText'] = GetLang('CreateGlossaryTerm');
					$GLOBALS['ButtonClass'] = 'Field150';
					$GLOBALS['Message'] = MessageBox(GetLang('NoTerms'), MSG_SUCCESS);
					$GLOBALS['URL'] = 'index.php?ToDo=createGlossaryTerm';
					$GLOBALS['Style'] = '';

					$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("messagewithbutton");
					$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
				} else {
					$GLOBALS['HideIntro'] = 'none';
					$GLOBALS['HideList'] = 'none';
					$GLOBALS['Title'] = GetLang('ManageGlossary');
					$GLOBALS['ButtonText'] = GetLang('CreateGlossaryTerm');
					$GLOBALS['ButtonClass'] = 'Field150';
					$GLOBALS['Message'] = MessageBox(sprintf(GetLang('NoTermsForCharacter'), $start), MSG_SUCCESS);
					$GLOBALS['URL'] = 'index.php?ToDo=createGlossaryTerm';

					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('glossary.manage');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				}
			}
		}
		// }}}

		/**
		* DeleteTerm
		* Delete a glossary term from the database
		*
		* @return void
		*/
		function DeleteTerm()
		{
			if (!$_SESSION['user']->verify('glossary', 'delete')) {
				$this->NoPermission();
				return;
			}

			if (isset($_GET['termId'])) {
				$termId = $_GET['termId'];
				$query = sprintf("delete from %sglossary where glossaryid='%d'", $GLOBALS["tablePrefix"], $termId);

				if ($GLOBALS['AKB_DB']->Query($query)) {
					$this->ShowTermList(GetLang('TermDeletedSuccessfully'), MSG_SUCCESS);
				} else {
					$this->ShowTermList();
				}
			} else {
				$this->ShowTermList();
			}
		}

		/**
		* EditTerm
		* Show the pageto edit a glossary term
		*
		* @return void
		*/
		function EditTerm()
		{
			if (!$_SESSION['user']->verify('glossary', 'edit')) {
				$this->NoPermission();
				return;
			}

			if (isset($_GET['termId'])) {
				
				$GLOBALS['BreadcrumEntries'][GetLang("ManageGlossary")] = "index.php?ToDo=viewGlossary";
				$GLOBALS['BreadcrumEntries'][GetLang("UpdateGlossaryTitle")] = "";				
				
				$termId = $_GET['termId'];
				$g = new API_GLOSSARY();
				$g->load($_GET['termId']);

				if (!empty($g->word)) {
					$GLOBALS["FormAction"] = "saveUpdatedGlossaryTerm";
					$GLOBALS["hiddenFields"] = sprintf("<input type='hidden' name='termId' value='%d'>", $termId);
					$GLOBALS["GlossaryTitle"] = GetLang("UpdateGlossaryTitle");
					$GLOBALS["GlossaryIntro"] = GetLang("UpdateGlossaryIntro");
					$GLOBALS["GlossaryTerm"] = htmlspecialchars($g->word, ENT_QUOTES, $GLOBALS['charset']);
					$GLOBALS["GlossaryDesc"] = htmlspecialchars($g->description, ENT_QUOTES, $GLOBALS['charset']);

					$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("glossary.form");
					$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
				} else {
					$this->ShowTermList();
				}
			} else {
				$this->ShowTermList();
			}
		}

		/**
		* SaveUpdatedTerm
		* Update an existing glossary term in the database
		*
		* @return void
		*/
		function SaveUpdatedTerm()
		{
			if (!$_SESSION['user']->verify('glossary', 'edit')) {
				$this->NoPermission();
				return;
			}

			$g = new API_GLOSSARY();
			$g->load($_POST['termId']);

			if ($g->save()) {
				$this->ShowTermList(GetLang('TermSaved'), MSG_SUCCESS);
			} else {
				$this->ShowTermList(GetLang('TermNotSaved'), MSG_ERROR);
			}
		}
	}

?>