<?php

namespace App\Livewire\Forms\Studio\Feature;

use App\Models\ChooseUs;
use App\Traits\Utilities\WithSortOrder;
use Illuminate\Support\Facades\DB;
use Livewire\Form;

class ChooseUsForm extends Form
{
    use WithSortOrder;

    public ?ChooseUs $chooseUs = null;

    public string $name = '';

    public string $description = '';

    public string $icon = '';

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50'],
            'description' => ['required', 'string'],
            'icon' => ['required', 'string', 'max:30'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'name' => 'nama',
            'description' => 'keterangan',
            'icon' => 'ikon',
        ];
    }

    public function setChooseUs(ChooseUs $chooseUs): void
    {
        $this->chooseUs = $chooseUs;

        $this->name = $chooseUs->name;
        $this->description = $chooseUs->description;
        $this->icon = $chooseUs->icon;
    }

    public function store(): void
    {
        $this->validate();

        DB::transaction(function () {
            // Increment all existing choose us items' sort_order
            ChooseUs::query()->increment('sort_order');

            ChooseUs::create([
                'name' => $this->name,
                'description' => $this->description,
                'icon' => $this->icon,
                'sort_order' => 1,
            ]);
        });
    }

    public function update(): void
    {
        $this->validate();

        $this->chooseUs->update([
            'name' => $this->name,
            'description' => $this->description,
            'icon' => $this->icon,
        ]);
    }

    public function delete(): void
    {
        $this->chooseUs->delete();
        $this->adjustSortOrderAfterDelete($this->chooseUs);
    }

    protected function getModelClass(): string
    {
        return ChooseUs::class;
    }

    protected function getModelInstance(): ChooseUs
    {
        return $this->chooseUs;
    }
}
