<?php
namespace App\Http\Livewire;

use LaravelViews\Data\Contracts\Filterable;
use LaravelViews\Data\Contracts\Searchable;
use LaravelViews\Data\Contracts\Sortable;
use Illuminate\Database\Eloquent\Builder;
use DateTime; 

trait ConfigSearch
{
    /**
     * Sobrescribe la lógica de búsqueda + filtros + orden
     */
    public function getQueryProperty(Searchable $searchable, Filterable $filterable, Sortable $sortable): Builder
    {
        // Clonamos la consulta original
        $query = clone $this->initialQuery;

        // 1) BÚSQUEDA case-insensitive
        if ($this->search) {
            $searchTerm = $this->search;
            $query->where(function (Builder $q) use ($searchTerm) {
                foreach ($this->searchBy as $attribute) {
                    if (str_contains($attribute, '.')) {
                        // atributo en relación: p.ej. patient.firstname
                        [$relation, $column] = explode('.', $attribute, 2);
                        $q->orWhereHas($relation, function (Builder $qr) use ($column, $searchTerm) {
                            $qr->where($column, 'ilike', "%{$searchTerm}%");
                        });
                    } else {
                        // columna directa
                        $q->orWhere($attribute, 'ilike', "%{$searchTerm}%");
                    }
                }
            });
        }

        // 2) APLICAR filtros y 3) ORDEN
        $query = $filterable->applyFilters($query, $this->filters(), $this->filters);
        $query = $sortable->sortItems($query, $this->sortBy, $this->sortOrder);

        return $query;
    }
}