<?php
class Pagination {
    /**
     * @param int    $total_rows   Total number of rows
     * @param int    $rows_per_pg  Rows per page
     * @param int    $current_pg   Current page number
     * @param string $base_url     Base URL for page links (append page number)
     * @return array ['html' => string, 'limit' => string, 'offset' => int]
     */
    public static function paginate(int $total_rows, int $rows_per_pg, int $current_pg, string $base_url): array {
        $total_pages = (int)ceil($total_rows / $rows_per_pg);
        $current_pg  = max(1, min($current_pg, $total_pages));
        $offset      = ($current_pg - 1) * $rows_per_pg;

        if ($total_pages <= 1) {
            return ['html' => '', 'limit' => "LIMIT {$rows_per_pg} OFFSET 0", 'offset' => 0, 'current' => 1];
        }

        $html  = '<nav aria-label="Pagination"><ul class="pagination pagination-sm mb-0">';

        // Previous
        $prev_disabled = $current_pg === 1 ? 'disabled' : '';
        $prev_href     = $current_pg > 1 ? $base_url . ($current_pg - 1) : '#';
        $html .= "<li class='page-item {$prev_disabled}'><a class='page-link' href='{$prev_href}'>&laquo;</a></li>";

        // Page numbers (show window of 5 around current)
        $start = max(1, $current_pg - 2);
        $end   = min($total_pages, $current_pg + 2);

        if ($start > 1) {
            $html .= "<li class='page-item'><a class='page-link' href='{$base_url}1'>1</a></li>";
            if ($start > 2) $html .= "<li class='page-item disabled'><span class='page-link'>...</span></li>";
        }

        for ($i = $start; $i <= $end; $i++) {
            $active = $i === $current_pg ? 'active' : '';
            $html  .= "<li class='page-item {$active}'><a class='page-link' href='{$base_url}{$i}'>{$i}</a></li>";
        }

        if ($end < $total_pages) {
            if ($end < $total_pages - 1) $html .= "<li class='page-item disabled'><span class='page-link'>...</span></li>";
            $html .= "<li class='page-item'><a class='page-link' href='{$base_url}{$total_pages}'>{$total_pages}</a></li>";
        }

        // Next
        $next_disabled = $current_pg === $total_pages ? 'disabled' : '';
        $next_href     = $current_pg < $total_pages ? $base_url . ($current_pg + 1) : '#';
        $html .= "<li class='page-item {$next_disabled}'><a class='page-link' href='{$next_href}'>&raquo;</a></li>";

        $html .= '</ul></nav>';

        return [
            'html'    => $html,
            'limit'   => "LIMIT {$rows_per_pg} OFFSET {$offset}",
            'offset'  => $offset,
            'current' => $current_pg,
            'total'   => $total_pages,
        ];
    }
}
