<?php

namespace App\Http\Controllers;

use App\Models\Items;
use App\Models\StoreCategory;
use App\Models\Gender;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function search(Request $request)
    {
        $query = $request->get('q');
        
        if (empty($query) || strlen($query) < 2) {
            return response()->json([
                'success' => true,
                'results' => [],
                'message' => 'Please enter at least 2 characters'
            ]);
        }

        // Search products
        $products = Items::where('is_publish', true)
            ->where('deleted_at', null)
            ->where(function($q) use ($query) {
                $q->where('name', 'ILIKE', "%{$query}%")
                  ->orWhere('number', 'ILIKE', "%{$query}%")
                  ->orWhere('description', 'ILIKE', "%{$query}%");
            })
            ->select('id', 'name', 'number', 'slug')
            ->limit(8)
            ->get();

        // Search categories
        $categories = StoreCategory::where('name', 'ILIKE', "%{$query}%")
            ->select('id', 'name')
            ->limit(3)
            ->get();

        // Search genders
        $genders = Gender::where('name', 'ILIKE', "%{$query}%")
            ->select('id', 'name')
            ->limit(3)
            ->get();

        // Format results
        $results = [];

        if ($products->isNotEmpty()) {
            $results['products'] = $products->map(function($product) {
                $price = $product->display_price;
                return [
                    'id' => $product->id,
                    'name' => $product->name,
                    'number' => $product->number,
                    'slug' => $product->slug ?? $product->id,
                    'type' => 'product',
                    'route' => route('product.detail', $product->slug)
                ];
            });
        }

        if ($categories->isNotEmpty()) {
            $results['categories'] = $categories->map(function($category) {
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'slug' => $category->slug,
                    'type' => 'category',
                    'route' => route('product.index',['filter[category]'=>$category->id])
                ];
            });
        }

        if ($genders->isNotEmpty()) {
            $results['genders'] = $genders->map(function($gender) {
                return [
                    'id' => $gender->id,
                    'name' => $gender->name,
                    'slug' => $gender->slug,
                    'type' => 'gender',
                    'route' => route('product.index',['filter[gender]'=>$gender->id])
                ];
            });
        }

        return response()->json([
            'success' => true,
            'results' => $results,
            'query' => $query
        ]);
    }
}
