<?php
require_once('FacilityDataSet.php');
class Paginator {
    protected $_pages, $_totalPages, $_rowLimit, $_pageMatrix, $_rowCount;

    public function __construct($rowLimit, $dataset) {
        $this->_rowLimit = $rowLimit;
        $this->_totalPages = $this->calculateTotalPages($dataset['count']);
        $this->_rowCount = $dataset['count'];
        $this->_pages = $dataset['dataset'];
        $this->_pageMatrix = $this->Paginate();
    }
    public function getTotalPages() {
        return $this->_totalPages;
    }
    private function calculateTotalPages(int $count): int {
        return $count > 0 ? ceil($count / $this->_rowLimit) : 0;
    }

    public function Paginate(): array {
        $pageMatrix = [];
        for ($i = 0; $i < $this->_totalPages; $i++) {
            $page = [];
            $start = $i * $this->_rowLimit;
            $end = min($start + $this->_rowLimit, $this->_rowCount); // Ensure within bounds

            for ($j = $start; $j < $end; $j++) {
                $page[] = $this->_pages[$j];
            }

            $pageMatrix[$i] = $page;
        }
        return $pageMatrix;
    }

    public function getPageFromUri(): int {
        // Retrieve 'page' parameter and default to 0 if missing or invalid
        return filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, [
            'options' => ['default' => 0, 'min_range' => 0] // Default to 1 if invalid or missing
        ]);
    }

    public function getPage(int $pageNumber): array {

        if ($pageNumber < 0 || $pageNumber >= $this->_totalPages) {
            return []; // Return an empty array if the page number is invalid
        }
        return $this->_pageMatrix[$pageNumber];
    }

    public function countPageResults(int $pageNumber): int {
        if ($pageNumber < 0 || $pageNumber >= $this->_totalPages) {
            return 0; // Return 0 if the page number is invalid
        }
        return count($this->_pageMatrix[$pageNumber]);
    }
}