<?php

namespace App\Livewire\Forms\Studio\Information;

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

class FaqForm extends Form
{
    use WithSortOrder;

    public ?Faq $faq = null;

    public string $question = '';

    public string $answer = '';

    public function rules(): array
    {
        return [
            'question' => ['required', 'string', 'max:100'],
            'answer' => ['required', 'string'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'question' => 'pertanyaan',
            'answer' => 'jawaban',
        ];
    }

    public function setFaq(Faq $faq): void
    {
        $this->faq = $faq;

        $this->question = $faq->question;
        $this->answer = $faq->answer;
    }

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

        DB::transaction(function () {
            // Increment all existing faqs' sort_order
            Faq::query()->increment('sort_order');

            Faq::create([
                'question' => $this->question,
                'answer' => $this->answer,
                'sort_order' => 1,
            ]);
        });
    }

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

        $this->faq->update([
            'question' => $this->question,
            'answer' => $this->answer,
        ]);
    }

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

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

    protected function getModelInstance(): Faq
    {
        return $this->faq;
    }
}
