<?php

namespace Modules\User\Requests\Api;


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

class RegisterRequest extends FormRequest
{

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

    public function rules()
    {
        return [
            'code' => ['required', 'regex:/^[0-9]{4}$/'],
            'name' => ['required', 'string', 'min:3', 'max:15'],
            'last_name' => ['required', 'string', 'min:3', 'max:15'],
            /*'email' => [
                'required',
                'email',
                'max:250',
                Rule::unique('users')
            ],*/
            'phone' => [
                'required',
                'regex:/^9665\d{8}$/',
                Rule::unique('users')
            ],
            'id_number' => [
                'required',
                'digits:10',
                Rule::unique('users')
            ],
            'password' => [
                'required',
                'string',
                'min:6',
                'regex:/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&#]).+$/',
                'confirmed'
            ],
        ];
    }

    protected function prepareForValidation()
    {
        $this->merge([
            'phone' => $this->input('phone'),
            'code' => $this->input('code'),
        ]);
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if (!$this->isValidVerificationRecord()) {
                $validator->errors()->add('phone', __('validation.exists', ['attribute' => __('users.phone')]));
            }
        });
    }

    private function isValidVerificationRecord()
    {
        return DB::table('verifications')
            ->where('phone', $this->input('phone'))
            ->where('code', $this->input('code'))
            ->exists();
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes(): array
    {
        return [
            'code' => __('users.code'),
            'name' => __('users.name'),
            'last_name' => __('users.last_name'),
            'email' => __('users.email'),
            'id_number' => __('users.id_number'),
            'phone' => __('users.phone'),
            'password' => __('users.password'),
            'confirmed' => __('users.password_confirmation'),
            'password_confirmation' => __('users.password_confirmation'),
        ];
    }

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

}
