<?php

namespace App\Http\Requests;

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

/**
 * @property mixed email
 * @property mixed password
 * @property mixed login_type
 */
class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     * So the user must be guest
     * @return bool
     */
    public function authorize()
    {
        return ! Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            'email' => 'required|email',
            'password' => 'required',
        ];

    }

    public function attributes()
    {
        $field = metaFields('users');
        $local = getCurrentLocale();
        return [
            'email' => $field[$local]['email'] ?? __('users.email'),
            'password'=> $field[$local]['password'] ?? __('users.password'),
        ];
    }


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