<?php

namespace app\models;

use yii\base\Model;

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

    public function rules()
    {
        return [
            [['surname', 'name', 'email', 'phone_number', 'password', 'password_repeat'], 'required'],
            [['name', 'surname', 'patronymic'], 'match', 'pattern' => '/^[а-яё\s\-]+$/iu', 'message' => 'Разрешены только кириллические символы, пробелы'],
            ['password', 'string', 'min' => 8],
            ['password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => 'Пароли не совпадают'],
            ['email', 'email'],
            ['phone_number', 'match', 'pattern' => '/^8\(\d{3}\)-\d{3}-\d{2}-\d{2}$/', 'message' => 'Неверный формат номера телефона'],
        ];
    }

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

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

        $user = new User();
        $user->surname = $this->surname;
        $user->name = $this->name;
        $user->patronymic = $this->patronymic;
        $user->phone_number = $this->phone_number;
        $user->email = $this->email;
        $user->setPassword($this->password);

        return $user->save() ? $user : null;
    }
}