<?php

namespace App\Http\Controllers;

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

class SearchController extends Controller
{
    public function search(Request $request)
    {
        $query = $request->input('query');
        
        // Search in products
        $products = Product::where('name', 'LIKE', "%{$query}%")
            ->orWhere('description', 'LIKE', "%{$query}%")
            ->where('is_active', 1)
            ->with(['category', 'subcategories', 'images'])
            ->get();

        // Search in categories
        $categories = Category::where('name', 'LIKE', "%{$query}%")
            ->where('status', 1)
            ->with('subcategories')
            ->get();

        // Search in subcategories
        $subcategories = Subcategory::where('name', 'LIKE', "%{$query}%")
            ->where('status', 1)
            ->with('category')
            ->get();

        // Find similar products based on category and subcategory
        $similarProducts = collect();
        if ($products->isNotEmpty()) {
            $categoryIds = $products->pluck('category_id')->unique();
            $subcategoryIds = $products->pluck('subcategory_id')->unique();

            $similarProducts = Product::where('is_active', 1)
                ->where(function ($query) use ($categoryIds, $subcategoryIds) {
                    $query->whereIn('category_id', $categoryIds)
                        ->orWhereIn('subcategory_id', $subcategoryIds);
                })
                ->whereNotIn('id', $products->pluck('id'))
                ->with(['category', 'subcategories', 'images'])
                ->limit(8)
                ->get();
        }

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