<?php

namespace Modules\User\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 CreateChildrenRequest extends FormRequest
{

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

    public function rules()
    {
        return [
            'photo' => ['sometimes', 'nullable', 'image', 'mimes:jpeg,png,jpg,gif,svg'],
            'name' => ['required', 'string', 'min:3', 'max:30'],
            'school_id' => [
                'required',
                Rule::exists('schools', 'id')
            ],
            'gender' => [
                'required',
                'in:0,1',
            ],
            'cash_per_day' => [
                'sometimes',
                'numeric',
                'min:' . settings('min_cash'),
                'max:' . settings('max_cash')
            ],
        ];
    }


    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes(): array
    {
        return [
            'photo' => __('users.photo'),
            'name' => __('users.name'),
            'gender' => __('users.gender'),
            'points_per_day' => __('users.points_per_day'),
            'school_id' => __('users.school')
        ];
    }

    /**
     * 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));
    }

}
