<?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;
use Illuminate\Support\Facades\URL;

/**
 * @property mixed remember
 * @property mixed email
 */
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() || Auth::user()->verifications->code;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        preg_match('/admin/', URL::current(), $match);
        $type = array_shift($match);

        if ($type == 'admin'){
            return [
                'email'     => ['required', 'string', 'email'],
                'password'  => ['required', 'string', 'min:3'],
            ];
        }
        return [
            'email'     => ['required', 'string'],
            'password'  => ['required', 'string', 'min:3'],
        ];
    }

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