<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $role
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class User extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public $currentPassword;
    public $newPassword;
    public $newPasswordRepeat;
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'],
            [['role', 'status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
          //  [['currentPassword'],'compareCurrentPassword'],
            [['currentPassword,newPassword,newPasswordRepeat'],'required'],
            //[['currentPassword,newPassword'],'sameCheck'],
            [
                'newPasswordRepeat', 'compare',
                'compareAttribute'=>'newPassword',
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'password_reset_token' => 'Password Reset Token',
            'email' => 'Email',
            'role' => 'Role',
            'status' => 'Status',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'currentPassword' => 'Current Password',
            'newPassword' => 'New password',
            'newPasswordRepeat' => 'New Password Repeat',
        ];
    }
    public function compareCurrentPassword()
    {
        $user_id = Yii::$app->user->id;
        $model = User::find()->where('id ='.$user_id)->one();
        $model->attributes=$_POST['User'];
        if($model->password_hash !== crypt($model->currentPassword,$model->password_hash))
            $this->addError('currentPassword', 'Current pass is invalid');

    }

    public  function sameCheck()
    {
        $user_id = Yii::$app->user->id;
        $model = User::find()->where('id='.$user_id)->one();
        $model->attributes=$_POST['User'];
        if($model->password_hash == crypt($model->newPassword,$model->password_hash))
            $this->addError('newPassword', 'Current Password and New password are the same, you need to choose different one');
    }
}
