<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryApiResource;
use App\Http\Resources\GroupResource;
use App\Models\Category;
use App\Models\Group;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class FiltersController extends ApiBaseController
{
    public function groups(Request $request)
    {
        $data = $request->only(['type', 'locale']);
        $validator = Validator::make($data, array_merge([
            'type' => 'required|in:export,import'
        ], $this->localeValidationRule()));

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        return GroupResource::collection(Group::whereType($data['type'])
            ->orderBy('is_default', 'desc')
            ->orderBy('id', 'desc')
            ->get());
    }

    public function categories(Request $request)
    {
        $validator = Validator::make($request->only('locale'), $this->localeValidationRule());
        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        return CategoryApiResource::collection(Category::all());
    }

    public function otherFilters(Request $request)
    {
        $validator = Validator::make($request->all(), array_merge([
            'model' => 'required|in:Export,Import',
            'group' => 'required|exists:groups,id',
            'filter' => 'required|in:unit,currency,payment,send,country'
            
        ], $this->localeValidationRule()));

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        $modelClass = '\\App\\Models\\' . $request['model'];
        
        return $modelClass::selectRaw(request('filter'))
            ->where('group_id', request('group'))
            ->where('locale', request('locale'))
            ->distinct()
            ->pluck(request('filter'));
        
    }
}
