<?php

namespace App\Livewire\Studio\Information;

use App\Livewire\Forms\Studio\Information\FaqForm;
use App\Models\Faq as FaqModel;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithCloseModal;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Utilities\WithUpdatedData;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('FAQs')]
class Faq extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithSubscribeNotification, WithToast, WithUpdatedData;

    public FaqForm $form;

    public string $method = 'create';

    public string $modalTitle = '';

    public function create(): void
    {
        $this->canOrAbort('create faq');

        $this->form->store();

        $this->dispatch('refreshDatatable');

        $this->toast('FAQs berhasil ditambahkan.');

        Flux::modals()->close();
    }

    public function update(): void
    {
        $this->canOrAbort('update faq');

        $this->form->update();

        $this->dispatch('refreshDatatable');

        $this->toast('FAQs berhasil diperbarui.');

        Flux::modals()->close();
    }

    public function delete(FaqModel $faq): void
    {
        $this->canOrAbort('delete faq');

        $this->form->faq = $faq;

        $this->form->delete();

        $this->dispatch('refreshDatatable');

        $this->toast('FAQs berhasil dihapus.');

        Flux::modals()->close();
    }

    #[On('fn:sortOrder')]
    public function sortOrder(FaqModel $faq, string $direction): void
    {
        $this->canOrAbort('update faq');

        $this->form->faq = $faq;

        $this->form->sortOrder($direction);

        $this->dispatch('refreshDatatable');
    }

    #[On('modal:open')]
    public function openModal(string $method, string $modalTitle, ?string $id = null): void
    {
        $this->resetValidation();
        $this->resetErrorBag();

        $this->method = $method;
        $this->modalTitle = $modalTitle;

        $id && $this->form->setFaq(FaqModel::byHashOrFail($id));
    }

    public function render(): View
    {
        return view('livewire.studio.information.faqs', [
            'pageTitle' => 'FAQs',
        ]);
    }
}
