<?php

namespace App\Livewire\Studio\Feature;

use App\Livewire\Forms\Studio\Feature\ChooseUsForm;
use App\Models\ChooseUs as ChooseUsModel;
use App\Traits\WithAuthorization;
use App\Traits\WithCloseModal;
use App\Traits\WithConfirmation;
use App\Traits\WithToast;
use App\Traits\WithUpdatedData;
use Flux\Flux;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Pilih Kami')]
class ChooseUs extends Component
{
    use WithAuthorization, WithCloseModal, WithConfirmation, WithToast, WithUpdatedData;

    public ChooseUsForm $form;

    public string $method = 'create';

    public string $modalTitle = '';

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

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

        if ($id) {
            $this->form->setChooseUs(ChooseUsModel::byHashOrFail($id));
        }
    }

    public function create()
    {
        $this->canOrAbort('create choose us');

        $this->form->store();

        $this->dispatch('refreshDatatable');

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

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

    public function update()
    {
        $this->canOrAbort('update choose us');

        $this->form->update();

        $this->dispatch('refreshDatatable');

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

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

    public function delete(ChooseUsModel $chooseUs)
    {
        $this->form->chooseUs = $chooseUs;

        $this->form->delete();

        $this->dispatch('refreshDatatable');

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

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

    #[On('fn:sortOrder')]
    public function sortOrder(ChooseUsModel $chooseUs, string $direction)
    {
        $this->canOrAbort('update choose us');

        $this->form->chooseUs = $chooseUs;

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

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

    public function render()
    {
        return view('livewire.studio.feature.choose-us', [
            'pageTitle' => 'Pilih Kami',
        ]);
    }
}
