<?php

namespace Velis\Dto\Common\Result;

use Velis\Dto\BaseDto;
use Velis\Model\DataObject;

/**
 * @author Damian Kurek <damian.kurek@velistech.com>
 * @author Łukasz Gąsiorek <luksz.gasiorek@velistech.com>
 */
class PaginationMetadata extends BaseDto
{
    public int $page;
    public int $per_page;
    public int $pages_count;
    public int $items_count;

    /**
     * @var MetadataLinks
     */
    public MetadataLinks $links;


    /**
     * @param int $page
     * @param int $perPage
     * @param int $itemsFound
     * @return PaginationMetadata
     */
    public static function create(int $page, int $perPage, int $itemsFound): PaginationMetadata
    {
        $perPage = DataObject::limit($perPage);
        if ($itemsFound) {
            $pagesCount = (int) ceil($itemsFound / $perPage);
        } else {
            $pagesCount = 0;
        }

        $currentLink = $_SERVER['REQUEST_URI'];

        if (preg_match('/[?&]page=/', $currentLink) !== 1) {
            if (strpos($currentLink, '?') !== false) {
                $currentLink .= "&page=$page";
            } else {
                $currentLink .= "?page=$page";
            }
        }

        $firstLink = str_replace('page=' . $page, 'page=1', $currentLink);
        $prevLink = str_replace('page=' . $page, 'page=' . ($page - 1), $currentLink);
        $nextLink = str_replace('page=' . $page, 'page=' . ($page + 1), $currentLink);
        $lastLink = str_replace('page=' . $page, 'page=' . $pagesCount, $currentLink);


        $links = MetadataLinks::fromArray([
            'self' => $currentLink,
            'first' => $firstLink,
            'previous' => $page > 1 ? $prevLink : null,
            'next' => $page < $pagesCount ? $nextLink : null,
            'last' => $lastLink,
        ]);

        return PaginationMetadata::fromArray([
            'page' => $page,
            'per_page' => $perPage,
            'pages_count' => $pagesCount,
            'items_count' => $itemsFound,
            'links' => $links,
        ]);
    }
}
