<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use yii\behaviors\AttributeBehavior;
use yii\behaviors\BlameableBehavior;

/**
 * This is the model class for table "t_usuario".
 *
 * @property integer $id
 * @property integer $parent_id
 * @property string $usuario
 * @property string $clave
 * @property integer $rol_id
 * @property string $equipo
 * @property integer $superior_id
 * @property string $api_key
 * @property integer $estado
 * @property integer $usucre
 * @property integer $planta_sede_id
 * @property string $feccre
 * @property integer $usureg
 * @property string $fecreg
 * @property string $username
 * @property string $emp_pk
 * @property Usuario $superior
 * @property Usuario[] $usuarios
 */
class Usuario extends \yii\db\ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_usuario';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['usr_pk', 'usr_nombre', 'per_pk'], 'required'],
            [['session'], 'string'],
            [['usr_nombre', 'usr_pwd'], 'string', 'max' => 100],
            [['usr_login'], 'string', 'max' => 100],
            [['usr_estado'], 'string', 'max' => 1],
            [['rol_id'], 'string', 'max' => 64],
            [['usr_login'], 'unique'],
            [['usr_login'], 'unique', 'targetAttribute' => ['usr_login'], 'message' => 'Ya existe el login'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [            
            'usr_pk' => 'Codigo',
            'usr_nombre' => 'Nombre',
            'usr_login' => 'Login',
            'usr_pwd' => 'Password',
            'per_pk' => 'Perfil',
            'usr_estado' => 'Estado',
            'session' => 'Session',
            'usr_acceso' => 'Acceso',
            'id' => 'Id',
            'usr_jefe' => 'Jefe',
            'usr_perfil' => 'Perfil',
            'usr_pwd2' => 'Pwd2',
            'rol_id' => 'Rol',
            'usr_login' => 'Login',
        ];
    }


    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        //return static::findOne($id);
        $user = self::find()->where(["id" => $id])->one();
        if ($user == null) {
            return null;
        }
        /*if (!count($user)) {
            return null;
        }*/
        return new static($user);
    }

    /**
     * @inheritdoc
     */
    /* modified */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        //return static::findOne(['access_token' => $token]);
        $user = self::find()->where(["usr_login" => $token])->one();
        if (!$user) {
            return null;
        }
        return new static($user);
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($usr_login)
    {
        //return static::findOne(['username' => $username]);
        $user = self::find()->where(["usr_login" => $usr_login])->one();
        if (!count($user)) {
            return null;
        }
        return new static($user);
    }

    public function getPerfilname()
    {
        if(isset($this->per_pk)){
            $perfil = Perfil::find()->where(['per_pk' => $this->per_pk])->one();
            if(isset($perfil)){
                return $perfil->per_nombre;
            }else{
                return "";
            }
        }else{
            return "";
        }
    }     

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        $identity = self::find()->where(['usr_login' => $this->usr_login, 'usr_pwd' => md5($this->usr_pwd), 'usr_estado' => 'a'])->one();
        if (isset($identity)) {
            Yii::$app->user->login($identity);
            return true;
        } else {
            return false;
        }
        /*
        public static function check_password($hash, $password) {
        $full_salt = substr($hash, 0, 29);
        $new_hash = crypt($password, $full_salt);
        return ($hash == $new_hash);
    }
        */
    }

    public static function findByUser($usr_login)
    {
        $user = self::find()->where([
            "usr_login" => $usr_login
        ])->one();
        if (!count($user)) {
            return null;
        }
        return $user;
    }


    /**
     * Finds user by password reset token
     *
     * @param  string      $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        $expire = \Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        if ($timestamp + $expire < time()) {
            // token expired
            return null;
        }
        return static::findOne([
            'API_KEY' => $token
        ]);
    }

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

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

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        //return $this->password === sha1($password);
        return $this->usr_pwd ===  md5($password);
    }

    public function getRole()
    {
        // Asume que el rol está almacenado en un campo llamado `rol_id`
        return $this->rol_id;
    }
    /*public function behaviors()
    {
        return [
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['feccre','fecreg'], // update 1 attribute 'created' OR multiple attribute ['created','updated']
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'fecreg', // update 1 attribute 'created' OR multiple attribute ['created','updated']
                ],
                'value' => function ($event) {
                    //return date('Y-m-d H:i:s', strtotime($this->FECREG));
                  return date('Y-m-d H:i:s');
                },
            ],
            [
            'class' => BlameableBehavior::className(),
            'createdByAttribute' => 'usucre',
            'updatedByAttribute' => 'usureg',
            ],
        ];
    }*/
}
