<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\BlogPost;
use App\Models\BlogCategory;
use App\Models\SeoMeta;

class BlogController extends Controller
{
    public function index()
    {
        $posts = BlogPost::with('category', 'author')
            ->published()
            ->orderBy('published_at', 'desc')
            ->paginate(9);

        $categories = BlogCategory::withCount('posts')->get();
        $recentPosts = BlogPost::published()->take(4)->get();
        $seo = SeoMeta::where('url_path', '/blog')->first();

        return view('public.blog', compact('posts', 'categories', 'recentPosts', 'seo'));
    }

    public function show(string $slug)
    {
        $post = BlogPost::with('category', 'author')
            ->where('slug', $slug)
            ->where('is_published', true)
            ->firstOrFail();

        $post->increment('views_count');

        $relatedPosts = BlogPost::published()
            ->where('id', '!=', $post->id)
            ->take(3)
            ->get();

        return view('public.blog-show', compact('post', 'relatedPosts'));
    }
}
