<?php
/**
* @package   Gridbox
* @author    Balbooa http://www.balbooa.com/
* @copyright Copyright @ Balbooa
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/

namespace Balbooa\Component\Gridbox\Site\View\System;

use Balbooa\Component\Gridbox\Site\Helper\GridboxHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\HtmlView as BaseView;
use Joomla\CMS\Uri\Uri;

defined('_JEXEC') or die;

class HtmlView extends BaseView
{
    protected $item;
    
    public function display($tpl = null)
    {
        $this->item = $this->get('Item');
        if (empty($this->item)) {
            GridboxHelper::raiseError(404, Text::_('NOT_FOUND'));
        }
        if ($this->item->type == 'submission-form') {
            $options = json_decode($this->item->page_options);
            $user = Factory::getUser();
            $groups = $user->getAuthorisedViewLevels();
            if (!in_array($options->access, $groups)) {
                GridboxHelper::raiseError(403, Text::_('JERROR_ALERTNOAUTHOR'));
                return;
            }
        }
        $this->item->html = GridboxHelper::checkModules($this->item->html, $this->item->items);
        $this->prepareDocument();
        parent::display($tpl);
    }

    public function prepareDocument()
    {
        $doc = Factory::getDocument();
        $doc->addScript(Uri::root().'/media/vendor/jquery/js/jquery.min.js');
        $doc->addScript(Uri::root().'/components/com_gridbox/libraries/bootstrap/bootstrap.js');
        if ($this->item->type == 'thank-you-page') {
            $session = Factory::getSession();
            $json = $session->get('gridbox-store-layer', '');
            if (!empty($json)) {
                $script = 'window.gridboxOrder = '.$json.';';
                $doc->addScriptDeclaration($script);
                $session->clear('gridbox-store-layer');
            }
            if (!empty($json) && GridboxHelper::$website->google_analytics
                && !empty(GridboxHelper::$website->google_gtm_id) && GridboxHelper::$website->ecommerce_tracking) {
                $script = "window.dataLayer = window.dataLayer || []; window.dataLayer.push(".$json.");";
                $doc->addScriptDeclaration($script);
            }
        }
        $time = $this->item->saved_time;
        if (!empty($time)) {
            $time = '?'.$time;
        }
        $doc->addStyleSheet(Uri::root().'templates/gridbox/css/storage/system-page-'.$this->item->id.'.css'.$time);
        $doc->setTitle($this->item->title);
        GridboxHelper::checkMoreScripts($this->item->html, $time);
    }
}