<?php

namespace App\Http\Controllers;

use App\Models\NewsPost;
use App\Models\Category;
use Illuminate\Http\Request;

class NewsController extends Controller
{
    public function index()
    {
        $featured = NewsPost::where('status', 'approved')->where('is_featured', true)->latest()->take(5)->get();
        $recent = NewsPost::where('status', 'approved')->latest()->paginate(10);
        $categories = Category::with('newsPosts')->get();
        return view('welcome', compact('featured', 'recent', 'categories'));
    }

    public function show($slug)
    {
        $post = NewsPost::where('slug', $slug)->firstOrFail();
        
        $viewed = session()->get('viewed_posts', []);
        if (!in_array($post->id, $viewed)) {
            $post->increment('view_count');
            session()->push('viewed_posts', $post->id);
        }

        return view('news.show', compact('post'));
    }

    public function category($slug)
    {
        $category = Category::where('slug', $slug)->firstOrFail();
        $news = NewsPost::where('category_id', $category->id)->where('status', 'approved')->latest()->paginate(10);
        return view('news.category', compact('category', 'news'));
    }
}
