<?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 EditChildrenRequest extends FormRequest
{

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

    public function rules()
    {
        return [
            'id' => [
                'required',
                Rule::exists('users')->where(function ($query) {
                    $query->where('parent_id', auth()->id());
                }),
            ],
            'photo' => ['sometimes', 'nullable', 'image', 'mimes:jpeg,png,jpg,gif,svg'],
            'name' => ['sometimes', 'string', 'min:3', 'max:30'],
            'school_id' => [
                'sometimes',
                Rule::exists('schools', 'id')
            ],
            'gender' => [
                'sometimes',
                'in:0,1',
            ],
            'active' => [
                'sometimes',
                'in:true,false',
            ],
            'points_per_day' => [
                'sometimes',
                'numeric',
                'min:' . settings('min_points'),
                'max:' . settings('max_points')
            ],
        ];
    }


    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes(): array
    {
        return [
            'photo' => __('users.photo'),
            'name' => __('users.name'),
            'gender' => __('users.gender'),
            'active' => __('users.active'),
            'parent_id' => __('users.parent_id'),
            '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));
    }

}
