<?php


namespace App\Filters;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DemandFilters
{
    protected $request;
    protected $queryBuilder;
    protected $filters = ['created_at_start', 'created_at_end', 'type'];
    protected $array_filter;
    protected $params = [];

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->params = $request->all();
        $this->array_filter = array_filter($this->request->only($this->filters));
    }

    public function apply($builder)
    {
        $this->queryBuilder = $builder;
        $this->before();
        foreach ($this->array_filter as $filter => $value) {
            if (method_exists($this, $filter)) {
                $this->$filter($value, $this->queryBuilder);
            }
        }
        return $this->queryBuilder;
    }

    public function created_at_start($created_at)
    {
        $this->queryBuilder->where('demands.created_at', '>=', $created_at . ' 00:00:00');
    }

    public function created_at_end($created_at)
    {
        $this->queryBuilder->where('demands.created_at', '<=', $created_at . ' 23:59:59');
    }

    public function type($type)
    {
        $this->queryBuilder->where('demands.type',$type);
    }

    public function before()
    {
        $user = Auth::user();
        if(!isset($user))return;
        if($user->isSuperAdmin()){
            return;
        }
        $authorities = $user->authorities();
        $authorities = data_get($authorities,'*.id');
        $authorities[] = null;
        $this->queryBuilder->whereIn('authority_id',$authorities);
    }
}
