<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpCustomerSalesRankings\Pages;

use App\Business\Report\SalesReportService;
use App\Filament\Resources\DberpCustomerSalesRankings\DberpCustomerSalesRankingResource;
use App\Models\DberpCustomer;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;

class ListDberpCustomerSalesRankings extends ListRecords
{
    protected static string $resource = DberpCustomerSalesRankingResource::class;

    public function getSubheading(): string|Htmlable|null
    {
        return __('dberp.resources.customer_sales_ranking.scope_hint');
    }

    public function computeCustomerSalesRankingRank(DberpCustomer $record): int
    {
        $paginator = $this->getTableRecords();

        if (! $paginator instanceof LengthAwarePaginator) {
            return 0;
        }

        $perPage = max(1, $paginator->perPage());
        $offset = max(0, ($paginator->currentPage() - 1) * $perPage);

        foreach ($paginator->items() as $index => $item) {
            if ($item instanceof DberpCustomer && $item->getKey() === $record->getKey()) {
                return $offset + $index + 1;
            }
        }

        return 0;
    }

    protected function getTableQuery(): Builder
    {
        $filters = SalesReportService::filtersFromTableState(
            is_array($this->tableFilters) ? $this->tableFilters : null,
        );

        return app(SalesReportService::class)->customerRankingQuery($filters);
    }
}
