<?php

namespace App\Http\Controllers;

use App\Models\BlogPost;
use App\Models\ForumTopic;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SearchController extends Controller
{
    public function index(Request $request): View
    {
        $q = $request->input('q', '');
        $blogResults = collect();
        $forumResults = collect();

        if (strlen($q) >= 2) {
            // Blog search
            $blogResults = BlogPost::published()
                ->with(['user', 'category'])
                ->where(function($query) use ($q) {
                    $query->where('title', 'like', "%{$q}%")
                          ->orWhere('content', 'like', "%{$q}%");
                })
                ->latest('published_at')
                ->limit(8)
                ->get();

            // Forum search
            $forumResults = ForumTopic::with(['user', 'category'])
                ->where(function($query) use ($q) {
                    $query->where('title', 'like', "%{$q}%")
                          ->orWhere('content', 'like', "%{$q}%");
                })
                ->latest('last_reply_at')
                ->limit(8)
                ->get();
        }

        return view('search.index', compact('q', 'blogResults', 'forumResults'));
    }
}
