<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\News;

class CategoryController extends Controller
{
    public function show(string $slug)
    {
        $category = Category::where('slug', $slug)->firstOrFail();

        // Paginated articles for this category
        $articles = News::with(['category', 'author'])
            ->where('category_id', $category->category_id)
            ->published()
            ->orderByDesc('news_id')
            ->paginate(15);

        // Featured (first) article for the big card at top
        $featuredArticle = $articles->first();

        // Latest news in the sidebar (all categories)
        $latestSidebar = News::with('category')
            ->where('category_id', '!=', $category->category_id)
            ->orderByDesc('news_id')
            ->take(5)
            ->get();

        // Other categories to suggest
        $otherCategories = Category::where('category_id', '!=', $category->category_id)
            ->withCount('news')
            ->orderByDesc('news_count')
            ->take(8)
            ->get();

        return view('category', compact(
            'category',
            'articles',
            'featuredArticle',
            'latestSidebar',
            'otherCategories'
        ));
    }
}
