<?php

namespace Modules\Catalog\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Routing\Controller;
use Modules\Catalog\Http\Resources\DestinationResource;
use Modules\Catalog\Models\Destination;

class DestinationController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $terms = array_filter(array_map(
            trim(...),
            explode(',', (string) $request->string('search')),
        ));

        return DestinationResource::collection(
            Destination::query()
                ->where('is_active', true)
                ->when($terms !== [], fn ($query) => $query->where(function ($query) use ($terms) {
                    foreach ($terms as $term) {
                        $query->orWhere('name', 'ilike', "%{$term}%")
                            ->orWhere('mm_name', 'ilike', "%{$term}%");
                    }
                }))
                ->paginate()
        );
    }
}
