<?php

/**
 * This Software is the property of Data Development and is protected
 * by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * http://www.shopmodule.com
 *
 * @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
 * @author    D3 Data Development - Daniel Seifert <support@shopmodule.com>
 * @link      http://www.oxidmodule.com
 */

class d3_navigation_modcfgupdate extends d3_navigation_modcfgupdate_parent
{
    public function init()
    {
        oxRegistry::getConfig()->getActiveView()->addTplParam('clearTpl', false);
        oxRegistry::getConfig()->getActiveView()->addTplParam('clearLang', false);
        oxRegistry::getConfig()->getActiveView()->addTplParam('clearTplLang', false);
        return parent::init();
    }

    /**
     * @return string
     */
    public function render()
    {
        $sRet = parent::render();

        if ($sRet == 'header.tpl'
            && false == oxRegistry::getConfig()->getConfigParam('blDemoShop')
            && class_exists('d3_cfg_mod')
            && d3_cfg_mod::isCallable()
            && d3_cfg_mod::get('d3modcfg_lib')->getValue('blClrTmp_shownoheaderform') != 1
        ) {
            $this->addTplParam('sOriginalTplName', $sRet);
            $this->addTplParam('oModCfg', d3_cfg_mod::get('d3modcfg_lib'));
            $sRet = 'd3_adm_header.tpl';
        }

        if ($sRet == 'navigation.tpl') {
            $sRet = 'd3_adm_navigation.tpl';
        }

        return $sRet;
    }

    public function d3ShowAdminLayoutChanges()
    {
        if (class_exists('d3_cfg_mod')
            && d3_cfg_mod::isCallable()
        ) {
            return (bool) d3_cfg_mod::get('d3modcfg_lib')->getValue('blModCfg_hideAdminLayoutChanges') ? false : true;
        }

        return true;
    }

    /**
     * @return array
     */
    protected function _doStartUpChecks()
    {
        $aMessage = parent::_doStartUpChecks();

        $aMessage = array_merge($aMessage, $this->_d3ModLicenceCheck());
        $aMessage = array_merge($aMessage, $this->_d3ModUpdateCheck());
        $aMessage = array_merge($aMessage, $this->_doModCfgUpdateRequired());

        return $aMessage;
    }

    /**
     * @return array
     */
    protected function _doModCfgUpdateRequired()
    {
        if (oxRegistry::getConfig()->getConfigParam('blD3IgnoreAutoUpdate')) {
            return array();
        }

        startProfile(__METHOD__);

        $aMessages = array();

        if (class_exists('d3install') && d3install::getInstance()->getUpdateInstaller()->getRequiredUpdates()) {
            $aMessages['d3__updatecheck'] = sprintf(
                oxRegistry::getLang()->translateString('D3_UPDATE_REQUIRED_MODCFGUPDATE'),
                $this->_d3getUpdateWizzardUrl()
            );
        }

        stopProfile(__METHOD__);

        return $aMessages;
    }

    /**
     * @return array
     */
    protected function _d3ModLicenceCheck()
    {
        startProfile(__METHOD__);

        $aMessages = array();

        if (false == class_exists('d3_cfg_mod') ||
            false == d3_cfg_mod::isCallable() ||
            d3_cfg_mod::get('d3modcfg_lib')->getValue('blModCfg_noAdminHomeInfo') >= 1
        ) {
            stopProfile(__METHOD__);
            return $aMessages;
        }

        $aModuleList = d3_cfg_mod::get('d3modcfg_lib')->getModuleList(oxRegistry::getConfig()->getShopId());

        foreach ($aModuleList as $mModule) {
            $sModId = is_array($mModule) ? $mModule['id'] : $mModule;

            $oModule = d3_cfg_mod::get($sModId);
            $sLinkTarget = 'http://www.oxidmodule.com/';

            if ($oModule->isExpired()) {
                $aMessages[$sModId.'_exp'] = sprintf (
                    oxRegistry::getLang()->translateString('D3_UPDATE_EXPIREDMODULE'),
                    $sLinkTarget,
                    $oModule->getModTitle()
                );
            } elseif ($oModule->expiresSoon()) {
                $aMessages[$sModId.'_exp'] = sprintf (
                    oxRegistry::getLang()->translateString('D3_UPDATE_EXPIRESOONMODULE'),
                    $sLinkTarget,
                    $oModule->getModTitle(),
                    $oModule->getExpireTimeSpan()
                );
            }
        }

        stopProfile(__METHOD__);

        return $aMessages;
    }

    /**
     * @return array
     */
    protected function _d3ModUpdateCheck()
    {
        startProfile(__METHOD__);

        $aMessages = array();

        if (false == class_exists('d3_cfg_mod') ||
            false == d3_cfg_mod::isCallable() ||
            d3_cfg_mod::get('d3modcfg_lib')->getValue('blModCfg_noAdminHomeInfo') >= 1
        ) {
            stopProfile(__METHOD__);
            return $aMessages;
        }

        $iAllTimeOut = 10;
        $aModuleList = d3_cfg_mod::get('d3modcfg_lib')->getModuleList(oxRegistry::getConfig()->getShopId());
        $iModuleCount = count($aModuleList);
        $dTimeOut = $iAllTimeOut / $iModuleCount > 1 ? 1 : $iAllTimeOut / $iModuleCount;

        foreach ($aModuleList as $mModule) {
            $sModId = is_array($mModule) ? $mModule['id'] : $mModule;

            if ($this->isModuleActive($sModId) && d3_cfg_mod::get($sModId)->getActiveStatus()) {
                /** @var d3shopversionconverter $oShopVersionConverter */
                $oShopVersionConverter = oxNew('d3shopversionconverter');
                $oUpdateServer = d3install::getInstance()->getFromUpdateServer();
                $oUpdateServer->setParameter('sModId', $sModId);
                $oUpdateServer->setParameter(
                    'sEdition',
                    $oShopVersionConverter->fixEditionToDefaultEdition(
                        oxRegistry::getConfig()->getEdition()
                    )
                );
                $oUpdateServer->setParameter(
                    'sShopVersion',
                    $oShopVersionConverter->fixVersionToDefaultEdition(
                        oxRegistry::getConfig()->getVersion()
                    )
                );

                if (d3_cfg_mod::get($sModId)->getLicenseData('modversion')) {
                    $oUpdateServer->setParameter(
                        'sLicModVersion',
                        d3_cfg_mod::get($sModId)->getLicenseData('modversion')
                    );
                }
                if (d3_cfg_mod::get($sModId)->getFieldData('oxversion') &&
                    d3_cfg_mod::get($sModId)->getFieldData('oxversion') != 'basic'
                ) {
                    $oUpdateServer->setParameter('sModVersion', d3_cfg_mod::get($sModId)->getFieldData('oxversion'));
                }
                $oUpdateServer->setParameter('dTimeOut', $dTimeOut);

                $aRemoteModVersion = $oUpdateServer->getRemoteModuleVersion();

                if (strtolower($aRemoteModVersion['availableversion']['version']) != '' &&
                    version_compare(
                        $aRemoteModVersion['availableversion']['version'],
                        d3_cfg_mod::get($sModId)->getFieldData('oxversion'),
                        '>'
                    )
                ) {
                    $aMessages[$sModId.'_upd'] = $aRemoteModVersion['availableversion']['infourl'] ?
                        sprintf(
                            oxRegistry::getLang()->translateString('D3_UPDATE_AVAILABLE_VERSION'),
                            $aRemoteModVersion['availableversion']['infourl'],
                            d3_cfg_mod::get($sModId)->getModTitle(),
                            $aRemoteModVersion['availableversion']['version']
                        ) :
                        sprintf(
                            oxRegistry::getLang()->translateString('D3_UPDATE_AVAILABLE_VERSION_NOLINK'),
                            d3_cfg_mod::get($sModId)->getModTitle(),
                            $aRemoteModVersion['availableversion']['version']
                        );
                }
            }
        }

        stopProfile(__METHOD__);

        return $aMessages;
    }

    /**
     * @return string
     */
    protected function _d3getUpdateWizzardUrl()
    {
        startProfile(__METHOD__);

        $aParams = array(
            'cl'         => 'd3_mod_update',
            'formercl'   => $this->getClassName(),
            'formeritem' => oxRegistry::getConfig()->getRequestParameter('item'),
            'blHideSkip' => 'true'
        );
        $sURL    = oxRegistry::get('d3utils')->getAdminClassUrl($aParams);

        stopProfile(__METHOD__);

        return $sURL;
    }

    /**
     * @param $sModCfgId
     *
     * @return bool
     */
    protected function isModuleActive($sModCfgId)
    {
        startProfile(__METHOD__);

        $sMetaModuleId = d3_cfg_mod::get('d3modcfg_lib')->getMetaModuleId($sModCfgId);

        /** @var oxmodule $oModule */
        $oModule = oxNew('oxmodule');
        $oModule->load($sMetaModuleId);

        $blActive = $oModule->isActive();

        stopProfile(__METHOD__);

        return $blActive;
    }

    public function d3ClearTmp()
    {
        /** @var $oClrTmp d3clrtmp */
        $oClrTmp = oxNew('d3clrtmp');

        if (oxRegistry::getConfig()->getRequestParameter('d3clrtmpcachetype') == 'all') {
            oxRegistry::getConfig()->getActiveView()->addTplParam('clearAll', true);
            $oClrTmp->clearAllCache();
        } elseif (oxRegistry::getConfig()->getRequestParameter('d3clrtmpcachetype') == 'tpllang') {
            oxRegistry::getConfig()->getActiveView()->addTplParam('clearTplLang', true);
            $oClrTmp->clearFrontendCache() && $oClrTmp->clearLangCache();
        } elseif (oxRegistry::getConfig()->getRequestParameter('d3clrtmpcachetype') == 'tpl') {
            oxRegistry::getConfig()->getActiveView()->addTplParam('clearTpl', true);
            $oClrTmp->clearFrontendCache();
        } elseif (oxRegistry::getConfig()->getRequestParameter('d3clrtmpcachetype') == 'lang') {
            oxRegistry::getConfig()->getActiveView()->addTplParam('clearLang', true);
            $oClrTmp->clearLangCache();
        }
    }

    public function d3ExecCommand1()
    {
        /** @var $oClrTmp d3clrtmp */
        $oClrTmp = oxNew('d3clrtmp');
        $oClrTmp->d3ExecCommand(1);
    }

    public function d3ExecCommand2()
    {
        /** @var $oClrTmp d3clrtmp */
        $oClrTmp = oxNew('d3clrtmp');
        $oClrTmp->d3ExecCommand(2);
    }
}
