<?php

namespace App\Livewire\Studio\Manage\Article;

use App\Enums\CategoryType;
use App\Livewire\Forms\Studio\Manage\ArticleForm;
use App\Models\Article;
use App\Models\Category;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithCategorySelector;
use App\Traits\Components\WithToast;
use App\Traits\Utilities\WithUpdatedData;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Ubah Artikel')]
class Edit extends Component
{
    use WithAuthorization, WithCategorySelector, WithToast, WithUpdatedData;

    public ArticleForm $form;

    public array $categories = [];

    public function mount(Article $article): void
    {
        $this->form->setArticle($article);

        $this->categories = Category::article()->pluck('name', 'id')->toArray();
    }

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

        $this->form->update();

        $this->redirectRoute('studio.manage.article.index', [
            'notification' => 'Artikel berhasil diperbarui.',
        ], navigate: true);
    }

    public function render(): View
    {
        return view('livewire.studio.manage.article.form', [
            'pageTitle' => 'Ubah Artikel',
            'categories' => Category::query()->where('type', CategoryType::ARTICLE)->orderBy('sort_order')->get(),
        ]);
    }
}
