<?php

namespace App\Http\Controllers\Frontend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Project\app\Models\Project;
use Modules\Shop\app\Models\Product;
use Modules\Service\app\Models\Service;

class SearchController extends Controller
{
    public function search(Request $request)
    {
		$query = $request->input('q');
	
		if (!$query) {
			return response()->json(['error' => 'Search query is required.'], 400);
		}
		
		//Search in Products
		$products = Product::select('id', 'slug', 'image')
					->with(['translation' => function ($query) {
						$query->select('product_id', 'title');
					}])
					->whereHas('translation', function ($q) use ($query) {
						$q->where('title', 'LIKE', "%{$query}%");
					})
					->active()
					->latest()
					->get();
	
		//Search in Service
		$services = Service::select('id', 'slug', 'image')
					->with(['translation' => function ($query) {
						$query->select('service_id', 'title');
					}])
					->whereHas('translation', function ($q) use ($query) {
						$q->where('title', 'LIKE', "%{$query}%");
					})
					->active()
					->latest()
					->get();
	
		//Search in Projects
		$projects = Project::select('id', 'slug', 'image')
					->with(['translation' => function ($query) {
						$query->select('project_id', 'title');
					}])
					->whereHas('translation', function ($q) use ($query) {
						$q->where('title', 'LIKE', "%{$query}%");
					})
					->active()
					->latest()
					->get();
	
	
		// Combine and return results
			return view('frontend.pages.search', [
				'services' => $services,
				'projects' => $projects,
				'products' => $products,
			]);
	}
}
