<?php

namespace App\Http\Requests;

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

class UserProfileRequest 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 = [
            'first_name_'.getCurrentLocale() => 'required',
            'last_name_'.getCurrentLocale() => 'required',
            'city' => 'required',
            'street' > 'required',
            'facebook_url' => 'required|url',
            'twitter_url' => 'required|url',
            'instagram_url' => 'required|url',
            'phone' => 'required|numeric|unique:users,phone',
            'photo' => 'required|image|mimes:png,jpg,jpeg',
            'about_me' => 'required',
        ];

        return $rules;
    }

    protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests
        if(Request::json()){
            $errors = $validator->errors()->first();
            throw new HttpResponseException(response()->json(['error' => $errors, 'status' => 0]));
        } else {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
