<?php namespace ProcessWire;

/**
 * ProcessWire MarkupPagerNav module
 *
 * Provides capability for rendering pagination navigation with PageArrays
 *
 * Basic Example usage:
 * 
 * $items = $pages->find("id>0, limit=10"); // replace id>0 with your selector
 * $pager = $modules->get("MarkupPagerNav"); 
 * echo "<ul>";
 * foreach($items as $item) echo "<li>{$item->title}</li>";
 * echo "</ul>";
 * echo $pager->render($items); // render the pagination navigation
 *
 * MarkupPagerNav generates it's own HTML5/XHTML markup. To modify its markup
 * or options, specify a second $options array to the render() method. See 
 * the MarkupPagerNav::$options to see what defaults can be overridden. 
 *
 * PLEASE NOTE
 * 
 * The MarkupPageArray class uses MarkupPagerNav automatically when 
 * rendering a PageArray that was retrieved with a "limit=n" selector. 
 * 
 * MarkupPageArray also adds a PageArray::renderPager (i.e. $myPages->renderPager()) 
 * method which is the same as MarkupPagerNav::render() (i.e. $pager->render($items).
 *
 * 
 * ProcessWire 3.x (development), Copyright 2015 by Ryan Cramer
 * https://processwire.com
 * 
 */

require_once(dirname(__FILE__) . '/PagerNav.php'); 


/**
 * Class MarkupPagerNav
 * 
 * ProcessWire module that provides pagination for PageArray types
 * 
 * @property int $numPageLinks 10 number of links that the pagination navigation should have (typically 10)
 * @property array $getVars get vars that should appear in the pagination, or leave empty and populate $input->whitelist (preferred)
 * @property string $baseUrl the baseUrl from which the navigiation item links will start (default='')
 * @property null|Page $page the current Page, or leave NULL to autodetect
 * @property string $listMarkup List container markup. Place {out} where you want the individual items rendered (default="<ul class='MarkupPagerNav'>{out}</ul>")
 * @property string $itemMarkup List item markup. Place {class} for item class (required), and {out} for item content. (default="<li class='{class}'>{out}</li>")
 * @property string $linkMarkup Link markup. Place {url} for href attribute, and {out} for label content. (default="<a href='{url}'><span>{out}</span></a>")
 * @property string $currentLinkMarkup Link markup for current page. Place {url} for href attribute and {out} for label content. (default="<a href='{url}'><span>{out}</span></a>")
 * @property string $nextItemLabel label used for the 'Next' button (default='Next')
 * @property string $previousItemLabel label used for the 'Previous' button (default='Prev')
 * @property string $separatorItemLabel label used in the seperator item (default='&hellip;')
 * @property string $separatorItemClass Class for separator item (default='MarkupPagerNavSeparator')
 * @property string $firstItemClass Class for first item (default='MarkupPagerNavFirst')
 * @property string $firstNumberItemClass Class for first numbered item (default='MarkupPagerNavFirstNum')
 * @property string $nextItemClass Class for next item (default='MarkupPagerNavNext')
 * @property string $previousItemClass Class for previous item (default='MarkupPagerNavPrevious')
 * @property string $lastItemClass Class for last item (default='MarkupPagerNavLast')
 * @property string $lastNumberItemClass Class for last numbered item (default='MarkupPagerNavLastNum')
 * @property string $currentItemClass Class for current item (default='MarkupPagerNavOn')
 * @property bool $arrayToCSV when arrays are present in getVars, they will be translated to CSV strings in the queryString: ?var=a,b,c. if set to false, then arrays will be kept in traditional format: ?var[]=a&var[]=b&var=c (default=true)
 * @property int $totalItems Get total number of items to paginate (set automatically)
 * @property int $itemsPerPage Get number of items to display per page (set automatically)
 * @property int $pageNum Get the current page number (1-based, set automatically)
 * @property string $queryString the queryString used in links (set automatically, based on whitelist or getVars array)
 * @property bool $isLastPage Is the current pagination the last? Set automatically after a render() call. 
 * 
 * @method string render(WirePaginatable $items, $options = array())
 *
 */
class MarkupPagerNav extends Wire implements Module {

	public static function getModuleInfo() {
		return array(
			'title' => 'Pager (Pagination) Navigation', 
			'summary' => 'Generates markup for pagination navigation', 
			'version' => 104, 
			'permanent' => false, 
			'singular' => false, 
			'autoload' => false, 
			);
	}

	/**
	 * Options to modify the behavior and output of MarkupPagerNav
	 *
	 * Many of these are set automatically. 
	 *
	 */
	protected $options = array(

		// number of links that the pagination navigation should have (typically 10) 
		'numPageLinks' => 10,	

		// get vars that should appear in the pagination, or leave empty and populate $input->whitelist (preferred)
		'getVars' => array(), 	

		// the baseUrl from which the navigiation item links will start
		'baseUrl' => '',	

		// the current Page, or leave NULL to autodetect
		'page' => null, 	

		// List container markup. Place {out} where you want the individual items rendered. 
		'listMarkup' => "\n<ul class='MarkupPagerNav'>{out}\n</ul>",

		// List item markup. Place {class} for item class (required), and {out} for item content. 
		'itemMarkup' => "\n\t<li class='{class}'>{out}</li>",

		// Link markup. Place {url} for href attribute, and {out} for label content. 
		'linkMarkup' => "<a href='{url}'><span>{out}</span></a>", 

		// Link markup for current page. Place {url} for href attribute and {out} for label content. 
		'currentLinkMarkup' => "<a href='{url}'><span>{out}</span></a>", 

		// label used for the 'Next' button
		'nextItemLabel' => 'Next', 

		// label used for the 'Previous' button
		'previousItemLabel' => 'Prev', 

		// label used in the seperator item
		'separatorItemLabel' => '&hellip;', 

		// default classes used for list items, according to the type. 
		'separatorItemClass' => 'MarkupPagerNavSeparator', 
		'firstItemClass' => 'MarkupPagerNavFirst', 
		'firstNumberItemClass' => 'MarkupPagerNavFirstNum', 
		'nextItemClass' => 'MarkupPagerNavNext', 
		'previousItemClass' => 'MarkupPagerNavPrevious', 
		'lastItemClass' => 'MarkupPagerNavLast', 
		'lastNumberItemClass' => 'MarkupPagerNavLastNum',
		'currentItemClass' => 'MarkupPagerNavOn', 

		/*
		 * NOTE: The following options are set automatically and should not be provided in your $options,
	 	 * because anything you specify will get overwritten. 
		 *
		 */

		// total number of items to paginate (set automatically)
		'totalItems' => 0,	

		// number of items to display per page (set automatically) 
		'itemsPerPage' => 10,	

		// the current page number (1-based, set automatically)
		'pageNum' => 1,		

		// when arrays are present in getVars, they will be translated to CSV strings in the queryString: ?var=a,b,c
		// if set to false, then arrays will be kept in traditional format: ?var[]=a&var[]=b&var=c 
		'arrayToCSV' => true,

		// the queryString used in links (set automatically, based on whitelist or getVars array)
		'queryString' => '', 	
	
		); 
	
	protected $isLastPage = null; 


	public function __construct() {
		$this->options['nextItemLabel'] = $this->_('Next');
		$this->options['previousItemLabel'] = $this->_('Prev');
	}

	/**
	 * Render the output for the pagination
	 *
	 * @param WirePaginatable $items Pages used in the pagination that have had a "limit=n" selector applied when they were loaded. 
	 * @param array $options Any options to override the defnults. For the defaults see MarkupPagerNav::$options
	 * @return string
	 *
	 */
	public function ___render(WirePaginatable $items, $options = array()) {

		$config = $this->wire('config');
		$this->isLastPage = true; 
		$this->totalItems = $items->getTotal();
		if(!$this->totalItems) return '';

		$this->options = array_merge($this->options, $options); 
		$limit = $items->getLimit();
		if($limit) $this->itemsPerPage = $limit;
		$this->pageNum = $items->getStart() < $this->itemsPerPage  ? 1 : ceil($items->getStart() / $this->itemsPerPage)+1; 

		if(is_null($this->options['page'])) $this->options['page'] = $this->wire('page'); 

		if(!strlen($this->queryString)) {
			$whitelist = $this->wire('input')->whitelist->getArray(); 
			if(!count($this->options['getVars']) && count($whitelist)) $this->setGetVars($whitelist); 
				else if(count($this->options['getVars'])) $this->setGetVars($this->getVars); 
		}

		$pagerNav = new PagerNav($this->totalItems, $this->itemsPerPage, $this->pageNum); 
		$pagerNav->setLabels($this->options['previousItemLabel'], $this->options['nextItemLabel']); 
		$pagerNav->setNumPageLinks($this->numPageLinks); 
		$pager = $pagerNav->getPager();
		$out = '';
	
		// if allowPageNum is true, then we can use urlSegment style page numbers rather than GET var page numbers	
		$allowPageNum = $this->options['page']->template->allowPageNum; 
		$slashUrls = $this->options['page']->template->slashUrls;
		$slashPageNum = $this->options['page']->template->slashPageNum;
		$pageNumUrlPrefix = $config->pageNumUrlPrefix; 
		if(!$pageNumUrlPrefix) $pageNumUrlPrefix = 'page';

		$pagerCount = count($pager);
		if($pagerCount > 1) $this->isLastPage = false; 
		$firstNumberKey = null;
		$lastNumberKey = null;

		// determine first and last numbered items
		foreach($pager as $key => $item) {
			if(!ctype_digit("$item->label")) continue;
			if(is_null($firstNumberKey)) $firstNumberKey = $key;
			$lastNumberKey = $key;
		}
		
		$_url = ''; // URL from previous loop interation
		$nextURL = '';
		$prevURL = '';
		$lastWasCurrent = false; // was the last iteration for the current page item?
		
		foreach($pager as $key => $item) {

			if($item->type == 'separator') {
				$out .= str_replace(
					array('{class}', '{out}'), 
					array($this->options['separatorItemClass'], $this->options['separatorItemLabel']), 
					$this->options['itemMarkup']); 
				continue; 
			} 

			$url = $this->baseUrl;
			if(!$url) $url = $this->options['page']->url;

			if($item->pageNum > 1) {
				if($allowPageNum) {
					if($slashUrls === 0) $url .= '/'; // enforce a trailing slash, regardless of slashUrls template setting
					$url .= "$pageNumUrlPrefix{$item->pageNum}";
					if($slashPageNum > 0) $url .= '/';
					$url .= $this->queryString; 
				} else {
					$url .= $this->queryString . ($this->queryString ? "&" : "?") . "$pageNumUrlPrefix=" . $item->pageNum;
				}
			} else {
				$url .= $this->queryString; 
			}

			$class = isset($this->options[$item->type . 'ItemClass']) ? $this->options[$item->type . 'ItemClass'] : '';

			if(!$key) $class .= ' ' . $this->options['firstItemClass']; 
				else if($key == ($pagerCount-1)) $class .= ' ' . $this->options['lastItemClass'];

			if($key === $firstNumberKey) {
				$class .= ' ' . $this->options['firstNumberItemClass'];
			} else if($key === $lastNumberKey) {
				$class .= ' ' . $this->options['lastNumberItemClass'];
				if($item->type == 'current') $this->isLastPage = true; 
			}
			
			$linkMarkup = isset($this->options[$item->type . 'LinkMarkup']) ? $this->options[$item->type . 'LinkMarkup'] : $this->options['linkMarkup'];
			$link = str_replace(array('{url}', '{out}'), array($url, $item->label), $linkMarkup); 
			$out .= str_replace(array('{class}', '{out}'), array(trim($class), $link), $this->options['itemMarkup']); 
			
			if($item->type == 'current') {
				$prevURL = $_url;
				$lastWasCurrent = true;
			} else {
				if($lastWasCurrent) $nextURL = $url;
				$lastWasCurrent = false;
			}
			
			$_url = $url; // remember previous url
		}

		if($out) {
			$out = str_replace(array(" class=''", ' class=""'), '', $out);
			$out = str_replace('{out}', $out, $this->options['listMarkup']); 
			
			if($nextURL) $config->urls->next = $nextURL;
			if($prevURL) $config->urls->prev = $prevURL;
		}
		
		return $out; 
	}

	/**
	 * Retrieve a MarkupPagerNav option as an object property
	 *
	 */
	public function __get($property) {
		if(isset($this->options[$property])) return $this->options[$property]; 
		if($property == 'isLastPage') return $this->isLastPage; 
		return null;
	}

	/**
	 * Set a MarkupPagerNav option as an object property
	 *
	 */
	public function __set($property, $value) {
		if(isset($this->options[$property])) $this->options[$property] = $value; 
	}

	/**
	 * Set the getVars for this MarkupPagerNav
	 *
	 * Generates $this->options['queryString'] automatically.
	 *
	 * @param array $vars Array of GET vars indexed as ($key => $value)
	 *
	 */
	public function setGetVars(array $vars) { 
		$this->options['getVars'] = $vars; 
		$queryString = "?";
		foreach($this->options['getVars'] as $key => $value) {
			if(is_array($value)) {
				if($this->options['arrayToCSV']) {
					$a = $value; 
					$value = '';
					foreach($a as $k => $v) $value .= "$v,";
					$value = rtrim($value, ", "); 
					$queryString .= "$key=" . urlencode($value) . "&";	
				} else {
					foreach($value as $k => $v) $queryString .= "$key%5B%5D=" . urlencode($v) . "&";
				}
	
			} else {
				$queryString .= "$key=" . urlencode($value) . "&";	
			}
		}
		$this->queryString = htmlspecialchars(rtrim($queryString, "?&")); 
	}

	/*
	 * All the methods below are optional and typically set automatically, or via the $options param. 
	 *
	 */

	public function setPageNum($n) { $this->pageNum = $n; }
	public function setItemsPerPage($n) { $this->itemsPerPage = $n; }
	public function setTotalItems($n) { $this->totalItems = $n; }
	public function setNumPageLinks($n) { $this->numPageLinks = $n; }
	public function setQueryString($s) { $this->queryString = $s; }
	public function setBaseUrl($url) { $this->baseUrl = $url; }

	public function setLabels($next, $prev) { 
		$this->options['nextItemLabel'] = $next; 
		$this->options['previousItemLabel'] = $prev; 
	}
	
	/**
	 * Returns true when the current pagination is the last one
	 *
	 * Only set after a render() call. Prior to that it is null.
	 *
	 * @return bool|null
	 *
	 */
	public function isLastPage() {
		return $this->isLastPage;
	}


	/* 
	 * The following methods are specific to the Module interface 
 	 *
	 */

	public function init() { }	
	public function ___install() { }
	public function ___uninstall() { }

}

