<?php

if (empty($_view["pageData"])) {
    return;
}

$adjacents = 1;

$pd = $_view["pageData"];
$page = $pd["currentPage"] ?? 1;
$limit = $pd["limit"] ?? 10;
$lastpage = $pd["pages"];
$prevToLastpage = $lastpage - 1;

// previous button
$links = [["<span class='icon'></span>", $page > 1 ? $page - 1 : "#"]];

// pages
if ($lastpage < 5 + ($adjacents * 2)) {
// not enough pages to bother breaking it up
    for ($i = 1; $i <= $lastpage; $i++) {
        $links[] = $i;
    }
} else {
// enough pages to hide some
    if ($page <= 2 + ($adjacents * 2)) {
        // close to beginning; only hide later pages
        for ($i = 1; $i < 4 + ($adjacents * 2); $i++) {
            $links[] = $i;
        }
        $links = [...$links, ["...", "javascript:;"], $prevToLastpage, $lastpage];
    } elseif ($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
        // in middle; hide some front and some back
        $links = [...$links, 1, 2, ["...", "javascript:;"]];
        for ($i = $page - $adjacents; $i <= $page + $adjacents; $i++) {
            $links[] = $i;
        }
        $links = [...$links, ["...", "javascript:;"], $prevToLastpage, $lastpage];
    } else {
        // close to end; only hide early pages
        $links = [...$links, 1, 2, ["...", "javascript:;"]];
        for ($i = $lastpage - (0 + ($adjacents * 3)); $i <= $lastpage; $i++) {
            $links[] = $i;
        }
    }
}

// next button
$links[] = ["<span class='icon'></span>", $page < $i - 1 ? $page + 1 : "#"];
?>

<nav class="space-mt-lg">
    <ul class="pagination justify-content-center">
        <?php
            $params = $_view["linkParams"] ?? [];
            foreach ($links as $row) {
                $link = $row[1] ?? $row;
                $name = $row[0] ?? $row;
                $disabled = $link == "#" || str_contains($link, "javascript:");
                $params["p"] = $link;
                $showMobile = $row === $links[0] || $row === $links[1] || $row === $links[count($links) - 1]
                    || $row === $links[count($links) - 2] || $page == $link || $name == "...";

                $url = $disabled ? "#" : $_con->getLink($_view["linkArgs"] ?? [], $params);
                echo "<li class='page-item" . ($disabled ? " disabled" : "") . ($page == $link ? " active" : "") . (!$showMobile ? " d-none d-md-block" : "") . "'>";
                echo "<a href=\"" . $url . "\" class='page-link'>$name</a></li>";
            }
        ?>
    </ul>
</nav>
