<?php

namespace Modules\Category\Requests\Api;



use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class CategoryRequest extends FormRequest
{

    public function authorize()
    {
        return auth()->check() && auth()->user()->role == 6;
    }

    public function rules()
    {
        $rules[] = [];

        foreach (languages() as $lang) {
            $lang_rules = [
                'title_' . $lang->local => 'required|max:30',
                // 'description_' . $lang->local => 'required|max:500',
            ];
            $rules = array_merge($rules, $lang_rules);
        }
        return $rules;
    }


    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes(): array
    {
        $attributes = [
            // 'image' => __('categories.image'),
            // 'category_id' => __('categories.category_id'),

        ];
        foreach (languages() as $lang) {
            $lang_attributes = [
                'title_' . $lang->local => __('categories.title') . ' ' . $lang->local,
                // 'description_' . $lang->local => __('categories.description') . ' ' . $lang->local,
            ];
            $attributes = array_merge($attributes, $lang_attributes);
        }
        return $attributes;
    }

    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param Validator $validator
     * @return void
     *
     * @throws ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        $errors = (new ValidationException($validator))->errors();
        $message = $validator->errors()->first();
        throw new HttpResponseException(response()->json(['message' => $message, 'errors' => $errors], 400));
    }

}
