<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

trait HasSearchRequest
{
    /**
     * Search where or in group
     *
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param string $value
     * @param array $fields
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function searchRequest(&$builder, $value, array $fields)
    {
        if (empty($value)) {
            return $builder;
        } else {
            $value = trim(strtolower($value));
            $builder = $builder->where(function ($query) use ($value, $fields) {
                foreach ($fields as $index => $field) {
                    if ($index === 0) {
                        $query = $query->whereRaw("LOWER($field) LIKE '%$value%'");
                    } else {
                        $query = $query->orWhereRaw("LOWER($field) LIKE '%$value%'");
                    }
                }
                return $query;
            });
            return $builder;
        }
    }
}
