<?php
declare(strict_types=1);

/**
 * @param array<int, array{label: string, href: ?string}> $crumbs Last item may have href null
 */
function admin_breadcrumbs(array $crumbs): string
{
    $html = '<nav aria-label="breadcrumb"><ol class="breadcrumb mb-0 small">';
    $n = count($crumbs);
    foreach ($crumbs as $i => $c) {
        $isLast = $i === $n - 1;
        $label = htmlspecialchars($c['label'], ENT_QUOTES, 'UTF-8');
        if ($isLast || empty($c['href'])) {
            $html .= '<li class="breadcrumb-item active" aria-current="page">' . $label . '</li>';
        } else {
            $html .= '<li class="breadcrumb-item"><a href="' . htmlspecialchars($c['href'], ENT_QUOTES, 'UTF-8') . '">' . $label . '</a></li>';
        }
    }
    $html .= '</ol></nav>';
    return $html;
}

function admin_pagination(int $total, int $page, int $perPage, array $queryParams = []): string
{
    if ($total <= $perPage) {
        return '';
    }
    $pages = (int)ceil($total / $perPage);
    $page = max(1, min($page, $pages));
    $self = basename($_SERVER['SCRIPT_NAME'] ?? 'index.php');
    $qs = array_merge($_GET, $queryParams);
    unset($qs['page']);
    $build = static function (int $p) use ($self, $qs): string {
        $q = $qs;
        $q['page'] = $p;
        return $self . '?' . http_build_query($q);
    };
    $html = '<nav class="mt-3"><ul class="pagination pagination-sm justify-content-end mb-0">';
    if ($page > 1) {
        $html .= '<li class="page-item"><a class="page-link" href="' . htmlspecialchars($build($page - 1)) . '">Previous</a></li>';
    }
    for ($i = max(1, $page - 2); $i <= min($pages, $page + 2); $i++) {
        $active = $i === $page ? ' active' : '';
        $html .= '<li class="page-item' . $active . '"><a class="page-link" href="' . htmlspecialchars($build($i)) . '">' . $i . '</a></li>';
    }
    if ($page < $pages) {
        $html .= '<li class="page-item"><a class="page-link" href="' . htmlspecialchars($build($page + 1)) . '">Next</a></li>';
    }
    $html .= '</ul><p class="text-muted small text-end mb-0 mt-1">Showing ' . (($page - 1) * $perPage + 1) . '–' . min($total, $page * $perPage) . ' of ' . $total . '</p></nav>';
    return $html;
}
