<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Application;
use App\Models\Employee;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\RenewalOpportunity;
use App\Models\SupportTicket;
use App\Models\Tenant;
use App\Services\CustomerSearchService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GlobalSearchController extends Controller
{
    public function __invoke(Request $request, CustomerSearchService $customerSearch): JsonResponse
    {
        $query = trim((string) $request->query('q', ''));
        if (mb_strlen($query) < 2) {
            return response()->json(['results' => []]);
        }

        if (auth()->user()->isPlatformUser()) {
            $results = collect();
            Tenant::withoutGlobalScopes()->where(function ($builder) use ($query) {
                $builder->where('company_name', 'like', "%{$query}%")
                    ->orWhere('slug', 'like', "%{$query}%")
                    ->orWhere('email', 'like', "%{$query}%")
                    ->orWhere('mobile', 'like', "%{$query}%")
                    ->orWhere('trn', 'like', "%{$query}%");
            })->limit(8)->get()->each(fn ($tenant) => $results->push([
                'type' => 'Tenant', 'title' => $tenant->company_name,
                'subtitle' => $tenant->email.' · '.$tenant->status,
                'url' => route('platform.tenants.show', $tenant->id),
            ]));
            SupportTicket::withoutGlobalScopes()->where(function ($builder) use ($query) {
                $builder->where('ticket_code', 'like', "%{$query}%")->orWhere('subject', 'like', "%{$query}%");
            })->limit(4)->get()->each(fn ($ticket) => $results->push([
                'type' => 'Support', 'title' => $ticket->ticket_code,
                'subtitle' => $ticket->subject.' · '.$ticket->status,
                'url' => route('platform.support.show', $ticket->id),
            ]));

            return response()->json(['results' => $results->take(12)->values()]);
        }

        $tenant = auth()->user()->tenant;
        $master = $customerSearch->search($tenant, $query);
        $results = collect();

        foreach ($master['customers']->take(5) as $customer) {
            $results->push([
                'type' => 'Customer', 'title' => $customer->full_name_en,
                'subtitle' => $customer->customer_code.' · '.($customer->contact?->primary_mobile ?? 'No mobile'),
                'url' => route('app.customers.show', $customer->id),
            ]);
        }

        foreach ($master['companies']->take(3) as $company) {
            $results->push([
                'type' => 'Corporate', 'title' => $company->name_en,
                'subtitle' => $company->company_code.' · '.($company->trade_license_number ?: 'Company account'),
                'url' => route('app.corporate.companies.show', $company->id),
            ]);
        }

        Application::with(['customer', 'service'])
            ->where('application_number', 'like', "%{$query}%")
            ->limit(4)->get()->each(function ($application) use ($results) {
                $results->push([
                    'type' => 'Application', 'title' => $application->application_number,
                    'subtitle' => ($application->customer?->full_name_en ?? 'Customer').' · '.($application->service?->name_en ?? $application->status),
                    'url' => route('app.applications.show', $application->id),
                ]);
            });

        Invoice::with('customer')->where('invoice_number', 'like', "%{$query}%")
            ->limit(3)->get()->each(function ($invoice) use ($results) {
                $results->push([
                    'type' => 'Invoice', 'title' => $invoice->invoice_number,
                    'subtitle' => 'AED '.number_format((float) $invoice->balance_due, 2).' balance · '.$invoice->status,
                    'url' => route('app.billing.invoices.show', $invoice->id),
                ]);
            });

        if (auth()->user()->hasPermission('employees.view')) {
            Employee::with(['branch', 'department'])->where(function ($builder) use ($query) {
                $builder->where('employee_code', 'like', "%{$query}%")
                    ->orWhere('full_name', 'like', "%{$query}%")
                    ->orWhere('mobile', 'like', "%{$query}%")
                    ->orWhere('email', 'like', "%{$query}%")
                    ->orWhere('passport_number', 'like', "%{$query}%")
                    ->orWhere('emirates_id', 'like', "%{$query}%");
            })->limit(4)->get()->each(function ($employee) use ($results) {
                $results->push([
                    'type' => 'Employee', 'title' => $employee->full_name,
                    'subtitle' => $employee->employee_code.' · '.($employee->branch?->name ?? $employee->designation),
                    'url' => route('app.employees.show', $employee->id),
                ]);
            });
        }

        if (auth()->user()->hasPermission('payments.view')) {
            Payment::with('invoice')->where(function ($builder) use ($query) {
                $builder->where('payment_number', 'like', "%{$query}%")
                    ->orWhere('transaction_reference', 'like', "%{$query}%");
            })->limit(3)->get()->each(function ($payment) use ($results) {
                $results->push([
                    'type' => 'Payment', 'title' => $payment->payment_number,
                    'subtitle' => 'AED '.number_format((float) $payment->amount, 2).' · '.$payment->status,
                    'url' => $payment->invoice ? route('app.billing.invoices.show', $payment->invoice_id) : route('app.cashier'),
                ]);
            });
        }

        RenewalOpportunity::with('customer')->where(function ($builder) use ($query) {
            $builder->where('renewal_number', 'like', "%{$query}%")
                ->orWhere('document_number', 'like', "%{$query}%");
        })->limit(3)->get()->each(function ($renewal) use ($results) {
            $results->push([
                'type' => 'Renewal', 'title' => $renewal->renewal_number,
                'subtitle' => ($renewal->customer?->full_name_en ?? str($renewal->entity_type)->title()).' · '.$renewal->expiry_date->format('d M Y'),
                'url' => route('app.renewals.show', $renewal->id),
            ]);
        });

        return response()->json(['results' => $results->take(16)->values()]);
    }
}
