<?php

namespace app\models;

use Yii;

class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['name', 'last_name', 'email', 'password'], 'required'],
            ['email', 'email'],
            ['email', 'unique'],
            [['name', 'last_name', 'phone', 'address'], 'string', 'max' => 255],
            [['phone', 'address'], 'default', 'value' => null],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Имя',
            'last_name' => 'Фамилия',
            'email' => 'Email',
            'phone' => 'Телефон',
            'address' => 'Адрес',
            'password' => 'Пароль',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

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

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

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return null;
    }

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

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

    public function getActiveOrders()
    {
        return Order::find()
            ->where(['user_id' => $this->id])
            ->andWhere(['!=', 'status', 'delivered'])
            ->andWhere(['!=', 'status', 'cancelled'])
            ->orderBy(['created_at' => SORT_DESC])
            ->all();
    }

    public function getAllOrders()
    {
        return Order::find()
            ->where(['user_id' => $this->id])
            ->orderBy(['created_at' => SORT_DESC])
            ->all();
    }

    public function isAdmin()
    {
        return $this->role == 1;
    }
}