<?php

namespace App\Http\Controllers\PublicSite;

use App\Http\Controllers\Controller;
use App\Models\News;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;

class NewsController extends Controller
{
    public function index(Request $request): View
    {
        $category = $request->string('category')->toString() ?: null;

        return view('public.news.index', [
            'articles' => News::published()
                ->when($category, fn ($q) => $q->where('category', $category))
                ->latestFirst()
                ->paginate(9)
                ->withQueryString(),
            'categories' => News::published()->whereNotNull('category')->distinct()->pluck('category'),
            'activeCategory' => $category,
        ]);
    }

    public function show(News $news): View
    {
        abort_unless($news->status->value === 'published', 404);

        return view('public.news.show', [
            'article' => $news->load('author:id,name'),
            'related' => News::published()
                ->whereKeyNot($news->id)
                ->latestFirst()
                ->take(3)
                ->get(),
        ]);
    }
}
