<?php

namespace App\Livewire\Home\News;

use App\Models\Category;
use App\Models\News;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;
use Spatie\Tags\Tag;

#[Title('Berita')]
class Index extends Component
{
    use WithPagination;

    #[Url(as: 'q')]
    public $search = '';

    #[Url(as: 'category')]
    public $category = '';

    #[Url(as: 'tag')]
    public $tag = '';

    public function updatedSearch()
    {
        $this->resetPage();
    }

    public function updatedCategory()
    {
        $this->resetPage();
    }

    public function updatedTag()
    {
        $this->resetPage();
    }

    public function render()
    {
        $news = News::published()
            ->with(['categories', 'author'])
            ->when($this->search, function ($query) {
                $query->where('title', 'like', '%'.$this->search.'%')
                    ->orWhere('content', 'like', '%'.$this->search.'%');
            })
            ->when($this->category, function ($query) {
                $query->whereHas('categories', function ($query) {
                    $query->where('categories.id', $this->category);
                });
            })
            ->when($this->tag, function ($query) {
                $query->withAnyTags([$this->tag]);
            })
            ->latest('published_at')
            ->paginate(5)
            ->through(function ($news) {
                $news->thumbnail = $news->getFirstMediaUrl('news') ?: 'https://images.pexels.com/photos/12199409/pexels-photo-12199409.jpeg';
                $news->formatted_date = $news->published_at?->translatedFormat('d F Y') ?: '-';
                $news->author_name = $news->author?->name ?: 'Admin';
                $news->formatted_views = number_format($news->views).' Views';
                $news->excerpt = str($news->content)->stripTags()->limit(160);

                return $news;
            });

        $categories = Category::active()
            ->withCount(['news' => function ($query) {
                $query->published();
            }])
            ->orderBy('name')
            ->get();

        $popularPosts = News::published()
            ->latest('views')
            ->limit(3)
            ->get()
            ->map(function ($news) {
                $news->thumbnail = $news->getFirstMediaUrl('news') ?: 'https://images.pexels.com/photos/12199409/pexels-photo-12199409.jpeg';
                $news->formatted_date = $news->published_at?->translatedFormat('d F Y') ?: '-';

                return $news;
            });

        return view('livewire.home.news.index', [
            'pageTitle' => 'Berita',
            'pageDescription' => 'Jelajahi berita terbaru seputar purwakarta.',
            'news' => $news,
            'popularPosts' => $popularPosts,
            'categories' => $categories,
            'tags' => Tag::all(),
        ]);
    }
}
