<?php

namespace App\Http\Controllers;

use App\Models\Task;
use App\Models\Project;
use App\Models\User;
use App\Models\Comment;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index(Request $request)
    {
        $query = $request->get('q', '');
        $results = ['projects' => [], 'tasks' => [], 'users' => [], 'comments' => []];

        if (strlen($query) >= 2) {
            $companyId = $request->user()->company_id;

            $results['projects'] = Project::where('company_id', $companyId)
                ->where('name', 'like', "%{$query}%")
                ->with('owner')
                ->limit(5)->get();

            $results['tasks'] = Task::whereHas('project', fn ($q) => $q->where('company_id', $companyId))
                ->where(function ($q) use ($query) {
                    $q->where('title', 'like', "%{$query}%")
                      ->orWhere('description', 'like', "%{$query}%");
                })
                ->with(['project', 'assignee'])
                ->limit(10)->get();

            $results['users'] = User::where('company_id', $companyId)
                ->where(function ($q) use ($query) {
                    $q->where('name', 'like', "%{$query}%")
                      ->orWhere('email', 'like', "%{$query}%");
                })
                ->limit(5)->get();

            $results['comments'] = Comment::whereHas('task.project', fn ($q) => $q->where('company_id', $companyId))
                ->where('body', 'like', "%{$query}%")
                ->with(['task.project', 'user'])
                ->limit(5)->get();
        }

        if ($request->wantsJson()) {
            return response()->json($results);
        }

        return view('search.index', compact('query', 'results'));
    }
}
