<?php
namespace EasyChat\Library;

class Pagination {
	public $total = 0;
	public $page = 1;
	public $limit = 20;
	public $num_links = 5;
	public $url = '';  
	public $text_first = '|<';
	public $text_last = '>|';
	public $text_next = '>';
	public $text_prev = '<';

	public function render() {
		$total = $this->total;

		if ($this->page < 1) {
			$page = 1;
		} else {
			$page = $this->page;
		}

		if (!(int)$this->limit) {
			$limit = 10;
		} else {
			$limit = $this->limit;
		}

		$num_links = $this->num_links;
		$num_pages = ceil($total / $limit);

		if ($num_pages == 1) {
			return '';
		}

		$output = '<ul class="pagination pagination-sm mb-0 justify-content-center">';

		if ($page > 1) {
			$output .= '<li class="page-item"><a class="page-link" href="' . str_replace('{page}', 1, $this->url) . '" data-page="1">' . $this->text_first . '</a></li>';
			$output .= '<li class="page-item"><a class="page-link" href="' . str_replace('{page}', $page - 1, $this->url) . '" data-page="' . ($page - 1) . '">' . $this->text_prev . '</a></li>';
		}

		if ($num_pages > 1) {
			if ($num_pages <= $num_links) {
				$start = 1;
				$end = $num_pages;
			} else {
				$start = $page - floor($num_links / 2);
				$end = $page + floor($num_links / 2);

				if ($start < 1) {
					$end += abs($start) + 1;
					$start = 1;
				}

				if ($end > $num_pages) {
					$start -= ($end - $num_pages);
					$end = $num_pages;
				}
			}

			for ($i = $start; $i <= $end; $i++) {
				if ($page == $i) {
					$output .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
				} else {
					$output .= '<li class="page-item"><a class="page-link" href="' . str_replace('{page}', $i, $this->url) . '" data-page="' . $i . '">' . $i . '</a></li>';
				}
			}
		}

		if ($page < $num_pages) {
			$output .= '<li class="page-item"><a class="page-link" href="' . str_replace('{page}', $page + 1, $this->url) . '" data-page="' . ($page + 1) . '">' . $this->text_next . '</a></li>';
			$output .= '<li class="page-item"><a class="page-link" href="' . str_replace('{page}', $num_pages, $this->url) . '" data-page="' . $num_pages . '">' . $this->text_last . '</a></li>';
		}

		$output .= '</ul>';

		return $output;
	}
}
