<?php

namespace App\Http\Controllers;

use App\AdminSearchRepository;
use App\Http\Requests\SearchRequest;
use App\Http\Resources\SearchResponse;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Mtc\ContentManager\Contracts\FormField;
use Mtc\MercuryDataModels\ContentElement;
use Mtc\MercuryDataModels\GlobalContent;
use Mtc\MercuryDataModels\Vehicle;

class SearchController extends Controller
{
    /**
     * Search for any type records on site
     *
     * @param SearchRequest $request
     * @return SearchResponse
     */
    public function index(SearchRequest $request, AdminSearchRepository $repository)
    {
        return new SearchResponse($repository->search($request));
    }


    /**
     * Search for content elements
     *
     * @param SearchRequest $request
     * @return Collection
     */
    public function elements(SearchRequest $request)
    {
        $global = GlobalContent::query()
            ->when(
                $request->filled('term'),
                fn ($query) => $query->where('name', 'like', '%' . $request->input('term') . '%')
            )
            ->get();

        $elements = ContentElement::query()
            ->with('fields.childElement.fields.childElement.fields.childElement.fields')
            ->where('is_enabled', 1)
            ->when($request->input('drag_and_drop'), fn($query) => $query->where('drag_and_drop', 1))
            ->when(
                $request->filled('term'),
                fn ($query) => $query->where(fn($search) => $search
                    ->where('title', 'like', '%' . $request->input('term') . '%')
                    ->orWhere('subtitle', 'like', '%' . $request->input('term') . '%'))
            )
            ->get();
        $resource = config('pages.content_element_block_resource');
        $term = $request->input('term');

        return collect(config('pages.block_categories'))
            ->map(fn ($category) => [
                'name' => $category['name'],
                'items' => new $resource($elements->filter(fn ($element) => $element->category === $category['id'])),
                'icon' => $category['icon'] ?? '',
            ])
            ->when(
                $request->filled('primitives'),
                fn(Collection $collection) => $collection
                    ->prepend([
                        'name' => 'Primitives',
                        'items' => new $resource(collect(config('pages.field_types', []))
                            ->map(fn($type) => App::make($type))
                            ->filter(fn(FormField $type) => stripos((string) $type::NAME, (string) $term) !== false)
                            ->values()),
                        'icon' => 'shapes',
                    ])
            )
            ->push([
                'name' => 'Global',
                'items' => new $resource($global),
                'icon' => 'globe-stand',
            ]);
    }

    /**
     * Search for vehicles
     *
     * @param SearchRequest $request
     * @return LengthAwarePaginator
     */
    public function vehicles(SearchRequest $request): LengthAwarePaginator
    {
        return Vehicle::query()
            ->with(['make', 'model'])
            ->whereFullText('search_content', $request->input('term'))
            ->paginate();
    }

    public function getFilters(string $type, AdminSearchRepository $repository): array
    {
        return $repository->getSectionFilters($type);
    }
}
