<?php

namespace onespace\tools\widgets\tracking;

use onespace\tools\assets\TrackingAsset;
use Yii;
use yii\bootstrap\Widget;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\JsExpression;
use yii\web\View;

/**
 * Clarity tracking script
 * 
 * @property string $projectId ID of the project to store to
 * @property bool $customId whether to identify the user using custom identity system
 * @property bool $cookieConsentAutoGrant if true, it is assumed that the user has consented to cookies
 * @property string $userIdAttribute attribute of the user model to identify with. If not set, will use user id
 * @property string $userNameAttribute attribute of the user model to send as a pretty name. If not set, nothing is sent
 * 
 * @author  Jason Phillips <jason@one-space.co.za>
 */
class ClarityTracker extends Widget {

    public $projectId = null;
    public $customId = false;
    public $cookieConsentAutoGrant = true;
    public $userIdAttribute = null;
    public $userNameAttribute = null;

    public function init() {
        parent::init();

        TrackingAsset::register($this->view);

        
    }

    public function run() {
        if ($this->projectId == null) {
            return;
        }

        // actually fire the scripts
        $this->view->registerJs(<<<JS
            loadClarity(window, document, "clarity", "script", "{$this->projectId}");
JS, View::POS_HEAD);

        if ($this->cookieConsentAutoGrant) {
            
        $this->view->registerJs(<<<JS
            window.clarity("consent");
JS, View::POS_HEAD);
        }

        if ($this->customId && Yii::$app->user != null && !Yii::$app->user->isGuest) {
            // load the user ID and name
            if ($this->userIdAttribute != null) {
                $userId = ArrayHelper::getValue(Yii::$app->user->identity, $this->userIdAttribute);
            } else {
                $userId = Yii::$app->user->id;
            }
            $sessionId = Yii::$app->session->id;
            $pageId = Yii::$app->requestedRoute;
            if ($this->userNameAttribute != null) {
                $userName = ArrayHelper::getValue(Yii::$app->user->identity, $this->userNameAttribute);
                $identifyJs = <<<JS
                window.clarity("identify", "$userId", "$sessionId", "$pageId", "$userName");
JS;
            } else {
                $identifyJs = <<<JS
                window.clarity("identify", "$userId", "$sessionId", "$pageId");
JS;
            }
            $this->getView()->registerJs($identifyJs, View::POS_HEAD);

        }
        return;
    }
}
