<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Request;
use App\Models\Account;
use App\Models\Contact;
use App\Models\Lead;
use App\Models\Opportunity;

final class SearchController extends BaseController
{
    public function index(Request $request): void
    {
        $q = $this->q();
        if (mb_strlen($q) < 2) {
            json_out(['ok' => true, 'groups' => []]);
        }
        $groups = [];
        if (can_see('accounts')) {
            $rows = Account::search($q);
            if ($rows) {
                $groups[] = ['label' => 'Accounts', 'items' => array_map(static fn($r) => [
                    'title' => $r['name'],
                    'meta' => $r['email'] ?: $r['phone'],
                    'url' => url('accounts/' . $r['id']),
                ], $rows)];
            }
        }
        if (can_see('contacts')) {
            $rows = Contact::search($q);
            if ($rows) {
                $groups[] = ['label' => 'Contacts', 'items' => array_map(static fn($r) => [
                    'title' => trim($r['first_name'] . ' ' . $r['last_name']),
                    'meta' => $r['account_name'] . ($r['email'] ? ' · ' . $r['email'] : ''),
                    'url' => url('contacts/' . $r['id']),
                ], $rows)];
            }
        }
        if (can_see('leads')) {
            $rows = Lead::search($q);
            if ($rows) {
                $groups[] = ['label' => 'Leads', 'items' => array_map(static fn($r) => [
                    'title' => trim($r['first_name'] . ' ' . $r['last_name']),
                    'meta' => $r['company'] ?: ($r['email'] ?: $r['phone']),
                    'url' => url('leads/' . $r['id']),
                ], $rows)];
            }
        }
        if (can_see('opportunities')) {
            $rows = Opportunity::search($q);
            if ($rows) {
                $groups[] = ['label' => 'Opportunities', 'items' => array_map(static fn($r) => [
                    'title' => $r['name'],
                    'meta' => $r['account_name'] . ' · ' . $r['stage_name'],
                    'url' => url('opportunities/' . $r['id']),
                ], $rows)];
            }
        }
        json_out(['ok' => true, 'groups' => $groups]);
    }
}
