<?php

namespace app\models;

use yii\base\Model;

class SignupForm extends Model
{
    public $is_admin;
    public $surname;
    public $name;
    public $patronymic;
    public $phone_number;
    public $password;

    public function rules()
    {
        return [
            [['is_admin', 'surname', 'name', 'patronymic', 'phone_number', 'password'], 'required'],
            ['is_admin', 'integer'],
            [['surname', 'name', 'patronymic'], 'match', 'pattern' => '/^[А-Яа-яЁё\s]/u', 'message' => 'Разрешены только символы кириллицы и пробелы'],
            ['password', 'string', 'min' => 8],
            ['phone_number', 'string', 'length' => 16],
        ];
    }

    public function attributeLabels()
    {
        return [
            'is_admin' => 'Роль',
            'surname' => 'Фамилия',
            'name' => 'Имя',
            'patronymic' => 'Отчество',
            'phone_number' => 'Номер телефона',
            'password' => 'Пароль',
        ];
    }

    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }

        $user = new User();
        $user->is_admin = $this->is_admin;
        $user->surname = $this->surname;
        $user->name = $this->name;
        $user->patronymic = $this->patronymic;
        $user->phone_number = $this->phone_number;
        $user->setPassword($this->password);
        return $user->save() ? $user : null;
    }
}