<?php
/**
 * @package     Google Reviews Pro
 * @subpackage  plg_googlereviewspro
 * @license     http://www.gnu.org/licenseses/gpl-3.0.html GNU/GPL
 *
 * Created by Oleg Micriucov for Joomla!
 * https://allforjoomla.com
 *
 */
defined('_JEXEC') or die(':)');

use Joomla\String\StringHelper;

JLoader::registerPrefix('GRP_Helper_', JPATH_ROOT.'/components/com_googlereviewspro/helpers');
GRP_Helper_Compatibility::check();

class plgSystemGooglereviewspro extends JPlugin {

    private static $scriptsLoaded = false;
    private $_static_content_version = '2.16.1';
    private $_v = null;
    private $_cfg = null;
    
    public function onAfterRender() {
        $app = JFactory::getApplication();
        $doc = JFactory::getDocument();
        if ($this->_isAdmin() || $doc->getType() != 'html'){
            return;
        }
        if ($app->input->getCmd('option', '')=='com_content' && $app->input->getCmd('view', '')=='form' && $app->input->getCmd('layout', '')=='edit') {
            return;
        }
        $html = $this->_getResponseBody();
        $delim = StringHelper::strpos($html, '<body');
        if ($delim === false) {
            return true;
        }
        $htmlHead = StringHelper::substr($html, 0, $delim);
        $htmlBody = StringHelper::substr($html, $delim);
        if (strpos($htmlBody, '[googlereviewspro') === false) {
            return true;
        }

        $htmlBody = preg_replace_callback('~\[googlereviewspro([^\]]+)\]~', array($this, '_renderShortcode'), $htmlBody);

        $scriptsLoadMode = GRP_Helper_Data::getComponentConfig()->get('load_mode', 'all');
        if ($scriptsLoadMode != 'all' && !self::$scriptsLoaded) {
            $lang = JFactory::getLanguage();
            self::$scriptsLoaded = true;
            $scripts = '';

            $scripts.= '<script src="'.GRP_Helper_Data::getMediaURI('/js/frontend.js?v='.$this->_static_content_version).'" defer ></script>';
            $htmlBody = preg_replace('~<\/body>~', $scripts . '</body>', $htmlBody, 1);
        }
        $this->_setResponseBody($htmlHead . $htmlBody);
        return true;
    }
    
    private function _isAdmin(){
        $app = JFactory::getApplication();
        return ((method_exists($app, 'isAdmin') && $app->isAdmin()) || (method_exists($app, 'isClient') && $app->isClient('administrator')));
    }

    private function _setResponseBody($html) {
        if (version_compare(JVERSION, '4.0.0', '>=')) {
            $app = JFactory::getApplication();
            return $app->setBody($html);
        }
        JResponse::setBody($html);
    }

    private function _getResponseBody() {
        if (version_compare(JVERSION, '4.0.0', '>=')) {
            $app = JFactory::getApplication();
            return $app->getBody();
        }
        return JResponse::getBody();
    }

    public function onBeforeCompileHead() {
        $app = JFactory::getApplication();
        $doc = JFactory::getDocument();

        if ($doc->getType() != 'html') {
            return;
        }
        if ($this->_isAdmin()) {
            $this->_loadBackendStaticContent();
        } else {
            $this->_loadFrontendStaticContent();
        }
    }

    private function _loadBackendStaticContent() {
        $app = JFactory::getApplication();
        $doc = JFactory::getDocument();
        $lang = JFactory::getLanguage();

        if ($app->input->getCmd('option', '') != 'com_googlereviewspro') {
            return;
        }

        JHtml::_('jquery.framework');
        JHtml::_('behavior.core');

        if ((int) GRP_Helper_Data::getComponentConfig()->get('load_gfont', 1)) {
            JHtml::_('stylesheet', 'https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,600,600i,700,700i&amp;subset=cyrillic,cyrillic-ext,latin-ext');
        }
        $doc->addStyleSheet(GRP_Helper_Data::getMediaURI('/css/backend.css?v='.$this->_static_content_version));

        $doc->addScript(GRP_Helper_Data::getMediaURI('/js/backend.js?v='.$this->_static_content_version));
    }

    private function _loadFrontendStaticContent() {
        $app = JFactory::getApplication();
        $doc = JFactory::getDocument();
        $lang = JFactory::getLanguage();

        GRP_Helper_Data::loadLanguage();

        $fCfg = array(
            'i18n' => array(
                'view_on_fb' => JText::_('COM_GOOGLEREVIEWSPRO_VIEW_ON_FB'),
                'load_more' => JText::_('COM_GOOGLEREVIEWSPRO_LOAD_MORE'),
                'show_more' => JText::_('COM_GOOGLEREVIEWSPRO_SHOW_MORE'),
                'show_less' => JText::_('COM_GOOGLEREVIEWSPRO_SHOW_LESS'),
                'ajax_error' => JText::_('COM_GOOGLEREVIEWSPRO_AJAX_ERROR'),
                'network_error' => JText::_('COM_GOOGLEREVIEWSPRO_NETWORK_ERROR'),
                'no_reviews' => JText::_('COM_GOOGLEREVIEWSPRO_NO_REVIEWS_FOUND'),
                'rate_request_text' => JText::_('COM_GOOGLEREVIEWSPRO_RATE_REQUEST_TEXT'),
                'yes' => JText::_('COM_GOOGLEREVIEWSPRO_YES'),
                'no' => JText::_('COM_GOOGLEREVIEWSPRO_NO'),
                'all_author_reviews' => JText::_('COM_GOOGLEREVIEWSPRO_ALL_AUTHOR_REVIEWS_ON_GOOGLE'),
            ),
            'widgetConfig' => array(
                'id' => 0,
                'ajax_url' => GRP_Helper_Data::getAjaxURI(),
                'templates_url' => GRP_Helper_Data::getMediaURI('/templates/'),
                'template' => 'widget',
                'mode' => 'frontend',
                'version' => $this->_static_content_version
            )
        );

        JHtml::_('jquery.framework');
        JHtml::_('behavior.core');

        $doc->addCustomTag('<script type="application/json" id="googlereviewspro-config">' . json_encode($fCfg, JSON_HEX_APOS) . '</script>');

        if ((int) GRP_Helper_Data::getComponentConfig()->get('load_gfont', 1)) {
            JHtml::_('stylesheet', 'https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,600,600i,700,700i&amp;subset=cyrillic,cyrillic-ext,latin-ext');
        }
        $doc->addStyleSheet(GRP_Helper_Data::getMediaURI('/css/frontend.css?v='.$this->_static_content_version));

        $scriptsLoadMode = GRP_Helper_Data::getComponentConfig()->get('load_mode', 'all');
        if ($scriptsLoadMode == 'all' && !self::$scriptsLoaded) {
            self::$scriptsLoaded = true;
            
            $doc->addScript(GRP_Helper_Data::getMediaURI('/js/frontend.js?v='.$this->_static_content_version), [], ["defer"=>true]);
        }
    }

    public function _renderShortcode($matches) {
        $attribs = $this->_shortcodeAttribs($matches[1]);
        $id = (int) $attribs['id'];
        $result = '';
        if ($id > 0) {
            $result = '<div class="googlereviewspro-widget" data-id="' . $id . '"></div>';
        }

        return $result;
    }

    public function _shortcodeAttribs($rawAttribs) {
        $attribs = array();
        if (is_array($rawAttribs)) {
            $attribs = $rawAttribs;
        } else {
            preg_match_all('~([a-z0-9_\-]+)=\&quot;(.*?)(?=\&quot;)\&quot;~i', $rawAttribs, $mchs);
            foreach ($mchs[1] as $k => $v) {
                $attribs[$v] = $mchs[2][$k];
            }
            preg_match_all('~([a-z0-9_\-]+)="([^"]+)"~i', $rawAttribs, $mchs);
            foreach ($mchs[1] as $k => $v) {
                $attribs[$v] = $mchs[2][$k];
            }
        }
        $defaults = array(
            'id' => 0,
        );
        return array_merge($defaults, $attribs);
    }

    public function onExtensionAfterSave($context, $table, $isNew = true) {
        if ($isNew || $context != 'com_config.component' || $table->element != 'com_googlereviewspro') {
            return;
        }
        $params = new JRegistry($table->params);
        $db = JFactory::getDbo();
        $query = $db->getQuery(true)
                ->update('#__update_sites')
                ->set('extra_query=' . $db->quote('purchase_code=' . $params->get('purchase_code', '')))
                ->where('name=' . $db->quote('Google Reviews Pro'));
        $db->setQuery($query);
        $db->execute();
    }
    

}
