<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Category;
use App\Models\Setting;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function show($slug)
    {
        $post = Post::where('slug', $slug)
            ->where('status', 'published')
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->with(['user', 'category', 'images'])
            ->firstOrFail();

        // Incrementar visualizações
        $post->increment('views');

        // Notícias relacionadas
        $related = Post::where('category_id', $post->category_id)
            ->where('id', '!=', $post->id)
            ->where('status', 'published')
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->orderBy('published_at', 'desc')
            ->limit(6)
            ->get();

        // Mais lidas
        $mostRead = Post::where('status', 'published')
            ->where('id', '!=', $post->id)
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->orderBy('views', 'desc')
            ->limit(5)
            ->get();

        $template = Setting::get('active_template', 'v1');

        if ($template === 'v2') {
            return view('frontend.v2.post', compact('post', 'related', 'mostRead'));
        }

        return view('frontend.v1.post', compact('post', 'related', 'mostRead'));
    }

    public function search(Request $request)
    {
        $query = $request->get('q', '');
        
        $posts = Post::where('status', 'published')
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->where(function($q) use ($query) {
                $q->where('title', 'like', '%' . $query . '%')
                  ->orWhere('body', 'like', '%' . $query . '%')
                  ->orWhere('excerpt', 'like', '%' . $query . '%');
            })
            ->orderBy('published_at', 'desc')
            ->paginate(12);

        $template = Setting::get('active_template', 'v1');

        return view('frontend.' . $template . '.search', compact('posts', 'query'));
    }
}

