<?php

namespace App\Http\Controllers;

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

class SearchController extends Controller
{
    public function search(Request $request)
    {
        $query = $request->get('q', '');
        $category = $request->get('category');

        $products = Product::query()
            ->where('name', 'like', "%$query%")
            ->orWhere('description', 'like', "%$query%")
            ->when($category, fn($q) => $q->where('category_id', $category))
            ->with('category')
            ->paginate(12);

        $categories = Category::orderBy('name')->get();

        return view('search.results', compact('products', 'categories', 'query', 'category'));
    }
}
