<?php

namespace App\Livewire\Website;

use App\Domain\Website\Models\WebsiteNews;
use App\Domain\Website\Services\WebsiteCacheService;
use Illuminate\Support\Str;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('الأخبار')]
class NewsManager extends Component
{
    public bool $showForm = false;
    public ?int $editingId = null;

    public string $title = '';
    public string $title_en = '';
    public string $body = '';
    public string $body_en = '';
    public string $excerpt = '';
    public string $excerpt_en = '';
    public bool $is_featured = false;

    public function mount(): void
    {
        $this->authorize('settings.manage');
    }

    public function create(): void
    {
        $this->reset(['title', 'title_en', 'body', 'body_en', 'excerpt', 'excerpt_en', 'is_featured', 'editingId']);
        $this->showForm = true;
    }

    public function edit(int $id): void
    {
        $news = WebsiteNews::find($id);
        if (!$news) return;

        $this->editingId = $id;
        $this->title = $news->title;
        $this->title_en = $news->title_en ?? '';
        $this->body = $news->body;
        $this->body_en = $news->body_en ?? '';
        $this->excerpt = $news->excerpt ?? '';
        $this->excerpt_en = $news->excerpt_en ?? '';
        $this->is_featured = $news->is_featured;
        $this->showForm = true;
    }

    public function save(): void
    {
        $this->validate([
            'title' => 'required|string|max:255',
            'body' => 'required|string',
        ]);

        $data = [
            'title' => $this->title,
            'title_en' => $this->title_en ?: null,
            'body' => $this->body,
            'body_en' => $this->body_en ?: null,
            'excerpt' => $this->excerpt ?: Str::limit($this->body, 150),
            'excerpt_en' => $this->excerpt_en ?: null,
            'is_featured' => $this->is_featured,
        ];

        if ($this->editingId) {
            WebsiteNews::find($this->editingId)->update($data);
        } else {
            $data['slug'] = Str::slug($this->title) ?: Str::random(8);
            $data['created_by'] = auth()->id();
            $data['published_at'] = now();
            WebsiteNews::create($data);
        }

        app(WebsiteCacheService::class)->invalidate(app('current_academy')->id);
        $this->showForm = false;
        session()->flash('success', __('تم الحفظ بنجاح'));
    }

    public function delete(int $id): void
    {
        WebsiteNews::find($id)?->delete();
        app(WebsiteCacheService::class)->invalidate(app('current_academy')->id);
        session()->flash('success', __('تم الحذف'));
    }

    public function render()
    {
        return view('livewire.website.news-manager', [
            'news' => WebsiteNews::orderByDesc('published_at')->get(),
        ]);
    }
}
