<?php
namespace app\models;
use Yii;
use yii\base\Model;
use app\models\User;

class RegisterForm extends Model {
    public $name;
    public $last_name;
    public $email;
    public $phone;
    public $address;
    public $role = 0;
    public $password;
    public $password_repeat;

    public function rules()
    {
        return [
            [['password', 'name', 'last_name', 'email', 'phone', 'address'], 'required'],
            ['email', 'email'],
            ['email', 'unique', 'targetClass' => User::class],
            [['phone'],'match','pattern'=>'/^\+7 \(\d{3}\) \d{3}-\d{2}-\d{2}$/', 'message' => 'Телефон должен быть в формате: +7 (999) 999-99-99'],
            [['name', 'last_name'], 'match', 'pattern' => '/^[а-яёА-ЯЁ\- ]+$/u', 'message' => 'Имя может содержать только кириллица и пробелы'],
            ['password', 'string', 'min'=>6],
            ['password_repeat', 'compare', 'compareAttribute'=>'password'],
            ['role', 'default', 'value'=>0],
        ];  
    }

    public function attributeLabels()
    {
        return [
            'name' => 'Имя',
            'last_name' => 'Фамилия',
            'phone' => 'Телефон',
            'address' => 'Адрес',
            'password' => 'Пароль',
            'password_repeat' => 'Повтор пароля',
        ];
    }

    public function register()
    {
        if (!$this->validate()) {
            return false;
        }

        $user = new User();
        $user->name = $this->name;
        $user->last_name = $this->last_name;
        $user->email = $this->email;
        $user->phone = $this->phone;
        $user->address = $this->address;
        $user->role = $this->role;
        $user->setPassword($this->password);
        
        return $user->save();
    }
}