<?php

namespace Modules\Blog\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Blog\Entities\Post;
use Modules\Blog\Entities\BlogCategory;
use Modules\Blog\Entities\BlogTag;

class BlogController extends Controller
{
    public function __construct()
    {
        // Middleware to check if blog is enabled
        $this->middleware(function ($request, $next) {
            if (function_exists('setting') && setting('blog_enabled', '0') != '1') {
                abort(404); // Or redirect to homepage with a message
            }
            return $next($request);
        });
    }

    public function index()
    {
        $posts = Post::where('is_published', true)
            ->where('published_at', '<=', now())
            ->orderBy('published_at', 'desc')
            ->paginate(10);
        return view('blog::frontend.index', compact('posts'));
    }

    public function show(Post $post)
    {
        if (!$post->is_published || $post->published_at > now()) {
            abort(404);
        }
        // Increment view count (simple version, can be made more robust)
        $post->increment('views_count');
        return view('blog::frontend.show', compact('post'));
    }

    public function category(BlogCategory $category)
    {
        $posts = $category->posts()->where('is_published', true)->where('published_at', '<=', now())->orderBy('published_at', 'desc')->paginate(10);
        return view('blog::frontend.category_archive', compact('posts', 'category'));
    }

    public function tag(BlogTag $tag)
    {
        $posts = $tag->posts()->where('is_published', true)->where('published_at', '<=', now())->orderBy('published_at', 'desc')->paginate(10);
        return view('blog::frontend.tag_archive', compact('posts', 'tag'));
    }
}