<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\Quotation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    /**
     * Perform global search
     */
    public function search(Request $request): JsonResponse
    {
        $query = $request->get('q', '');

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

        $results = [];

        // Search invoices
        $invoices = Invoice::where('invoice_number', 'like', "%{$query}%")
            ->orWhereHas('customer', function ($q) use ($query) {
                $q->where('name', 'like', "%{$query}%")
                    ->orWhere('email', 'like', "%{$query}%");
            })
            ->limit(5)
            ->get();

        foreach ($invoices as $invoice) {
            $results[] = [
                'id' => 'invoice-'.$invoice->id,
                'title' => $invoice->invoice_number,
                'type' => 'Invoice',
                'icon' => 'description',
                'url' => route('admin.invoices.show', $invoice),
            ];
        }

        // Search customers
        $customers = Customer::where('name', 'like', "%{$query}%")
            ->orWhere('email', 'like', "%{$query}%")
            ->orWhere('company', 'like', "%{$query}%")
            ->limit(5)
            ->get();

        foreach ($customers as $customer) {
            $results[] = [
                'id' => 'customer-'.$customer->id,
                'title' => $customer->name.($customer->company ? ' - '.$customer->company : ''),
                'type' => 'Customer',
                'icon' => 'group',
                'url' => route('admin.customers.show', $customer),
            ];
        }

        // Search quotations
        $quotations = Quotation::where('quotation_number', 'like', "%{$query}%")
            ->orWhereHas('customer', function ($q) use ($query) {
                $q->where('name', 'like', "%{$query}%");
            })
            ->limit(3)
            ->get();

        foreach ($quotations as $quotation) {
            $results[] = [
                'id' => 'quotation-'.$quotation->id,
                'title' => $quotation->quotation_number,
                'type' => 'Quotation',
                'icon' => 'receipt_long',
                'url' => route('admin.quotations.show', $quotation),
            ];
        }

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