<?php

namespace App\Classes\General\Eloquent;


use App\Classes\Exceptions\MalformedRequestException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;

abstract class AbstractListRecord extends AbstractGetRecord
{


    /**
     * @param array $filters
     * @return mixed
     * @throws MalformedRequestException
     */
    public function execute(array $filters = [], array $param = []){

        try{
            return $this->handler($filters, $param);

        } catch (QueryException $exception){
            throw new MalformedRequestException('Unable to fetch the list of records due to unexpected error');
        }

    }

    /**
     * @param Builder $query
     * @return mixed
     */
    public function getResults(Builder $query, array $param = []) {
        $filters = $this->getDecorationFilters();

        if($filters->has('order_by')){
            $query = $query->orderBy($filters->get('order_by')->column, $filters->get('order_by')->DESC ? 'DESC': 'ASC');
        }

        if($filters->has('group_by')){
            $query = $query->groupBy($filters->get('group_by')->column);
        }

        //dd($query->toSql());
        if(!empty($param)){
            return $filters->has('per_page') ? $query->paginate($filters->get('per_page'), ['*'], 'page', $param['page']) : $query->get(); //page data from query parameters e.g ?page=1
        }
        else{
            return $filters->has('per_page') ? $query->paginate($filters->get('per_page')) : $query->get();
        }
    }

}
