<?php

namespace Modules\Product\Requests\Api;



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

class ProductRequest extends FormRequest
{

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

    public function rules()
    {
        // dd($this->product);
        $rules = [
            'category_id' => ['required', Rule::exists('categories', 'id')],
            'image' => [$this->product ? 'sometimes' : 'required', 'image', 'mimes:jpeg,png,jpg,gif,svg'],
            'cost' => ['required', 'numeric'],
            'count' => ['required', 'numeric'],
        ];

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


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

        ];
        foreach (languages() as $lang) {
            $lang_attributes = [
                'title_' . $lang->local => __('products.title') . ' ' . $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));
    }

}
