<?php

namespace App\Http\Requests\API;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
 * @property mixed password
 * @property mixed email
 * @property mixed phone
 * @property mixed register
 * @property mixed login
 * @property mixed change_phone
 */
class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */

    public function rules()
    {

        $phonePattern = '/^(05){1}([0-9]{8})$/';
        return [
            'phone'=> 'required|exists:users,phone|numeric|regex:'.$phonePattern,
        ];

    }

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

    /**
     * Handle a failed validation attempt.
     * Override the parent method action if the request is for AJAX
     * @param Validator $validator
     * @return void
     */
    protected function failedValidation(Validator $validator) :void
    {
        // Change response attitude if the request done via Ajax requests like API requests
        $errors = (new ValidationException($validator))->errors();
        $message = $validator->errors()->first();
        throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  400));
    }
}
