<?php

namespace Daylight\Core\Livewire\Tables;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Component;
use Livewire\WithPagination;

abstract class BaseTable extends Component
{
    use WithPagination;

    protected $perPage = 15;

    public array $selectedIds = [];

    public array $idsOnPage = [];

    abstract protected function getBaseQuery(): Builder;

    #[Computed]
    public function rows(): LengthAwarePaginator|Collection
    {
        $rows = $this->getBaseQuery()
            ->when(
                value: isset($this->searchable) && $this->searchable,
                callback: fn ($query) => $this->applySearch($query, $this->searchQuery))
            ->when(
                value: isset($this->multilingualism) && $this->multilingualism && ! empty($this->locale),
                callback: fn ($query) => $this->applyMultilingualism($query, $this->locale)
            )
            ->paginate($this->perPage);

        $this->idsOnPage = collect($rows->items())->map(fn ($row) => (string) $row->id)->toArray();

        return $rows;
    }
}
