<?php

namespace app\models;

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

class User extends ActiveRecord implements IdentityInterface
{
    public $password;
    public $password_repeat;
    public $agree_rules;

    public static function tableName()
    {
        return '{{%users}}';
    }

    public function rules()
    {
        return [
            [['full_name', 'phone', 'email', 'password', 'password_repeat', 'agree_rules'], 'required'],
            ['full_name', 'match', 'pattern' => '/^[а-яА-ЯёЁ\s-]+$/u', 'message' => 'Только кириллица и пробелы'],
            ['phone', 'match', 'pattern' => '/^8\(\d{3}\)\d{3}-\d{2}-\d{2}$/', 'message' => 'Формат: 8(XXX)XXX-XX-XX'],
            ['phone', 'unique', 'message' => 'Телефон уже занят'],
            ['email', 'email'],
            ['email', 'unique', 'message' => 'Email уже занят'],
            ['password', 'string', 'min' => 8, 'tooShort' => 'Пароль должен быть минимум 8 символов'],
            ['password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => 'Пароли не совпадают'],
            ['agree_rules', 'compare', 'compareValue' => true, 'message' => 'Необходимо согласие с правилами'],
        ];
    }

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

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

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

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

    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 $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->auth_key === $authKey;
    }
}