<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Ticket;
use App\Models\User;
use App\Models\Vehicle;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function __invoke(Request $request)
    {
        $query = $request->input('q', '');

        if (strlen($query) < 2) {
            return response()->json(['results' => []]);
        }

        $results = [];

        // Search Customers
        $customers = User::where('role', 'CUSTOMER')
            ->where(fn ($q) => $q->where('name', 'like', "%{$query}%")
                ->orWhere('email', 'like', "%{$query}%")
                ->orWhere('phone', 'like', "%{$query}%"))
            ->limit(5)
            ->get()
            ->map(fn ($u) => [
                'type' => 'عميل',
                'title' => $u->name,
                'subtitle' => $u->email,
                'url' => route('admin.users.show', $u),
                'icon' => 'user',
            ]);

        // Search Invoices
        $invoices = Invoice::where('invoice_number', 'like', "%{$query}%")
            ->limit(5)
            ->get()
            ->map(fn ($i) => [
                'type' => 'فاتورة',
                'title' => $i->invoice_number,
                'subtitle' => number_format($i->total_amount, 2).' ج.م',
                'url' => route('admin.finance.show', $i),
                'icon' => 'file-text',
            ]);

        // Search Vehicles
        $vehicles = Vehicle::where(fn ($q) => $q->where('make', 'like', "%{$query}%")
            ->orWhere('model', 'like', "%{$query}%")
            ->orWhere('vin', 'like', "%{$query}%")
            ->orWhere('stock_number', 'like', "%{$query}%"))
            ->limit(5)
            ->get()
            ->map(fn ($v) => [
                'type' => 'سيارة',
                'title' => $v->make.' '.$v->model.' '.$v->year,
                'subtitle' => $v->stock_number,
                'url' => route('admin.vehicles.show', $v),
                'icon' => 'truck',
            ]);

        // Search Tickets
        $tickets = Ticket::where(fn ($q) => $q->where('ticket_number', 'like', "%{$query}%")
            ->orWhere('subject', 'like', "%{$query}%"))
            ->limit(5)
            ->get()
            ->map(fn ($t) => [
                'type' => 'تذكرة',
                'title' => $t->ticket_number,
                'subtitle' => $t->subject,
                'url' => route('admin.support.tickets.show', $t),
                'icon' => 'headphones',
            ]);

        $results = $customers->concat($invoices)->concat($vehicles)->concat($tickets);

        if ($request->wantsJson()) {
            return response()->json(['results' => $results, 'query' => $query]);
        }

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