<?php

namespace App\Traits;

trait FilterModel
{
    public function scopeFilter($builder, $filters = [])
    {
        if (!$filters) {
            return $builder;
        }

        $tableName = $this->getTable();
        $defaultFillableFields = $this->fillable;

        foreach ($filters as $field => $value) {
            //Validar que la key exista y el value no sea null
            if (!in_array($field, $defaultFillableFields) || is_null($value)) {
                continue;
            }

            //Filtro para campos de tipo Boolean
            if (in_array($field, $this->boolFilterFields)) {
                $builder->where($field, boolval($value));
            }
            //Filtro para campos con LIKE
            elseif (in_array($field, $this->likeFilterFields)) {
                $builder->where($field, 'LIKE', "%$value%");
            }
            //Filtro defecto
            else {
                $builder->where($field, '=', $value);
            }
        }

        return $builder;
    }
}
