<?php
namespace App\Http\Controllers;
use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ClientInfoController extends Controller
{
    public function getClients(Request $request)
    {
        if ($request->ajax()) {
            $search = trim($request->get('q', ''));
            $page = $request->get('page', 1);
            $perPage = 20;

            if (strlen($search) < 2) {
                return response()->json([
                    'results' => [],
                    'pagination' => ['more' => false]
                ]);
            }

            // OPTIMIZATION 1: Use JOIN instead of whereHas + with (single query instead of N+1)
            $query = Client::listWithPendingAndClose()
                ->join('clientsinfo', 'clients.id', '=', 'clientsinfo.client_id')
                ->select(
                    'clients.id',
                    'clients.userid',
                    'clientsinfo.clients_name',
                    'clientsinfo.contact_no'
                )
                ->where(function ($q) use ($search) {
                    $q->where('clients.userid', 'like', $search . '%') // OPTIMIZATION 2: Remove leading % for index usage
                        ->orWhere('clientsinfo.clients_name', 'like', $search . '%')
                        ->orWhere('clientsinfo.contact_no', 'like', $search . '%');
                })
                ->orderBy('clients.userid', 'asc');

            // OPTIMIZATION 3: Use offset/limit directly
            $clients = $query->offset(($page - 1) * $perPage)
                ->limit($perPage + 1)
                ->get();

            $hasMore = $clients->count() > $perPage;
            $clients = $clients->take($perPage);

            // OPTIMIZATION 4: Direct array mapping (faster than eloquent collections)
            $results = $clients->map(function ($client) {
                $text = $client->userid;
                if ($client->clients_name) {
                    $text .= ' - ' . $client->clients_name;
                }
                if ($client->contact_no) {
                    $text .= ' (' . $client->contact_no . ')';
                }
                return [
                    'id' => $client->id,
                    'text' => $text
                ];
            })->values()->all();

            return response()->json([
                'results' => $results,
                'pagination' => ['more' => $hasMore]
            ]);
        }
    }
}
