<?php

namespace App\Livewire\Home\Article;

use App\Models\Article;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('components.layouts.home', [
    'title' => 'Detail Artikel',
])]
class Show extends Component
{
    public Article $article;

    public array $latestArticles = [];

    public ?Article $previousArticle = null;

    public ?Article $nextArticle = null;

    public function mount(Article $article): void
    {
        $article->load(['author', 'author.employee', 'categories']);

        $this->article = $article;
        $this->article->increment('views');
        $article->thumbnail = $article->getFirstMediaUrl('thumbnail') ? $article->getFirstMediaUrl('thumbnail') : asset('assets/images/dark-logo.png');

        $this->latestArticles = Article::where('id', '!=', $article->id)
            ->published()
            ->orderBy('published_at', 'desc')
            ->take(5)
            ->get()
            ->map(function ($article) {
                $article->thumbnail = $article->getFirstMediaUrl('thumbnail') ? $article->getFirstMediaUrl('thumbnail') : asset('assets/images/dark-logo.png');

                return $article;
            })
            ->toArray();

        $this->previousArticle = Article::where('id', '<', $article->id)
            ->published()
            ->orderBy('published_at', 'desc')
            ->first();

        $this->nextArticle = Article::where('id', '>', $article->id)
            ->published()
            ->orderBy('published_at', 'asc')
            ->first();
    }

    public function render(): View
    {
        return view('livewire.home.article.show', [
            'pageTitle' => $this->article->title,
        ]);
    }
}
