<?php

declare(strict_types=1);

namespace App\Http\Requests\Auth;

use Illuminate\Foundation\Http\FormRequest;

class OtpRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'cellphone' => ['required', 'string', 'regex:/^09\d{9}$/'],
        ];
    }

    public function messages(): array
    {
        return [
            'cellphone.required' => 'شماره همراه الزامی است.',
            'cellphone.regex' => 'شماره همراه باید با 09 شروع شده و 11 رقم باشد.',
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('cellphone')) {
            $cellphone = preg_replace('/\D+/', '', (string) $this->input('cellphone'));

            if (str_starts_with((string) $cellphone, '98') && strlen((string) $cellphone) === 12) {
                $cellphone = '0' . substr((string) $cellphone, 2);
            }

            $this->merge([
                'cellphone' => $cellphone,
            ]);
        }
    }
}
