<?php

declare(strict_types=1);

namespace App\Filament\Components\Form;

use App\Filament\Support\SelectOptionLabels;
use App\Models\Category;
use Filament\Forms\Components\Select;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class CategoriesSelect extends Select
{
    public static function create($model): static
    {
        return parent::make('categories')
            ->label('دسته‌بندی‌ها')
            ->multiple()
            ->preload()
            ->searchable(['title'])
            ->relationship('categories', 'title')
            ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::category($record))
            ->pivotData(['model_type' => $model])
            ->options(
                Category::query()
                    ->where('model_type', $model)
                    ->get(['id', 'title'])
                    ->mapWithKeys(fn (Category $category): array => [
                        $category->id => SelectOptionLabels::category($category),
                    ])
                    ->all()
            )
            ->createOptionForm([
                TitleTextInput::create()
                    ->required(),
            ])
            ->createOptionUsing(function (array $data) use ($model) {
                $data['slug'] = Str::slug($data['title']);
                $data['created_by'] = Auth::id();
                $data['page_title'] = $data['title'];
                $data['order'] = 0;
                $data['model_type'] = $model;
                $category = Category::create($data);

                return $category->getKey();
            })
            ->columnSpan(12);
    }
}
