<?php
declare(strict_types=1);

namespace Celena\Core\Http;

/**
 * Помощник пагинации. Считает смещение, общее число страниц, собирает массив ссылок для шаблона.
 */
final class Pagination
{
    public readonly int $currentPage;
    public readonly int $perPage;
    public readonly int $totalItems;
    public readonly int $totalPages;
    public readonly int $offset;

    public function __construct(int $currentPage, int $perPage, int $totalItems)
    {
        $this->perPage    = max(1, $perPage);
        $this->totalItems = max(0, $totalItems);
        $this->totalPages = max(1, (int) ceil($this->totalItems / $this->perPage));
        $this->currentPage = min(max(1, $currentPage), $this->totalPages);
        $this->offset = ($this->currentPage - 1) * $this->perPage;
    }

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

    /** @return array<string, mixed> — для передачи в шаблон */
    public function toArray(string $urlPattern = '?page=:page'): array
    {
        return [
            'current' => $this->currentPage,
            'per_page' => $this->perPage,
            'total' => $this->totalItems,
            'total_pages' => $this->totalPages,
            'has_prev' => $this->hasPrev(),
            'has_next' => $this->hasNext(),
            'prev_url' => $this->hasPrev() ? str_replace(':page', (string) ($this->currentPage - 1), $urlPattern) : '',
            'next_url' => $this->hasNext() ? str_replace(':page', (string) ($this->currentPage + 1), $urlPattern) : '',
        ];
    }
}
