<?php

namespace Modules\Address\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 AddressRequest extends FormRequest
{

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

    public function rules()
    {

        $rules = [
            'city_id' => ['required', Rule::exists('cities', 'id')],
            'latitude' => ['required', 'numeric', 'between:-90,90'],
            'longitude' => ['required', 'numeric', 'between:-180,180'],
            'description' => ['required'],
        ];


        return $rules;
    }


    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes(): array
    {
        $attributes = [
            'city_id' => __('products.city_id'),
            'latitude' => __('products.latitude'),
            'longitude' => __('products.longitude'),
            'description' => __('products.description'),

        ];

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

}
