<?php

namespace common\modules\sessions\models;

use Yii;

use common\modules\sessions\models\Session;

/**
 * This is the model class for table "sessions_url".
 *
 * @property integer $id
 * @property integer $session_id
 * @property string $url
 * @property string $referer
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property Sessions $session
 */
class SessionUrl extends \common\components\ActiveRecordModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sessions_url';
    }

    public function name()
    {
        return 'Посещения страниц';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['session_id'], 'required'],
            [['session_id', 'created_at', 'updated_at', 'utm'], 'integer'],
            [['url', 'referer'], 'string'],
            [['session_id'], 'exist', 'skipOnError' => true, 'targetClass' => Session::className(), 'targetAttribute' => ['session_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'session_id' => 'Сессия',
            'url' => 'Адрес страницы',
            'referer' => 'Реферер',
            'created_at' => 'Дата посещения',
            'updated_at' => 'Дата обновления',
        ];
    }

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

    // Время пребывания на странице в секундах
    public function getTime()
    {
        return $this->updated_at - $this->created_at;
    }

    public function parseUrl()
    {
        parse_str(parse_url($this->url, PHP_URL_QUERY), $params);

        return $params;
    }

    public function isUtm()
    {
        $params = $this->parseUrl();
        
        if(isset($params['utm_source']))
        {
            return 1;
        }

        return 0;
    }
}
