<?php

namespace App\Filters;

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

class QueryFilters
{
    protected $request;
    protected $builder;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function apply(Builder $builder)
    {
        $this->builder = $builder;
        foreach ($this->filters() as $name => $value) {
            if ((!method_exists($this, $name)) || $name == 'sortBy') {
                continue;
            }
            if (is_array($value)) {
                $this->$name($value);
            } else if (strlen($value)) {
                $this->$name($value);
            }
        }
        if (array_key_exists('sortBy', $this->filters())) {
            $this->sortBy($this->filters()['sortBy'], $this->filters()['direction'] ?? 'desc');
        }
        return  method_exists($this, 'sortBy') ? $this->sortBy('date', 'desc') : $this->builder;
    }

    public function filters()
    {
        return $this->request->all();
    }
}
