<?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
 */

namespace D3\ModCfg\Application\Controller\Admin;

use D3\ModCfg\Application\Model\Exception\d3ShopCompatibilityAdapterException;
use Doctrine\DBAL\DBALException;
use OxidEsales\Eshop\Application\Controller\Admin\AdminDetailsController;
use D3\ModCfg\Application\Model\Shopcompatibility\d3shopversionconverter;
use D3\ModCfg\Application\Model\Log\d3log;
use D3\ModCfg\Application\Model\Configuration\d3_cfg_mod;
use D3\ModCfg\Application\Model\Install\d3install;
use D3\ModCfg\Application\Model\Installcheck\d3installcheck;
use D3\ModCfg\Application\Model\d3utils;
use D3\ModCfg\Application\Model\d3filesystem;
use D3\ModCfg\Application\Model\d3str;
use D3\ModCfg\Application\Model\d3feeds;
use D3\ModCfg\Application\Model\Exception\d3_cfg_mod_exception;
use OxidEsales\Eshop\Core\Exception\DatabaseConnectionException;
use OxidEsales\Eshop\Core\Exception\DatabaseErrorException;
use OxidEsales\Eshop\Core\Exception\StandardException;
use OxidEsales\Eshop\Core\Request;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\Exception\DatabaseException;

class d3_cfg_mod_licence extends AdminDetailsController
{
    protected $_sThisTemplate = 'd3_cfg_mod_licence.tpl';
    protected $_sModId = 'd3modcfg_lib';
    protected $_hasLicence = false;
    protected $_hasUpdate = true;
    protected $_hasNewsletterForm = false;
    protected $_modUseCurl = false;
    protected $_sMenuItemTitle = 'd3mxcfg';
    protected $_sMenuSubItemTitle = 'd3tbcllib_support';
    protected $_sBlogFeed = "https://blog.oxidmodule.com/index.php?/feeds/index.rss2";
    protected $_sLogType = d3log::EMERGENCY;
    protected $_oInfoMail;
    public $mBlogContent;
    public $sHelpURL;
    public $oUpdateData;
    public $oNewestData;
    public $sAction;
    protected $_aMessages = array();
    public $mRevisionCheck = null;
    /**
     * @var string
     */
    protected $_sDefaultHelpLinkAdd = 'Modul-Connector/';
    /**
     * additional multilang item, which will added as last part to help url
     *
     * @var string
     */
    protected $_sHelpLinkMLAdd = 'D3MODCFG_LIB_HELPLINK_SUPPORT';

    /**
     * @return string
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     */
    public function render()
    {
        startProfile(__METHOD__);

        $sRet = parent::render();

        $this->addTplParam('edit', $this->d3GetSet());
        $this->addTplParam('oxid', $this->d3GetSet()->getId());

        stopProfile(__METHOD__);

        return $sRet;
    }

    /**
     * @return d3_cfg_mod
     */
    /**
     * @return d3_cfg_mod
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     */
    public function d3GetSet()
    {
        return d3_cfg_mod::get($this->d3getModId());
    }

    /**
     * @return string
     */
    public function d3getModId()
    {
        return $this->_sModId;
    }

    /**
     * ruft oxutils-Funktion auf, die vom Template aus nicht verfuegbar ist
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     * @throws d3ShopCompatibilityAdapterException
     * @throws StandardException
     * @throws d3_cfg_mod_exception
     */
    public function save()
    {
        $this->d3GetSet()->prepareSaveData();
        $this->d3GetSet()->save();

        return;
    }

    /**
     * @return bool
     */
    public function getInstallClass()
    {
        if (class_exists(d3install::class)) {
            return true;
        }
        return false;
    }

    /**
     * @return bool
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     * @throws StandardException
     * @throws d3ShopCompatibilityAdapterException
     * @throws d3_cfg_mod_exception
     */
    public function checkUpdate()
    {
        startProfile(__METHOD__);

        $oInstall      = d3install::getInstance();
        $oUpdateServer = $oInstall->getFromUpdateServer();

        $oModCfg = $this->d3GetSet();
        if ($oModCfg->getModCfgError()) {
            return false;
        }

        if ($this->d3GetSet()->getLicenseData('modversion')) {
            $oUpdateServer->setParameter('sLicModVersion', $this->d3GetSet()->getLicenseData('modversion'));
        }

        /** @var d3shopversionconverter $oShopVersionConverter */
        $oShopVersionConverter = oxNew(d3shopversionconverter::class);
        $oUpdateServer->setParameter('sModId', $this->d3getModId());
        $oUpdateServer->setParameter(
            'sEdition',
            $oShopVersionConverter->fixEditionToDefaultEdition($this->getShopEdition())
        );
        $oUpdateServer->setParameter(
            'sShopVersion',
            $oShopVersionConverter->fixVersionToDefaultEdition($this->getShopVersion())
        );
        $aUpdateData = $oUpdateServer->getRemoteModuleVersion();

        $this->sAction = 'versionCheck';

        if (version_compare(
            $aUpdateData['availableversion']['version'],
            $oInstall->getInstalledModVersion($this->d3getModId()),
            '>'
        )) {
            $this->oUpdateData = $aUpdateData['availableversion'];
        }

        if ($aUpdateData['newestversion'] &&
            is_array($aUpdateData['newestversion']) &&
            count($aUpdateData['newestversion'])
        ) {
            $this->oNewestData = $aUpdateData['newestversion'];
        }

        stopProfile(__METHOD__);

        return false;
    }

    /**
     * @return string
     */
    public function getAction()
    {
        return $this->sAction;
    }

    /**
     * @param $sPart
     * @return mixed
     */
    public function getUpdateData($sPart)
    {
        return $this->oUpdateData[$sPart];
    }

    /**
     * @param $sPart
     * @return mixed
     */
    public function getNewestModuleData($sPart)
    {
        return $this->oNewestData[$sPart];
    }

    public function installMod()
    {
        $this->addTplParam('sInstallModId', Registry::get(Request::class)->getRequestEscapedParameter('modid'));
    }

    /**
     * request newsletter form
     */
    public function setInfoMail()
    {
        $this->_oInfoMail = new \stdClass;
        $oInfoMailXML     = false;
        $iError           = false;

//        $aParams = oxConfig::getParameter("service");

//        $sEMail   = trim($aParams['d3_cfg_mod__s_updateinfomail']);
//        $blActive = (bool)$aParams['d3_cfg_mod__bl_updateinfo'];
        /*
                if (strlen($sEMail) && !d3_oxUtils_cfg::getInstance()->D3checkEmail($sEMail))
                {
                    $this->_oInfoMail->iError = 1;
                    return false;
                }
        */
        //d3_oxUtils_cfg::getInstance()->setModInfoMail($this->soxId, $oInfoMailXML, $iError, $sEMail, $blActive);

        $this->_oInfoMail->iError = $iError;

        $this->_oInfoMail->oXML = $oInfoMailXML;
        //if ($iError) return;

        // is removed
//        d3_oxUtils_cfg::getInstance()->SaveModCfg($this->soxId);
        //$this->d3GetSet()->d3_cfg_mod__importer_supdateinfomail = new oxField($sEMail, oxField::T_RAW);
        //$this->d3GetSet()->d3_cfg_mod__importer_blupdateinfo = new oxField($blActive, oxField::T_RAW);
        //$this->d3GetSet()->Save();
        //dumpvar($_POST);
    }

    /**
     * schreibt Lizenzkey in Modulconfig
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     * @throws StandardException
     * @throws d3ShopCompatibilityAdapterException
     * @throws d3_cfg_mod_exception
     */
    public function submit_licensekey()
    {
        if (false == $this->hasDemoShopMode()) {
            $this->d3GetSet()->setSerial(Registry::get(Request::class)->getRequestEscapedParameter('licensekey'));
            $this->d3GetSet()->save();
        }
    }

    /**
     * @return bool
     */
    public function hasDemoShopMode()
    {
        return d3utils::getInstance()->hasDemoShopMode();
    }

    public function image_logo()
    {
        $img_data =
            " ";
        header("Content-type: image/gif");
        echo base64_decode($img_data);
        exit;
    }

    /**
     * @return mixed
     */
    public function getLogoUrl()
    {
        $aParams = array(
            'cl'  => $this->getClassKey(),
            'fnc' => 'image_logo'
        );
        $sURL    = Registry::get(d3utils::class)->getAdminClassUrl($aParams);

        return $sURL;
    }

    /**
     * @return bool
     */
    public function hasLicense()
    {
        return $this->_hasLicence;
    }

    /**
     * @return bool
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     */
    public function hasLicenseKey()
    {
        if ($this->d3GetSet()->getFieldData('oxserial')) {
            return true;
        }

        return false;
    }

    /**
     * @return bool
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     * @throws StandardException
     * @throws d3ShopCompatibilityAdapterException
     * @throws d3_cfg_mod_exception
     */
    public function hasUpdate()
    {
        if (class_exists(d3install::class)) {
            $oModCfg = $this->d3GetSet();
            if ($oModCfg->getModCfgError()) {
                return false;
            }

            return true;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function hasNewsletterForm()
    {
        return $this->_hasNewsletterForm;
    }

    /**
     * @return string
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     */
    public function checkModuleVersion()
    {
        if (ip2long($this->d3GetSet()->getFieldData('oxversion')) == $this->d3GetSet()->getFieldData('oxversionnum')) {
            return 'OK';
        }

        return 'NOK';
    }

    /**
     * @return bool
     */
    public function d3CheckCurl()
    {
        if (false == function_exists('curl_init')) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * @return bool
     */
    public function d3ModUseCurl()
    {
        return $this->_modUseCurl;
    }

    /**
     * @param $sShopVersion
     * @return mixed
     */
    public function check4ShopUpdate($sShopVersion)
    {
        /** @var d3shopversionconverter $oShopVersionConverter */
        $oShopVersionConverter = oxNew(d3shopversionconverter::class);
        return version_compare(
            $oShopVersionConverter->fixVersionToDefaultEdition($this->getShopVersion()),
            $sShopVersion,
            "<"
        );
    }

    /**
     * @param $sModId
     * @param $sModVersion
     * @return bool
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     * @throws StandardException
     * @throws d3ShopCompatibilityAdapterException
     * @throws d3_cfg_mod_exception
     */
    public function check4LicenseUpdate($sModId, $sModVersion)
    {
        /** @var $oStr d3str */
        $oStr = oxNew(d3str::class);
        if ($this->d3GetSet()->getLicenseData('modversion')) {
            if ($oStr->versionToInt($sModVersion, 999) >
                $oStr->versionToInt(d3_cfg_mod::get($sModId)->getLicenseData('modversion'), 999)
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     * @throws StandardException
     * @throws d3ShopCompatibilityAdapterException
     * @throws d3_cfg_mod_exception
     */
    public function filedownload()
    {
        if (false == Registry::get(d3utils::class)->hasDemoshopMode()) {
            $this->checkUpdate();

            if (strtolower(Registry::get(Request::class)->getRequestEscapedParameter('type')) == 'newest') {
                if ($this->getNewestModuleData($this->getPhpVersionDownloadField(true)) && $this->getInstallClass()) {
                    /** @var $oFS d3filesystem */
                    $oFS = oxNew(d3filesystem::class);
                    $oFS->startDirectDownload($this->getNewestModuleData($this->getPhpVersionDownloadField(true)));
                } elseif ($this->getNewestModuleData($this->getPhpVersionDownloadField(false)) && $this->getInstallClass()) {
                    /** @var $oFS d3filesystem */
                    $oFS = oxNew(d3filesystem::class);
                    $oFS->startDirectDownload($this->getNewestModuleData($this->getPhpVersionDownloadField(false)));
                }
            } elseif ($this->getUpdateData($this->getPhpVersionDownloadField(true)) && $this->getInstallClass()) {
                $oFS = oxNew(d3filesystem::class);
                $oFS->startDirectDownload($this->getUpdateData($this->getPhpVersionDownloadField(true)));
            } elseif ($this->getUpdateData($this->getPhpVersionDownloadField(false)) && $this->getInstallClass()) {
                $oFS = oxNew(d3filesystem::class);
                $oFS->startDirectDownload($this->getUpdateData($this->getPhpVersionDownloadField(false)));
            }
        }
    }

    /**
     * @return string
     */
    public function d3GetMenuItemTitle()
    {
        return $this->_sMenuItemTitle;
    }

    /**
     * @return string
     */
    public function d3GetMenuSubItemTitle()
    {
        return $this->_sMenuSubItemTitle;
    }

    /**
     * @return string
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     */
    public function getHelpURL()
    {
        if ($this->sHelpURL === null) {
            $this->sHelpURL = false;

            startProfile(__METHOD__);

            $sUrl = $this->d3GetSet()->getHelpURL();
            /** @var $oFS d3filesystem */
            $oFS = oxNew(d3filesystem::class);

            if (false == $this->d3GetSet()->getHelpUrlAdd()) {
                $sUrl .= $oFS->unprefixedslashit($this->_sDefaultHelpLinkAdd);
            }

            if ($this->_sHelpLinkMLAdd) {
                $sUrl .= $oFS->unprefixedslashit(Registry::getLang()->TranslateString($this->_sHelpLinkMLAdd));
            }

            $aFileName = $oFS->splitFilename($sUrl);

            // has no extension
            if (false == $aFileName['ext']) {
                $sUrl = $oFS->trailingslashit($sUrl);
            }

            stopProfile(__METHOD__);

            $this->sHelpURL = $sUrl;
        }

        return $this->sHelpURL;
    }

    /**
     * @return bool|mixed
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     * @throws StandardException
     * @throws DatabaseException
     * @throws d3ShopCompatibilityAdapterException
     * @throws d3_cfg_mod_exception
     */
    public function hasBlogContent()
    {
        if ($this->mBlogContent === null) {
            $this->mBlogContent = false;

            startProfile(__METHOD__);

            $oModCfgSet = d3_cfg_mod::get('d3modcfg_lib');
            if ((isset($oModCfgSet)
                    && false == $oModCfgSet->getValue('blModCfg_noSupportBlogInfo')) ||
                (false == $this->d3GetSet()->getValue('blModCfg_noSupportBlogInfo'))
            ) {
                /** @var $oFeed d3feeds */
                $oFeed              = oxNew(d3feeds::class);
                $this->mBlogContent = $oFeed->getAdminSupportContent($this->_sBlogFeed);
            }

            stopProfile(__METHOD__);
        }

        return $this->mBlogContent;
    }

    /**
     * @return string
     */
    public function getBlogBaseUrl()
    {
        /** @var $oFeed d3feeds */
        $oFeed = oxNew(d3feeds::class);
        return $oFeed->getBlogBaseUrl();
    }

    /**
     * @return string
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     * @throws StandardException
     * @throws d3ShopCompatibilityAdapterException
     * @throws d3_cfg_mod_exception
     */
    public function getExpireSpanString()
    {
        if ($this->d3GetSet()->isExpired()) {
            return Registry::getLang()->translateString('D3_CFG_MOD_STATUS_EXPIRED');
        }

        return sprintf(
            Registry::getLang()->translateString("D3_CFG_MOD_STATUS_EXPIRES_IN"),
            $this->d3GetSet()->getExpireTimeSpan()
        );
    }

    /**
     * @param bool $blForceIonCube
     * @return bool|string
     */
    public function getPhpVersionDownloadField($blForceIonCube = false)
    {
        return d3install::getInstance()->getPhpVersionDownloadField($blForceIonCube);
    }

    /**
     * @return array
     */
    public function getUserMessages()
    {
        return $this->_aMessages;
    }

    /**
     * @param $sModId
     * @return mixed
     */
    public function getLicenceFrameUrl($sModId)
    {
        $aParams = array(
            'cl'  => 'd3mod_activation',  # don't use d3mod_activation::class
            'modid' => $sModId,
            'bgcolor' => '#F0F0F0'
        );
        return Registry::get(d3utils::class)->getAdminClassUrl($aParams);
    }

    /**
     * @return d3installcheck
     * @throws DBALException
     * @throws DatabaseConnectionException
     * @throws DatabaseErrorException
     */
    public function getInstallCheck()
    {
        $oInstallCheck = oxNew(d3installcheck::class, $this->d3GetSet());

        return $oInstallCheck;
    }

    /**
     * @return string
     */
    public function getLink()
    {
        return '';
    }
}
