<?php namespace AhmadFatoni\ApiGenerator\Controllers\API;

use Cms\Classes\Controller;
use BackendMenu;

use Illuminate\Http\Request;
use AhmadFatoni\ApiGenerator\Helpers\Helpers;
use Illuminate\Support\Facades\Validator;
use RainLab\Blog\Classes\CategoryResource;
use RainLab\Blog\Models\Category;
class CategoriesController extends Controller
{
	protected $Category;

    protected $helpers;

    public function __construct(Category $Category, Helpers $helpers)
    {
        parent::__construct();
        $this->Category    = $Category;
        $this->helpers          = $helpers;
    }

    public function index(Request $request){

        $data = $request->all();

        $validator = Validator::make($data, [
            'locale' => 'required|in:ru,en,tm',
            'count' => 'numeric',
            'sort_order' => 'in:asc,desc'
        ]);

        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }


        return response()->json(
            CategoryResource::collection($this->Category::orderBy('nest_left', $data['sort_order'] ?? 'asc')
                ->paginate($data['count'] ?? 7))->response()->getData(), 200);
    }



    public static function getAfterFilters() {return [];}
    public static function getBeforeFilters() {return [];}
    public static function getMiddleware() {return [];}
    public function callAction($method, $parameters=false) {
        return call_user_func_array(array($this, $method), $parameters);
    }

}
