count(); $totalPages = max(1, (int) ceil($total / $perPage)); $page = min($page, $totalPages); $records = (clone $base) // Actionable bills stay ahead of historical service dates. ->orderByRaw("CASE WHEN status IN ('open', 'overdue') THEN 0 ELSE 1 END") ->orderByDesc('created_at') ->orderByDesc('id') ->offset(($page - 1) * $perPage) ->limit($perPage) ->get([ 'id', 'purpose', 'instance_id', 'order_id', 'user_id', 'due_at', 'amount', 'status', 'created_at', ]); $count = $records->count(); return [ 'invoices' => CloudInvoiceService::listSummaries($records), 'pagination' => [ 'page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => $totalPages, 'has_previous' => $page > 1, 'has_next' => $page < $totalPages, 'from' => $count === 0 ? 0 : (($page - 1) * $perPage) + 1, 'to' => $count === 0 ? 0 : (($page - 1) * $perPage) + $count, ], ]; } }