<?php

namespace app\models;

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

class User extends ActiveRecord implements IdentityInterface
{
    const ROLE_EMPLOYEE = 'employee';
    const ROLE_ADMIN = 'admin';
    
    const SCENARIO_REGISTER = 'register';
    const SCENARIO_UPDATE = 'update';

    public static function tableName()
    {
        return '{{%user}}';
    }
    
    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_REGISTER] = ['name', 'email', 'password_hash', 'role'];
        $scenarios[self::SCENARIO_UPDATE] = ['name', 'email', 'role'];
        return $scenarios;
    }

    public function rules()
    {
        return [
            [['name', 'email'], 'required'],
            ['email', 'email'],
            ['email', 'unique'],
            ['role', 'in', 'range' => [self::ROLE_EMPLOYEE, self::ROLE_ADMIN]],
            [['name', 'email'], 'string', 'max' => 100],
            
            // Пароль обязателен только при регистрации
            ['password_hash', 'required', 'on' => self::SCENARIO_REGISTER],
            ['password_hash', 'string', 'min' => 6],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Имя',
            'email' => 'Email',
            'password_hash' => 'Пароль',
            'role' => 'Роль',
            'created_at' => 'Дата регистрации',
        ];
    }

    // IdentityInterface methods
    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 isAdmin()
    {
        return $this->role === self::ROLE_ADMIN;
    }

    public function isEmployee()
    {
        return $this->role === self::ROLE_EMPLOYEE;
    }
    
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($insert) {
                $this->generateAuthKey();
            }
            return true;
        }
        return false;
    }

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

    // Relations
    public function getAnswers()
    {
        return $this->hasMany(Answer::class, ['user_id' => 'id']);
    }
}