<?php

namespace Daylight\Core\Livewire\Store;

use Daylight\Core\Livewire\Tables\BaseTable;
use Daylight\Core\Livewire\Tables\Concerns\WithRowActions;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Livewire\Attributes\Computed;

class CategoryTable extends BaseTable
{
    use WithRowActions;

    protected function getBaseQuery(): Builder
    {
        return (daylightModel('category'))::query()
            ->whereParentId(null)
            ->with([
                'translations',
                'children.translations',
                'children.children.translations',
            ]);
    }

    #[Computed]
    public function rows(): 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)
            )
            ->get();

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

        return $rows;
    }

    public function render(): View
    {
        return view('daylight::livewire.store.category-table');
    }
}
