<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\web\IdentityInterface;
use common\components\PathologyActiveRecord;
use yii\web\UploadedFile;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class User extends PathologyActiveRecord implements IdentityInterface
{
    public $uploadFile = 'uploads/sign_img';
    public $userPhoto = 'uploads/user';

    const STATUS_DELETED = 1;
    const STATUS_NOT_ACTIVE = 5;
    const STATUS_ACTIVE = 10;
    public $is_change_password = false;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_table';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::class,
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED, self::STATUS_NOT_ACTIVE]],
            [['username', 'password_hash', 'realname'/*, 'status', 'role'*/], 'required'],
            [['realname', 'report_name', 'email', 'position', 'role', 'tel_x', 'position_no', 'role'], 'string'],
            [['hospital_id', 'department_id', 'supervisor_id', 'employment_type_id', 'is_partner'], 'integer'],
            [['last_login_at', 'employment_type_id', 'last_update_password', 'code'], 'safe'],
            //[['sign_img'], 'file', 'extensions' => 'jpg, png'],
            //[['photo'], 'file', 'extensions' => 'jpg,png,jpeg,gif'],
            [['username', 'email'], 'unique'],
            [['is_change_password'], 'boolean'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'username' => 'Username',
            'password_hash' => 'Password',
            'email' => 'Email',
            'realname' => 'ชื่อ-นามสกุล',
            'last_login_at' => 'เข้าสู่ระบบล่าสุด',
            'status' => 'สถานะ',
            'name_old' => 'ชื่อ-สกุลเดิม',
            'position_no' => 'เลขที่ตำแหน่ง',
            'position' => 'ตำแหน่ง',
            'department_id' => 'หน่วยงาน',
            'employment_type_id' => 'ประเภทบุคลากร',
            'supervisor_id' => 'หัวหน้างาน',
            'role' => 'บทบาทหลัก',
            'tel_x' => 'โทรศัพท์',
            'report_name' => 'ชื่อในใบรายงานผล',
            'sign_img' => 'ลายเซ็นต์',
            'hospital_id' => 'หน่วยงาน',
            'last_update_password' => 'เปลี่ยนรหัสผ่านล่าสุด',
            'is_change_password' => 'ต้องการเปลี่ยนรหัสผ่าน?',
            'created_at' => 'เพิ่มเมื่อ',
            'updated_at' => 'แก้ไขเมื่อ',
            'photo' => 'รูปประจำตัว',
            'code' => 'SSB Code',
        ];
    }

    public function attributeHints()
    {
        return [
            'is_change_password' => 'หากต้องการเปลี่ยนรหัสผ่านให้คลิกที่ Checkbox แล้วใส่รหัสผ่านใหม่ที่ช่อง Password',
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        //throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
        return static::findOne(['auth_key' => $token, 'status' => self::STATUS_ACTIVE]);
    }
    /**
     * @return string
     */
    public function getPicture()
    {
        if (!empty($this->photo)) {
            return Yii::getAlias('@web') . '/' . $this->userPhoto . '/' . $this->photo;
        }
        return Yii::getAlias('@web') . '/img/logo.png';
    }

    /**
     * @return string
     */
    public function getProfile()
    {
        return !empty($this->photo) ? Yii::getAlias('@web') . '/' . $this->uploadPhoto . '/' . $this->photo : Yii::getAlias('@web') . '/img/logo-n.png';
    }
    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    public static function findByHospital($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE, 'role' => 'hospital']);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int)substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

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

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_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 Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }


    public function getHospital()
    {
        return $this->hasOne(ConstHospital::class, ['id' => 'hospital_id']);
    }

    public function uploadFile($model, $attribute)
    {
        $file = UploadedFile::getInstance($model, $attribute);
        if ($file) {
            $file_name = substr(md5($file->baseName . time()), 0, 15) . '.' . $file->extension;
            $file->saveAs(Yii::getAlias('@webroot') . '/' . $this->uploadFile . '/' . $file_name);
            if ($model->isNewRecord) {
                return $file_name;
            } else {
                if (empty($model->sign_img)) {
                    return $file_name;
                } else {
                    $model->getOldAttribute($attribute);
                }
            }
        }
        return $model->isNewRecord ? false : $model->getOldAttribute($attribute);
    }

    /**
     * @return string
     */
    public function getPhoto()
    {
        if (empty($this->photo)) {
            return Yii::getAlias('@web') . '/' . $this->userPhoto . '/blank.png';
        } else {
            return Yii::getAlias('@web') . '/' . $this->userPhoto . '/' . $this->photo;
        }
    }

    /**
     * @param $model
     * @return false|string
     */
    public function uploadPhoto($model)
    {
        $file = UploadedFile::getInstance($model, 'photo');
        if ($file) {
            $filename = Yii::$app->user->getId() . '.' . $file->extension;

            $file->saveAs(Yii::getAlias('@webroot') . '/' . $this->userPhoto . '/' . $filename);

            return $filename;
        }

        return $model->isNewRecord ? false : $model->getOldAttribute('photo');
    }
}