<?php

namespace App\Livewire\Forms\Studio\Manage;

use App\Models\Faq;
use Livewire\Form;

class FaqForm extends Form
{
    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)
    {
        $this->faq = $faq;

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

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

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

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

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

    public function delete()
    {
        $this->faq->delete();

        Faq::where('sort_order', '>', $this->faq->sort_order)
            ->orderBy('sort_order')
            ->get()
            ->each(function ($cat) {
                $cat->update(['sort_order' => $cat->sort_order - 1]);
            });
    }

    public function sortOrder(string $direction)
    {
        if (in_array($direction, ['up', 'down'])) {
            $swap = null;

            if ($direction === 'up') {
                $swap = Faq::where('sort_order', '<', $this->faq->sort_order)
                    ->orderByDesc('sort_order')
                    ->first();
            } else {
                $swap = Faq::where('sort_order', '>', $this->faq->sort_order)
                    ->orderBy('sort_order')
                    ->first();
            }

            if ($swap) {
                $temp = $this->faq->sort_order;
                $this->faq->update(['sort_order' => $swap->sort_order]);
                $swap->update(['sort_order' => $temp]);
            }
        } elseif ($direction === 'first') {
            $this->faq->update(['sort_order' => Faq::min('sort_order') - 1]);
            $this->normalizeSortOrder();
        } elseif ($direction === 'last') {
            $this->faq->update(['sort_order' => Faq::max('sort_order') + 1]);
            $this->normalizeSortOrder();
        }
    }

    protected function normalizeSortOrder()
    {
        $categories = Faq::orderBy('sort_order')->get();
        foreach ($categories as $index => $faq) {
            $faq->update(['sort_order' => $index + 1]);
        }
    }
}
