<?php

namespace App\Http\Controllers\Traits;

use Illuminate\Support\Facades\Gate;
use Illuminate\Database\Eloquent\Builder;

trait FilterTrait
{
    public $paginate = 20;

    public $groupPluck = false;

    public function handleIndex($request)
    {
        $variableName = $this->variableName . 's';

        $gateName = $this->variableName;
        $gateAccess = $this->variableName . "_access";
        $gateDelete = $this->variableName . "_delete";

        if (! Gate::allows($gateAccess)) {
            return abort(401);
        }

        $search_id = $request->query->get('search_id');

        if (request('show_deleted') == 1) {
            if (! Gate::allows($gateDelete)) {
                return abort(401);
            }

            $collection = $this->model::onlyTrashed()->get();
        } else {
            if (!empty($search_id)) {
                $collection = $this->search($search_id);
            } else {
                $collection = $this->model::paginate($this->paginate);
            }
        }

        if ($this->groupPluck) {
            $filterList = $this->filterModel::groupBy($this->pluckVariable)
                ->pluck($this->pluckVariable, 'id')->prepend(trans('quickadmin.qa_please_select'), '');
        } else {
            $filterList = $this->filterModel::get()
                ->pluck($this->pluckVariable, 'id')->prepend(trans('quickadmin.qa_please_select'), '');
        }

        return view('admin.' . $variableName .'.index', [
            $variableName => $collection,
            'filterList' => $filterList,
            'search_id' => $search_id,
            'model_key' => $variableName,
            'gate_key' => $gateName
        ]);
    }

    /**
     * @param $search_id
     * @return mixed
     */
    private function search($search_id)
    {
        $collection = $this->model::query();
        $collection = $this->filterQuery($collection, $search_id);

        return $collection->get();
    }

    protected function filterQuery(Builder $query, $id)
    {
        return $query->{$this->modelQuery}($id);
    }
}
