<?php

	require_once(dirname(__FILE__).'/class.adminview.php');

	class AKB_SUBSCRIBER extends AdminView
	{
		// {{{ Class Variables
		/**
		* The link prefix to give for the ShowList page
		* @var string
		*/
		var $ListAction = 'index.php?ToDo=viewSubscribers';

		/**
		* The default field to sort by, this must also be in the ValidSortFields
		* var defined later on
		* @var string
		*/
		var $DefaultSortField = 'email';

		/**
		* The default order to sort items in in the ShowList function
		* @var string either asc or desc
		*/
		var $DefaultSortOrder = 'asc';

		/**
		* The number of items to display per page in the ShowList function
		* @var integer
		*/
		var $ListPerPage = AKB_SUBSCRIBER_PER_PAGE;

		/**
		* Database fields that are valid for the user to be sorting by
		* @var array
		*/
		var $ValidSortFields = array (
			'email',
			'subscribedate',
		);
		// }}}

		/**
		* HandlePage
		*
		* Handles page routing based on the current ToDo get string
		* @return void
		*/
		function HandlePage()
		{
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')) {
				$this->NoPermission();
				return;
			}

			$GLOBALS['Message'] = '';

			if (isset($_GET['ToDo'])) {
				switch (strtolower($_GET['ToDo'])) {
					case 'viewgroups':
					default:
						if (isset($_POST['bulkaction'])) {
							$this->BulkAction();
						}
						$this->ShowList();
				}
			}
		}

		/**
		* BulkAction
		*
		* The handler for performing an action to multiple items
		* @return void
		*/
		function BulkAction()
		{
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')) {
				$this->NoPermission();
				return;
			}

			if (!isset($_POST['bulkaction'])) {
				return false;
			}

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

			if (empty($_POST['item'])) {
				return false;
			}
			$g = new API_SUBSCRIBER();
			switch (strtolower($_POST['bulkaction'])) {
				case 'delete':
					if ($g->multiDelete($_POST['item'])) {
						$GLOBALS['Message'] = MessageBox(GetLang('SubscriberMultiDeleteOk'), MSG_SUCCESS);
					} else {
						$GLOBALS['Message'] = MessageBox(GetLang('SubscriberMultiDeleteFail'), MSG_ERROR);
					}
				break;
			}
		}

		/**
		* ShowList
		*
		* Shows a list of subscribers with links to be able to do CRUD like
		* actions on them
		*
		* @return void
		*/
		function ShowList($MsgDesc = "", $MsgStatus = "")
		{
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')) {
				$this->NoPermission();
				return;
			}

			$GLOBALS['Grid'] = '';

			// {{{ Setup our sorting
			if (isset($_GET['sortField'])
				&& in_array($_GET['sortField'], $this->ValidSortFields)) {
					$sortField =  $GLOBALS['AKB_DB']->Quote($_GET['sortField']);
			} else {
				$sortField = $this->DefaultSortField;
			}

			if (isset($_GET['sortOrder']) && in_array($_GET['sortOrder'], array('asc', 'desc'))) {
				$sortOrder = $GLOBALS['AKB_DB']->Quote($_GET['sortOrder']);
			} else {
				$sortOrder = $this->DefaultSortOrder;
			}
			// }}}

			// {{{ Setup our paging
			// What page are we on ?
			if (isset($_GET['page']) && (int) $_GET['page'] > 0) {
				$page = (int) $_GET['page'];
			} else {
				$page = 1;
			}

			// What is our offset in the results for the start ?
			if ($page == 1) {
				$start = 0;
			} else {
				$start =  $page * $this->ListPerPage - $this->ListPerPage ;
			}
			// 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"]."subscribers"
					. " WHERE ".$GLOBALS['AKB_DB']->SubString('email', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'";
				$link = $this->ListAction.'&letter='.$_GET['letter'];
			} else {
				$query = "SELECT COUNT(*)
				FROM ".$GLOBALS["tablePrefix"]."subscribers";
				$link = $this->ListAction;
			}
			$total = $GLOBALS['AKB_DB']->FetchOne($query);
			$numpages = ceil($total / $this->ListPerPage);

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

			// {{{ Build the alpha list (A-Z box list)
			$GLOBALS['FormAction'] = $GLOBALS['pathToKB'].'/admin/'.$this->ListAction;
			$GLOBALS["AlphaList"] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListHeader');
			$GLOBALS["Item"] = 'article subscribers with email';
			$letters = GetAlphaList();
			foreach ($letters as $letter) {
				$GLOBALS['Letter'] = $letter;
				$GLOBALS['TermClickLetter'] = sprintf(GetLang("TermClickLetter"), strtolower(GetLang('Subscribers')), $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 email, subscriberid, subscribedate, s.questionid, title, confirmed
					FROM ".$GLOBALS["tablePrefix"]."subscribers s LEFT JOIN ".$GLOBALS['tablePrefix']."questions q
					ON s.questionid = q.questionid "
					. " WHERE ".$GLOBALS['AKB_DB']->SubString('email', 1, 1)." between '".$GLOBALS['AKB_DB']->Quote($fromStartWith)."' AND '".$GLOBALS['AKB_DB']->Quote($toStartWith)."'"
					. " ORDER BY $sortField $sortOrder
					".$GLOBALS['AKB_DB']->AddLimit($start, $this->ListPerPage);
			} else {
				$query = "SELECT email, subscriberid, subscribedate, s.questionid, title, confirmed
				FROM ".$GLOBALS["tablePrefix"]."subscribers s LEFT JOIN ".$GLOBALS['tablePrefix']."questions q
				ON s.questionid = q.questionid
				ORDER BY $sortField $sortOrder
				".$GLOBALS['AKB_DB']->AddLimit($start, $this->ListPerPage);
			}

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

			if (!empty($MsgDesc)) {
				$GLOBALS["Message"] = MessageBox($MsgDesc, $MsgStatus);
			}
			
			$GLOBALS['BreadcrumEntries'][GetLang("ManageSubscribers")] = "";			

			if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
				while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					$GLOBALS["SubscriberId"] = $row['subscriberid'];

					if (trim($row["email"]) == "") {
						$GLOBALS["Email"] = GetLang("NA");
					} else {
						$GLOBALS["Email"] = $row["email"];
					}

					$GLOBALS['SubscribeDate'] = date('j F Y', strtotime($row['subscribedate']));

					if (!empty($row['title'])) {
						$GLOBALS['Href'] = GetUrl('question', $row['questionid']);
						$GLOBALS['Text'] = htmlspecialchars(ellipsize($row['title'], 75), ENT_QUOTES, $GLOBALS['charset']);
						$GLOBALS['QuestionTitle'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');
					} else {
						$GLOBALS['QuestionTitle'] = GetLang('QuestionNoLongerExists');
					}

					if ($row["confirmed"] == 0) {
						$GLOBALS["Confirmed"] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('Cross');
					} else {
						$GLOBALS["Confirmed"] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('Tick');
					}

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

				$GLOBALS['SubscribeDateSortUpLink'] = $this->ListAction.'&sortField=subscribedate&sortOrder=asc';
				$GLOBALS['SubscribeDateSortDownLink'] = $this->ListAction.'&sortField=subscribedate&sortOrder=desc';
				$GLOBALS['EmailSortUpLink'] = $this->ListAction.'&sortField=email&sortOrder=asc';
				$GLOBALS['EmailSortDownLink'] = $this->ListAction.'&sortField=email&sortOrder=desc';

				$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("subscriber.manage");
				$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
			} else {
				$GLOBALS["Title"] = GetLang("ManageSubscribers");
				$GLOBALS["Message"] = MessageBox(GetLang("NoSubscribers"), MSG_SUCCESS);

				$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("message");
				$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
			}
		}

		/**
		* Display the screen for editing a subscriber
		*
		* return @void
		*/
		function ShowEdit()
		{
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')) {
				$this->NoPermission();
				return;
			}

			$sub = new API_SUBSCRIBER();
			$sub->load((int) $_GET['subscriberid']);

			if ($sub->loaded) {

				// Make sure the question they are subscribed to exists
				$q = new API_QUESTION();
				$q->load($sub->questionid);
				if ($q->loaded) {
					$GLOBALS['Href'] = GetUrl('question', $sub->questionid);
					$GLOBALS['Text'] = $q->title;
					$GLOBALS['QuestionLink'] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('LinkNewWindow');
				} else {
					$GLOBALS['QuestionLink'] = GetLang('QuestionNoLongerExists');
				}

				$GLOBALS['Email'] = $sub->email;
				$GLOBALS['Confirmed'] = $sub->confirmed;

				if ($sub->confirmed) {
					$GLOBALS['Active_1'] = 'selected';
				} else {
					$GLOBALS['Active_0'] = 'selected';
				}

				$GLOBALS['SubscribeDate'] = date('j F Y', strtotime($sub->subscribedate));
				$GLOBALS['SubscriberId'] = $sub->subscriberid;

				$GLOBALS["FormAction"] = "updateSubscriber";
				$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("subscriber.form");
				$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
			} else {
				$this->ShowList();
			}
		}

		/**
		* Delete
		*
		* Delete the entry and show the confirmation/error message
		*
		* @return void
		*/
		function Delete()
		{
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')) {
				$this->NoPermission();
				return;
			}

			if (isset($_GET['subscriberid'])
				&& (int) $_GET['subscriberid'] > 0) {
				$sub = new API_SUBSCRIBER();
				if ($sub->delete((int) $_GET['subscriberid'])) {
					$this->ShowList(GetLang('questUnsubscribeSuccessSingle'), MSG_SUCCESS);
				} else {
					$this->ShowList(GetLang('questUnsubscribeFailed'), MSG_ERROR);
				}
			} else {
				$this->ShowList();
			}
		}

		/**
		* Update
		*
		* Update the entry and show the confirmation/error message
		*
		* @return void
		*/
		function Update()
		{
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')) {
				$this->NoPermission();
				return;
			}

			if (isset($_POST['subscriberid'])
				&& (int) $_POST['subscriberid'] > 0) {
				$sub = new API_SUBSCRIBER();
				$sub->load((int) $_POST['subscriberid']);
				if ($sub->save()) {
					$this->ShowList(GetLang('SubscriberUpdated'), MSG_SUCCESS);
				} else {
					$this->ShowList(GetLang('SubscriberUpdateFailed'), MSG_ERROR);
				}
			} else {
				$this->ShowList();
			}
		}

	}

?>
