<?
// TODO Улучшенный вариант, но возможно тоже переедет на class.php
if (!defined('B_PROLOG_INCLUDED') || B_PROLOG_INCLUDED !== true) {
    die();
}

use Bitrix\Main\Loader;
use Bitrix\Sale\Location\LocationTable;

Loader::includeModule('sale');

if ($USER->IsAuthorized()) {
    LocalRedirect('/personal/');
    exit();
}

$arResult['CITIES'] = getCities();

if (isFormSubmitted() && isValidFormData($_POST)) {
    $registrationResult = registerUser($_POST);
    if ($registrationResult['TYPE'] === 'ERROR') {
        ShowMessage($registrationResult);
        unset($_POST);
    } else {
        updateUserProfile($USER->GetID(), $_POST);
        $USER->Authorize($USER->GetID());
        LocalRedirect('/personal/');
    }
}

$this->includeComponentTemplate();

function getCities() {
    return LocationTable::getList([
        'filter' => [
            '=NAME.LANGUAGE_ID' => LANGUAGE_ID,
            'TYPE_CODE' => 'CITY'
        ],
        'select' => [
            'NAME_RU' => 'NAME.NAME',
            'TYPE_CODE' => 'TYPE.CODE'
        ]
    ])->fetchAll();
}

function isFormSubmitted() {
    return check_bitrix_sessid() && !empty($_POST['EMAIL']) && !empty($_POST['PASSWORD']);
}

function isValidFormData($data) {
    // Добавьте валидацию данных
    return true;
}

function registerUser($data) {
    global $USER;
    return $USER->Register(
        $data['EMAIL'],
        $data['NAME'],
        $data['LAST_NAME'],
        $data['PASSWORD'],
        $data['PASSWORD'],
        $data['EMAIL']
    );
}

function updateUserProfile($userId, $data) {
    $user = new CUser;
    $phoneNumber = formatPhoneNumber($data['PERSONAL_MOBILE']);
    $fields = [
        'PERSONAL_CITY' => $data['PERSONAL_CITY'],
        'PERSONAL_MOBILE' => $phoneNumber,
        'PHONE_NUMBER' => $phoneNumber,
    ];
    $user->Update($userId, $fields);
}

function formatPhoneNumber($phone) {
    if (substr($phone, 0, 1) === '8') {
        return '7' . substr($phone, 1);
    }
    return $phone;
}
