<?php
/*****************************************************************************
 * PageIndexWidget.php
 * Contains the template that displays a page index.
 *
 * Global Data Lab code (C) Radboud University Nijmegen
 * Programming (C) Aaron van Geffen, 2015-2022
 *****************************************************************************/

class PageIndexWidget extends Template
{
	private $index;
	private string $class;

	public function __construct(PageIndex $index)
	{
		$this->index = $index;
		$this->class = $index->getPageIndexClass();
	}

	public function html_main()
	{
		self::paginate($this->index, $this->class);
	}

	public static function paginate(PageIndex $index, $class = null)
	{
		$page_index = $index->getPageIndex();
		if (empty($page_index) || count($page_index) == 1)
			return;

		if (!isset($class))
			$class = $index->getPageIndexClass();

		echo '
				<ul class="pagination', $class ? ' ' . $class : '', '">
					<li class="page-item', empty($page_index['previous']) ? ' disabled' : '', '">',
						'<a class="page-link"', !empty($page_index['previous']) ? ' href="' . $page_index['previous']['href'] . '"' : '', '>',
						'&laquo; previous</a></li>';

		foreach ($page_index as $key => $page)
		{
			if (!is_numeric($key))
				continue;

			if (!is_array($page))
				echo '
					<li class="page-item disabled"><a class="page-link">...</a></li>';
			else
				echo '
					<li class="page-item', $page['is_selected'] ? ' active" aria-current="page' : '', '">',
						'<a class="page-link" href="', $page['href'], '">', $page['index'], '</a></li>';
		}

		echo '
					<li class="page-item', empty($page_index['next']) ? ' disabled' : '', '">',
						'<a class="page-link"', !empty($page_index['next']) ? ' href="' . $page_index['next']['href'] . '"' : '', '>',
						'next &raquo;</a></li>
				</ul>';
	}
}