<?php
namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
    public $password_repeat;
    public $agree;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['full_name', 'phone', 'email', 'password', 'password_repeat', 'agree'], 'required'],
            ['full_name', 'match', 'pattern' => '/^[а-яёА-ЯЁ\s]+$/u'],
            ['phone', 'match', 'pattern' => '/^[\d\s\(\)\-]+$/'],
            ['phone', 'string', 'min' => 11, 'max' => 20],
            ['email', 'email'],
            ['password', 'string', 'min' => 8],
            ['password_repeat', 'compare', 'compareAttribute' => 'password'],
            ['agree', 'compare', 'compareValue' => 1, 'message' => 'Необходимо согласие с правилами'],
            [['phone', 'email'], 'unique'],
        ];
    }

    public static function findByPhone($phone)
    {
        return static::findOne(['phone' => $phone]);
    }

    public function attributeLabels()
    {
        return [
            'full_name' => 'ФИО',
            'phone' => 'Телефон',
            'email' => 'Email',
            'password' => 'Пароль',
            'password_repeat' => 'Повтор пароля',
            'agree' => 'Согласие с правилами регистрации',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->password = Yii::$app->security->generatePasswordHash($this->password);
            }
            return true;
        }
        return false;
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        return null;
    }

    public function validateAuthKey($authKey)
    {
        return false;
    }

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }
}