<?php

namespace App\Http\Controllers\Api;

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

class SearchController extends Controller
{
    public function searchGames(Request $request)
    {
        $query = $request->get('q', '');
        
        // If query too short, return empty
        if (strlen($query) < 2) {
            return response()->json([
                'success' => true,
                'games' => []
            ]);
        }
        
        // Search in categories (games)
        $games = Category::where('is_active', true)
            ->whereIn('category_type', ['game', 'voucher'])
            ->where(function($q) use ($query) {
                $q->where('name', 'LIKE', "%{$query}%")
                  ->orWhere('slug', 'LIKE', "%{$query}%")
                  ->orWhere('description', 'LIKE', "%{$query}%");
            })
            ->select('id', 'name', 'slug', 'image', 'category_type', 'is_popular')
            ->orderBy('is_popular', 'desc')
            ->orderBy('name', 'asc')
            ->limit(10)
            ->get();
        
        return response()->json([
            'success' => true,
            'games' => $games
        ]);
    }
}