<?php

namespace App\Http\Requests\Api\Provider;

use Illuminate\Foundation\Http\FormRequest;

class SendVerificationCodeRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
     */
    public function rules(): array
    {
        // route is /provider or /user
        $is_user_route = $this->is('api/user/*');
        $db_table = $is_user_route ? 'users' : 'service_providers';
        return [
            'email' => ['nullable', 'email', "unique:$db_table,email"],
            'phone' => ['nullable', 'numeric', "unique:$db_table,phone", 'starts_with:9665', 'digits:12'],
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if (!$this->input('email') && !$this->input('phone')) {
                $validator->errors()->add('field', __('messages.one_of_email_or_phone_is_required'));
            }
            if ($this->input('email') && $this->input('phone')) {
                $validator->errors()->add('field', __('messages.one_of_email_or_phone_is_required'));
            }
        });
    }
}
