<?php

namespace Benhauer\Salesmanago\Block\Tracking;

use \Magento\Framework\View\Element\Template;
use \Magento\Framework\View\Element\Template\Context;
use \Magento\Store\Model\StoreManagerInterface;

use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Factories\FactoryOrganizer;

use \Benhauer\Salesmanago\Model\Hooks as HooksModel;

class Monitoring extends Template
{
    public $hooksModel;
    public $trackingScript;
    public $factoryOrganizer;
    public $storeManager;

    public function __construct(
        Context $context,
        HooksModel $hooksModel,
        FactoryOrganizer $factoryOrganizer
    ) {
        $data = [];
        parent::__construct($context, $data);
        $this->hooksModel       = $hooksModel;
        $this->factoryOrganizer = $factoryOrganizer;
        $this->storeManager     = $context->getStoreManager();
        $this->setStoreViewForModel();
        $this->getMonitoringCode();
    }

    /**
     * Sets $this->trackingScript prepare monitorig script;
     * @return string - monitoring scrip
    */
    public function getMonitoringCode()
    {
        $userData = $this->hooksModel->getUserSettings(null);

        if (isset($userData[HooksModel::CLIENT_ID])
            && !empty($userData[HooksModel::CLIENT_ID])
        ) {
            $userAccount = $this->factoryOrganizer->getInst(
                FactoryOrganizer::USER_ACCOUNT_C,
                UserProvider::initSettingsUser(
                    $this->hooksModel
                ),
                $this->hooksModel
            );

            $webPush = (isset($userData[HooksModel::WEB_PUSH]['code'])
                && !empty($userData[HooksModel::WEB_PUSH]['code']))
                ? $userData[HooksModel::WEB_PUSH]['code']
                : '';

            $trackingScript = $userAccount->createMonitorVisitorsCode(
                $webPush
            );

            return  $this->trackingScript = $trackingScript;
        } else {
            return $this->trackingScript = '';
        }
    }

    /**
     * Set store view id from $this->requestPrams to each model;
     */
    public function setStoreViewForModel()
    {
        $storeId = $this->storeManager->getStore()->getId();
        if ($storeId != null && $storeId != 0) {
            $this->hooksModel->setScopeId($storeId);
            $this->hooksModel->setScope('stores');
        }
    }
}
