<?php

namespace Licenzo\Traits\QueryBuilder;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Contracts\Database\Eloquent\Builder;

/**
 * Trait HasSearch
 *
 * This trait provides a scope for searching records based on specified fields.
 *
 * @package Licenzo\Traits\QueryBuilder
 * @version 1.0.0
 *
 * @method static Builder search($params)
 */

trait HasSearch
{
    public function scopeSearch(Builder $query, $params = null)
    {
        // If no search params or no searchable fields defined, return original query
        if (empty($params) || empty($this->searchables) || !is_array($this->searchables)) {
            return $query;
        }

        return $query->where(function (Builder $query) use ($params) {
            global $wpdb;
            $escapedParams = $wpdb->esc_like($params);
            foreach ($this->searchables as $field) {
                $query->orWhere($field, 'LIKE', '%' . $escapedParams . '%');
            }
        });
    }
}
