<?php

namespace App\Livewire\Studio\Manage\Article;

use App\Enums\CategoryType;
use App\Jobs\StorePushNotification;
use App\Livewire\Forms\Studio\Manage\ArticleForm;
use App\Models\Category;
use App\Models\PushNotification;
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 Illuminate\Support\Str;
use Livewire\Attributes\Title;
use Livewire\Component;

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

    public ArticleForm $form;

    public array $categories = [];

    public function mount(): void
    {
        $this->categories = Category::article()->pluck('name', 'id')->toArray();
    }

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

        $result = $this->form->store();

        StorePushNotification::dispatch(
            PushNotification::all(),
            [
                'title' => '📝 Artikel Baru!',
                'body' => Str::limit($result, 50).' '.' ✨ Yuk baca selengkapnya di aplikasi!',
            ],
        );

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

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