<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 *
 * @property-read User|null $user
 *
 */
class RegisterForm extends Model
{
    public $password;
    public $password_repeat;
    public $first_name;
    public $last_name;
    public $patronymic;
    public $phone;
    public $email;
    public $address;
    public $count;
    public $rules = false;


    public function rules()
    {
        return [
            [['password', 'password_repeat', 'first_name', 'last_name', 'patronymic', 'phone', 'email', 'address', 'count'], 'required'],
            ['count', 'integer', 'min' => 1],
            ['password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => 'Пароли не совпадают'],
            [['first_name', 'last_name', 'patronymic'], 'match', 'pattern' => '/^[а-яА-ЯёЁ\s]+$/u', 'message' => 'Используйте только кириллицу и пробелы'],
            ['rules', 'boolean'],
            ['rules', 'required', 'requiredValue' => true, 'message' => 'Вы должны согласиться с правилами'],
            ['email', 'email'],
            ['phone', 'unique', 'targetClass' => 'app\models\User'],
            ['password', 'string', 'min' => 10],
        ];
    }

    public function save(){
        if (!$this->validate()) {
            return false;
        }
        $user = new User();
        $user->password = Yii::$app->security->generatePasswordHash($this->password);
        $user->first_name = $this->first_name;
        $user->last_name = $this->last_name;
        $user->patronymic = $this->patronymic;
        $user->phone = $this->phone;
        $user->email = $this->email;
        $user->address = $this->address;
        $user->count = $this->count;
        if ($user->save()){
            return $user;
        }
        return false;
    }

    public function attributeLabels()
    {
        return [
            'password' => 'Пароль',
            'password_repeat' => 'Повтор пароля',
            'first_name' => 'Имя',
            'last_name' => 'Фамилия',
            'patronymic' => 'Отчество',
            'phone' => 'Номер телефона',
            'address' => 'Адрес проживания',
            'count' => 'Количество людей, проживающих по данному адресу',
            'rules' => 'Согласие с правилами регистрации'
        ];
    }
}
