<?php

namespace App\Filament\Pages\Auth;

use App\Modules\PhoneNumberVerification\Rules\PhoneNumberVerificationRule;
use Filament\Auth\Pages\Register as BaseRegister;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;

class Register extends BaseRegister
{
    public function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                $this->getNameFormComponent(),
                $this->getPhoneNumberFormComponent(),
                $this->getPasswordFormComponent(),
                $this->getPasswordConfirmationFormComponent(),
            ]);
    }

    protected function getPhoneNumberFormComponent(): TextInput
    {
        return TextInput::make('phone_number')
            ->prefix('+993')
            ->label('Telefon')
            ->mask('99 99 99 99')
            ->rules(['bail', 'required', new PhoneNumberVerificationRule, 'unique:users,phone_number'])
            ->autofocus();
    }

    protected function beforeValidate(): void
    {
        if (isset($this->data['phone_number'])) {
            $this->data['phone_number'] = str_replace(' ', '', $this->data['phone_number']);
        }
    }

    protected function mutateFormDataBeforeRegister(array $data): array
    {
        $data['phone_number'] = str_replace(' ', '', $data['phone_number']);
        $data['email'] = $data['phone_number'].'@telekechi.com';

        return $data;
    }
}
