<?php

namespace common\modules\triggers\models;

use Faker\Provider\DateTime;
use Yii;
use common\modules\users\models\User;

/**
 * This is the model class for table "trigger_logs".
 *
 * @property integer $id
 * @property integer $user_id
 * @property string $action
 * @property string $url
 * @property string $datetime
 * @property integer $presence_time
 *
 * @property User $user
 */
class TriggerLogs extends \yii\db\ActiveRecord
{
    const USER_REGISTRATION = 'registration';
    const USER_VISITED = 'visited';

    public static function logAction()
    {
        if (!Yii::$app->user->isGuest) {
            $date = new \DateTime();
            $model = new TriggerLogs();
            $model->user_id = Yii::$app->user->identity->id;
            $model->action = self::USER_VISITED;
            $model->url = Yii::$app->request->getUrl();
            $model->datetime = $date->format('Y-m-d H:i:s');
            $model->presence_time = 1;
            $model->save();
        }
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'trigger_logs';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'action', 'datetime', 'url'], 'required'],
            [['user_id', 'presence_time'], 'integer'],
            [['datetime'], 'safe'],
            [['action', 'url'], 'string', 'max' => 255],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'action' => 'Action',
            'datetime' => 'Datetime',
            'presence_time' => 'Presence Time',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
}
