<?php
namespace app\models;

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

class User extends ActiveRecord implements IdentityInterface
{
    const SCENARIO_REGISTER = 'register';

    public $password;
    public $password_repeat;
    public $agree;

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

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_REGISTER] = ['full_name', 'phone', 'email', 'password', 'password_repeat', 'agree'];
        return $scenarios;
    }

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

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

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

    // IdentityInterface
    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;
    }

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

    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    public function getOrders()
    {
        return $this->hasMany(Order::class, ['user_id' => 'id']);
    }
}