<?php
namespace App\Http\Controllers;

use App\Models as M;
use Illuminate\Http\Request;

class SearchController extends Controller {
    /** A6 global search: perm => [model, registry key, group label, searchable columns]. */
    public const MAP = [
        'sales.view' => [
            [M\Customer::class, 'customers', 'Customers', ['code', 'name']],
            [M\SalesInvoice::class, 'sales-invoices', 'Invoices', ['invoice_no']],
            [M\Quotation::class, 'quotations', 'Quotations', ['quotation_no']],
        ],
        'purchase.view' => [
            [M\Supplier::class, 'suppliers', 'Suppliers', ['code', 'name']],
            [M\PurchaseOrder::class, 'purchase-orders', 'LPOs', ['po_no']],
        ],
        'fleet.view' => [[M\Equipment::class, 'equipment', 'Equipment', ['code', 'name']]],
        'hr.view' => [[M\Employee::class, 'employees', 'Employees', ['employee_no', 'first_name', 'last_name']]],
        'projects.view' => [[M\Project::class, 'projects', 'Projects', ['code', 'name']]],
        'production.view' => [[M\Product::class, 'products', 'Products', ['code', 'name']]],
        'finance.view' => [[M\Journal::class, 'journals', 'Journals', ['journal_no', 'narration']]],
    ];

    public function query(Request $r) {
        $q = trim((string) $r->get('q', ''));
        if (strlen($q) < 2) return response()->json(['groups' => []]);
        $u = $r->user();
        $groups = [];
        foreach (self::MAP as $perm => $entities) {
            if (!$u->canDo($perm)) continue;
            foreach ($entities as [$model, $key, $label, $cols]) {
                $rows = $model::query()->where(function ($w) use ($cols, $q) {
                    foreach ($cols as $c) $w->orWhere($c, 'like', '%'.$q.'%');
                })->take(6)->get();
                if ($rows->isEmpty()) continue;
                $groups[] = ['label' => $label, 'items' => $rows->map(fn($row) => [
                    'title' => $model === M\Employee::class
                        ? trim($row->first_name.' '.$row->last_name).' ('.$row->employee_no.')'
                        : $row->display_name,
                    'url' => crud_url($key, 'show', $row->id),
                ])->all()];
            }
        }
        return response()->json(['groups' => $groups]);
    }
}
