<?php

namespace App\Http\Controllers;

use App\Models\Person;
use Illuminate\Http\Request;

class PeopleSearchController extends Controller
{
    public function __invoke(Request $request)
    {
        $q = trim((string) $request->query('q', ''));
        if ($q === '') {
            return response()->json([]);
        }

        $familyId = (int) $request->integer('family_id');

        $results = Person::query()
            ->whereHas('user')
            ->when($familyId > 0, function ($q2) use ($familyId) {
                $q2->whereHas('families', fn ($fq) => $fq->where('families.id', $familyId));
            })
            ->where(function($w) use ($q){
                $w->where('first_name', 'LIKE', "%$q%")
                  ->orWhere('last_name', 'LIKE', "%$q%")
                  ->orWhereRaw("CONCAT(first_name, ' ', last_name) LIKE ?", ["%$q%"]);
            })
            ->with('user:id,name')
            ->take(10)
            ->get(['id','first_name','last_name','photo_url','user_id'])
            ->map(function ($p) {
                $display = trim(($p->first_name.' '.$p->last_name));
                if ($display === '') { $display = $p->user?->name ?? 'Member'; }
                return [
                    'id' => $p->user_id,
                    'name' => $display,
                    'avatar' => $p->photo_url ?: 'https://ui-avatars.com/api/?name='.urlencode($display),
                ];
            });

        return response()->json($results->values());
    }
}
