<?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 && !Yii::$app->request->isAjax) {
            $action = self::USER_VISITED;
            if (Yii::$app->controller->action->id=='registration')
                $action = self::USER_REGISTRATION;
            $date = new \DateTime();
            $model = new TriggerLogs();
            $model->user_id = Yii::$app->user->identity->id;
            $model->action = $action;
            $model->url = Yii::$app->request->getUrl();
            $model->datetime = $date->format('Y-m-d H:i:s');
            $model->presence_time = 1;
            if ($model->save()) {
                $view = \Yii::$app->controller->view;
                // Создаем скрипт
                $script ='$(document).ready(function() {
                              var id='.($model->getPrimaryKey()).';
                              var interval = 5;
                              var value = 5;
                              setInterval(function() {
                                    $.ajax({
                                        url: "http://taskon.task-on.com/triggers/default/settimeoflogs",
                                        method: "GET",
                                        async: false,
                                        data: {
                                            id: id,
                                            value: value
                                        },
                                    });
                                    value += interval;
                                }, (interval*1000));
                              });';
                // Регистрируем его
                $view->registerJs($script, $view::POS_READY);
            }
        }
    }
    /**
     * @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']);


    }

    public static function getSummaryTimeByUrl($url, $user_id) {
        /** @var TriggerLogs[] $model */
        $model = TriggerLogs::find()->where(['url' => $url, 'user_id' => $user_id])->all();
        $summ = 0;
        foreach($model as $item) {
            $summ += $item->presence_time;
        }
        return $summ;
    }
}
