<?php

namespace common\modules\triggers\models;

use Yii;

/**
 * This is the model class for table "auth_hashes".
 *
 * @property integer $id
 * @property string $email
 * @property string $hash
 * @property integer $auth_count
 * @property string $valid_date
 */
class AuthHashes extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'auth_hashes';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['email', 'hash', 'valid_date'], 'required'],
            [['auth_count'], 'integer'],
            [['valid_date'], 'safe'],
            [['email'], 'string', 'max' => 255],
            [['hash'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'email' => 'Email',
            'hash' => 'Hash',
            'auth_count' => 'Auth Count',
            'valid_date' => 'Valid Date',
        ];
    }

    /**
     * @param $email
     * @return string
     */
    public static function setNewHash($email)
    {
        $validDate = new \DateTime();
        $validDate->modify('+3 hours');
        $hash = Yii::$app->security->generateRandomString(50);
        $model = new AuthHashes();
        $model->email = $email;
        $model->hash = $hash;
        $model->auth_count = 0;
        $model->valid_date = $validDate->format('Y-m-d H:i:s');
        if ($model->save())
            return $hash;
    }
}
