<?php

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class SearchController extends Controller
{
    public function index(Request $request)
    {
        $q = trim((string) $request->query('q', ''));
        $results = collect();

        if (Str::length($q) >= 2) {
            // Services (config-backed)
            foreach (config('brokam.services') as $service) {
                if (Str::contains(Str::lower($service['title'] . ' ' . $service['tagline'] . ' ' . $service['summary']), Str::lower($q))) {
                    $results->push([
                        'type'  => 'Service',
                        'title' => $service['title'],
                        'excerpt' => $service['tagline'],
                        'url'   => route('services.show', $service['slug']),
                    ]);
                }
            }

            // Projects
            Project::published()
                ->where(fn ($w) => $w->where('title', 'like', "%{$q}%")
                    ->orWhere('summary', 'like', "%{$q}%")
                    ->orWhere('client', 'like', "%{$q}%"))
                ->get()
                ->each(fn ($p) => $results->push([
                    'type'    => 'Project',
                    'title'   => $p->title,
                    'excerpt' => $p->summary,
                    'url'     => route('projects.show', $p),
                ]));

            // Articles
            Article::published()
                ->where(fn ($w) => $w->where('title', 'like', "%{$q}%")
                    ->orWhere('excerpt', 'like', "%{$q}%")
                    ->orWhere('body', 'like', "%{$q}%"))
                ->get()
                ->each(fn ($a) => $results->push([
                    'type'    => 'News',
                    'title'   => $a->title,
                    'excerpt' => $a->excerpt,
                    'url'     => route('news.show', $a),
                ]));
        }

        return view('pages.search', [
            'query'   => $q,
            'results' => $results,
        ]);
    }
}
