<?php
declare(strict_types=1);

namespace App\Admin;

final class AdminPagination
{
    public function __construct(public readonly int $page, public readonly int $perPage, public readonly int $total)
    {
    }

    public static function fromQuery(array $query, int $total, int $defaultPerPage = 50): self
    {
        $perPage = max(10, min(100, (int) ($query['per_page'] ?? $defaultPerPage)));
        $pages = max(1, (int) ceil(max(0, $total) / $perPage));
        $page = max(1, min($pages, (int) ($query['admin_page'] ?? 1)));
        return new self($page, $perPage, max(0, $total));
    }

    public function offset(): int { return ($this->page - 1) * $this->perPage; }
    public function pages(): int { return max(1, (int) ceil($this->total / $this->perPage)); }
    public function slice(array $rows): array { return array_slice($rows, $this->offset(), $this->perPage); }
}
