<?php

declare(strict_types=1);

class Pagination
{
    public int $page;
    public int $perPage;
    public int $total;
    public int $totalPages;
    public int $offset;

     
    public const MAX_PAGES = 250;

    public function __construct(int $total, int $page = 1, int $perPage = 100)
    {
        $this->total = $total;
        $this->perPage = max(1, $perPage);
        $rawPages = max(1, (int) ceil($total / $this->perPage));
        $this->totalPages = min($rawPages, self::MAX_PAGES);
        $this->page = max(1, min($page, $this->totalPages));
        $this->offset = ($this->page - 1) * $this->perPage;
    }

    public static function fromRequest(int $total, int $perPage = 100): self
    {
        $page = max(1, (int) ($_GET['page'] ?? 1));
         
         
         
         
        return new self($total, $page, $perPage);
    }

    

    public function pageUrl(string $base, int $page): string
    {
        $params = $_GET;
        $params['page'] = $page;
        return $base . '?' . http_build_query($params);
    }

    public function hasPrev(): bool
    {
        return $this->page > 1;
    }

    public function hasNext(): bool
    {
        return $this->page < $this->totalPages;
    }

    public function prevUrl(string $base = ''): string
    {
        return self::buildUrl($base, $this->page - 1);
    }

    public function nextUrl(string $base = ''): string
    {
        return self::buildUrl($base, $this->page + 1);
    }

    public function pages(): array
    {
        $pages = [];
        $start = max(1, $this->page - 2);
        $end = min($this->totalPages, $this->page + 2);

        if ($start > 1) {
            $pages[] = 1;
            if ($start > 2) {
                $pages[] = '...';
            }
        }

        for ($i = $start; $i <= $end; $i++) {
            $pages[] = $i;
        }

        if ($end < $this->totalPages) {
            if ($end < $this->totalPages - 1) {
                $pages[] = '...';
            }
            $pages[] = $this->totalPages;
        }

        return $pages;
    }

    private static function buildUrl(string $base, int $page): string
    {
        $params = $_GET;
        $params['page'] = $page;
        $query = http_build_query($params);
        return $base . '?' . $query;
    }
}
