<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele De Nobili
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\Dashboard;

use Pongho\Sdk\GoogleAnalytics\EmbedApi\AccessToken;
use Pongho\Template\Helper\JavaScript;

class GoogleAnalyticsApiLoader
{
    /**
     * @var string
     */
    protected $ga_view_id;

    /**
     * @var AccessToken
     */
    protected $token;

    /**
     * @var JavaScript
     */
    protected $js;

    /**
     * @var bool
     */
    protected $loaded = false;

    /**
     * @param string                     $viewId
     */
    public function __construct($viewId, GoogleAnalyticsAccessToken $token, JavaScript $js)
    {
        if (!str_starts_with($viewId, 'ga:')) {
            $viewId = 'ga:' . $viewId;
        }

        $this->ga_view_id = $viewId;
        $this->token = $token;
        $this->js = $js;
    }

    /**
     * @return string
     */
    public function load()
    {
        if ($this->loaded) {
            return '';
        }

        $this->loaded = true;

        $this->js->addInline(
            <<<JS
(function(w,d,s,g,js,fs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
  js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));

(function () {
    "use strict";

    window.Pongho = window.Pongho || {};

    window.Pongho.analytics = {
        id: '{$this->ga_view_id}',
        start: '30daysAgo',
        end: 'yesterday',
        accessToken: '{$this->token->getToken()}'
    };
}());
JS
        );

        $this->js->add(
            pongho_url('/Application/Admin/Resources/js/dashboard-analytics.js')
        );

        return <<<HTML
<style>
#date-range-container {
    overflow: hidden;
}
#date-range-container .date-range-selector {
    float: right;
}
#date-range-container .date-range-selector--item {
    display: inline-block;
}
#date-range-container label {
    padding: 0 3px 0 10px;
}
#date-range-container input {
    border: 1px solid #CCC;
    border-radius: 3px;
    padding: 3px;
    width: 200px;
}
</style>
<div id="date-range-container"></div>
HTML;
    }
}
