<?php

namespace App\Http\Requests\Web;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
 * @property mixed password
 * @property mixed active_way
 * @property mixed documentation_id
 * @property mixed coupon_code
 * @property mixed type
 * @property mixed city_id
 */
class OtherRequestsRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules=[
            'other_request_topic_id' => 'required|exists:other_request_topics,id',
            'request_type' => 'required|min:3|max:100',
            'details' => 'required|min:3|max:1000',
//            'files' => 'nullable|array|min:1',
            'files.*' => 'nullable|mimes:jpg,jpeg,png,pdf',
        ];
        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $field = metaFields('otherRequests');
        $local = getCurrentLocale();
        $attributes= [
            'request_type'=> $field[$local]['request_type'] ?? __('otherRequests.request_type'),
            'other_request_topic_id'=> $field[$local]['other_request_topic_id'] ?? __('otherRequests.other_request_topic_id'),
            'details'=> $field[$local]['details'] ?? __('otherRequests.details'),
            'files'=> $field[$local]['files'] ?? __('otherRequests.files'),
        ];

        $files = request('files');

        if ($files && count($files)){
            foreach ($files as $key => $file) {
                $attributes['files.'.$key] = $attributes['files'];
            }
        }

        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)
    {
        // Change response attitude if the request done via Ajax requests like API requests
        if(Request::ajax()){
            if ($validator->fails()){
                $errors = $validator->errors()->first();
                throw new HttpResponseException(response()->json(['errors' => $errors]));
            }

        } else {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
