<?php
// core/Pagination.php

class Pagination {
    public $totalRecords;
    public $recordsPerPage;
    public $currentPage;
    public $totalPages;
    public $offset;

    public function __construct($totalRecords, $recordsPerPage = DEFAULT_RECORDS_PER_PAGE, $currentPage = 1) {
        $this->totalRecords = $totalRecords;
        $this->recordsPerPage = $recordsPerPage;
        $this->currentPage = max(1, (int)$currentPage);
        $this->totalPages = ceil($totalRecords / $recordsPerPage);
        $this->offset = ($this->currentPage - 1) * $recordsPerPage;
    }

    public function render($baseUrl, $queryParams = []) {
    if ($this->totalPages <= 1) return '';

    $html = '<nav aria-label="Page navigation"><ul class="pagination justify-content-center">';

    // Previous
    $prevDisabled = ($this->currentPage <= 1) ? ' disabled' : '';
    $queryParams['page'] = max(1, $this->currentPage - 1);
    $html .= "<li class='page-item$prevDisabled'><a class='page-link' href='{$baseUrl}?" . http_build_query($queryParams) . "'>Previous</a></li>";

    // Page numbers
    for ($i = 1; $i <= $this->totalPages; $i++) {
        $queryParams['page'] = $i;
        $url = $baseUrl . '?' . http_build_query($queryParams);
        $active = ($i == $this->currentPage) ? ' active' : '';
        $html .= "<li class='page-item$active'><a class='page-link' href='$url'>$i</a></li>";
    }

    // Next
    $nextDisabled = ($this->currentPage >= $this->totalPages) ? ' disabled' : '';
    $queryParams['page'] = min($this->totalPages, $this->currentPage + 1);
    $html .= "<li class='page-item$nextDisabled'><a class='page-link' href='{$baseUrl}?" . http_build_query($queryParams) . "'>Next</a></li>";

    $html .= '</ul></nav>';
    return $html;
}
?>