<?php

namespace Modules\User\Requests\Api;


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

class LoginRequest extends FormRequest
{

    public function authorize()
    {
        return true; // Authorize the request for now
    }

    public function rules()
    {
        return [
            'phone' => [
                'nullable',
                'regex:/^9665\d{8}$/',
                'required_without:id_number'
            ],
            'id_number' => [
                'nullable',
                'digits:10',
                'required_without:phone'
            ],
            'password' => ['required', 'string'],
        ];
    }
    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes(): array
    {
        return [
            'id_number' => __('users.id_number'),
            'phone' => __('users.phone'),
            '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)
    {
        $errors = (new ValidationException($validator))->errors();
        $message = $validator->errors()->first();
        throw new HttpResponseException(response()->json(['message' => $message, 'errors' => $errors], 400));
    }

}
