<?php declare(strict_types=1);

/*
 * This file is part of the "neos-common" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

namespace Newland\NeosCommon\Utility;

class PaginationUtility
{
    public function getPaginationData(int $count, int $page, int $itemsPerPage): array
    {
        $pages = (int) ceil($count / $itemsPerPage);

        return [
            'isFirst' => $page === 1,
            'page' => $page,
            'currentPageFrom' => ($page - 1) * $itemsPerPage + 1,
            'currentPageTo' => $this->getCurrentPageTo($count, $page, $itemsPerPage),
            'isLast' => $pages === $page,
            'count' => [
                'items' => $count,
                'pages' => $pages,
            ],
        ];
    }

    private function getCurrentPageTo(int $count, int $page, int $itemsPerPage): int
    {
        $pages = (int) ceil($count / $itemsPerPage);
        $onlyOnePage = $pages === 1;
        $isLastPage = $pages === $page;

        if ($onlyOnePage || $isLastPage) {
            return $count;
        }

        return $itemsPerPage * $page;
    }
}
