<?php

namespace App;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

trait SearchTrait
{
    /**
     * @param \Illuminate\Database\Eloquent\Builder|static $query
     * @param string $keyword
     * @param boolean $matchAllFields
     */
    public static function scopeSearchFields($query, $keyword, $matchAllFields = false)
    {

        return static::where(function ($query) use ($keyword, $matchAllFields) {
            foreach (static::getSearchFields() as $field) {
                if ($matchAllFields) {
                    $query->where($field, 'LIKE', "%$keyword%");
                } else {
                    $query->orWhere($field, 'LIKE', "%$keyword%");
                }
            }
        });
    }

    /**
     * Get all searchable fields
     *
     * @return array
     */
    public static function getSearchFields($getInfo = false)
    {
        $model = new static;
        $module_name = lcfirst(substr(strrchr(get_class($model), "\\"), 1));
        $moduleInfo = $model::makeInfo($module_name);
        $fields = [];
        if (isset($moduleInfo['config']['forms'])) {

            if ($getInfo)
                return $moduleInfo['config']['forms'];

            foreach ($moduleInfo['config']['forms'] as $form)
                if ($form['search'] == 1 && !in_array($form['type'], ['hidden', 'select_relation']))
                    $fields[] = $form['alias'] . '.' . $form['field'];
        }
        if (empty($fields)) {
            $fields = Schema::getColumnListing($model->getTable());
            $others[] = $model->primaryKey;
            $others[] = $model->getUpdatedAtColumn() ?: 'created_at';
            $others[] = $model->getCreatedAtColumn() ?: 'updated_at';
            $others[] = method_exists($model, 'getDeletedAtColumn')
                ? $model->getDeletedAtColumn()
                : 'deleted_at';
            $fields = array_diff($fields, $model->getHidden(), $others);
        }
        return $fields;
    }
}