<?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_oxemail_usermanager extends d3_oxemail_usermanager_parent
{
    protected $_sUserManagerInfoTemplate = 'd3usermanager_info_html.tpl';
    protected $_sUserManagerInfoPlainTemplate = 'd3usermanager_info_plain.tpl';
    private $_sModId = 'd3usermanager';
    /** @var  d3usermanager */
    public $oUserManager;

    /**
     * constructor
     */
    public function __construct()
    {
        $this->_oConfig = oxRegistry::getConfig();

        parent::__construct();
    }

    /**
     * @param $aUserManagerNotes
     * @return bool
     */
    public function d3sendUserManagerEmail($aUserManagerNotes)
    {
        startProfile(__METHOD__);

        $oShop = $this->_getShop();
        $oSmarty = $this->_getSmarty();

        $this->_setMailParams($oShop);
        $this->setViewData("aNotes", $aUserManagerNotes);
        $this->setViewData("shopTemplateDir", oxRegistry::getConfig()->getTemplateDir(false));
        $this->setViewData("oShop", $oShop);
        $oSmarty->template_dir = oxRegistry::getConfig()->getTemplateDir(false);

        $this->_processViewArray();

        $this->setBody($oSmarty->fetch($this->_sUserManagerInfoTemplate));
        $this->setAltBody($oSmarty->fetch($this->_sUserManagerInfoPlainTemplate));

        d3_cfg_mod::get($this->_sModId)->d3getLog()->log(
            d3log::NOTICE,
            __CLASS__,
            __FUNCTION__,
            __LINE__,
            'send job execution info mail',
            $this->getBody()
        );

        $sSubject = oxRegistry::getLang()->translateString('D3_USERMANAGER_MAIL_USERSUBJECT', 0);
        $this->setSubject($sSubject);

        $sFullName = $oShop->__get('oxshops__oxname')->getRawValue();
        $this->setRecipient($oShop->getFieldData('oxinfoemail'), $sFullName);
        $this->setReplyTo($oShop->getFieldData('oxinfoemail'), $oShop->__get('oxshops__oxname')->getRawValue());

        $blSuccess = $this->send();

        stopProfile(__METHOD__);

        return $blSuccess;
    }

    /**
     * @param $sOxId
     * @return oxuser
     */
    public function d3getUser($sOxId)
    {
        if (strstr($sOxId, '@@')) {
            $aOxId = explode('@@', $sOxId);
            $sOxId = $aOxId[0];
        }

        /** @var $oUser oxuser */
        $oUser = oxNew('oxuser');
        $oUser->Load($sOxId);
        return $oUser;
    }

    /**
     * @param $sOxId
     * @return d3usermanager
     */
    public function d3getUserManager($sOxId)
    {
        /** @var $oUser d3usermanager */
        $oUser = oxNew('d3usermanager');
        $oUser->Load($sOxId);
        return $oUser;
    }

    /**
     * @param d3usermanager $oUserManager
     * @return bool
     */
    public function sendUserManagerMail(d3usermanager $oUserManager)
    {
        $this->oUserManager = $oUserManager;
        $aContent = $this->getUserManagerMailContent($oUserManager);

        $oShop = $this->_getShop();
        $this->setBody($aContent['html']);
        $this->setAltBody($aContent['plain']);
        $this->setSubject($aContent['subject']);

        $this->_d3SetUserManagerReplyAddress($oUserManager, $oShop);

        $oRemark = $this->_d3SetUserManagerMailRecipients($oShop);

        $blSuccess = $this->send();

        if ($blSuccess && $oRemark) {
            $oRemark->save();
        }

        return $blSuccess;
    }

    /**
     * @param oxshop         $oShop
     *
     * @return null|oxremark
     */
    protected function _d3SetUserManagerMailRecipients(oxshop $oShop)
    {
        $oRemark = null;
        if ($this->_d3hasUserManagerCustomerRecipient()) {
            $oRemark = $this->_d3sendUserManagerMailToCustomer($oShop);
        } elseif ($this->_d3hasUserManagerOwnerRecipient()) {
            $this->_d3sendUserManagerMailToOwner($oShop);
        } elseif ($this->_d3hasUserManagerCustomRecipient()) {
            $this->_d3sendUserManagerMailToCustom();
        }

        return $oRemark;
    }

    /**
     * @param               $sVarName
     *
     * @return mixed
     */
    protected function _d3getUserManagerMailOption($sVarName)
    {
        $aEditedValues = $this->oUserManager->getEditedValues();
        return $aEditedValues[$sVarName] === false || $aEditedValues[$sVarName] === null ?
            $this->oUserManager->getValue($sVarName) :
            $aEditedValues[$sVarName];
    }

    /**
     * @return mixed
     */
    protected function _d3hasUserManagerCustomerRecipient()
    {
        return $this->_d3getUserManagerMailOption('blSendMailToCustomer');
    }

    /**
     * @return mixed
     */
    protected function _d3hasUserManagerOwnerRecipient()
    {
        return $this->_d3getUserManagerMailOption('blSendMailToOwner');
    }

    /**
     * @return mixed
     */
    protected function _d3hasUserManagerCustomRecipient()
    {
        return $this->_d3getUserManagerMailOption('blSendMailToCustom');
    }

    /**
     * @return mixed
     */
    protected function _d3getUserManagerCustomRecipientList()
    {
        return $this->_d3getUserManagerMailOption('sSendMailToCustomAddress');
    }

    /**
     * @return d3_cfg_mod
     */
    public function d3GetSet()
    {
        return d3_cfg_mod::get($this->_sModId);
    }

    /**
     * @param d3usermanager $oUserManager
     * @return array
     */
    public function getUserManagerMailContent(d3usermanager $oUserManager)
    {
        $this->oUserManager = $oUserManager;
        $aContent = array();

        $blTplFromAdmin = $oUserManager->getValue('sSendMailFromTheme') == 'admin' ? true : false;
        oxRegistry::getConfig()->setAdminMode($blTplFromAdmin);

        $oShop = $this->_getShop();
        $this->_setMailParams($oShop);

        $oSmarty = $this->_getSmarty();

        $this->setViewData("oShop", $oShop);
        $this->setViewData("oViewConf", $this->getViewConfig());
        $this->setViewData("oUser", $oUserManager->getCurrentItem());
        $this->setViewData("shopTemplateDir", oxRegistry::getConfig()->getTemplateDir(false));
        $this->setViewData("charset", oxRegistry::getLang()->translateString("charset"));

        $this->setViewData("shop", $oShop);
        $this->setViewData("user", $oUserManager->getCurrentItem());

        $oSmarty->template_dir = $this->getTemplateDir4UserManager($oUserManager);
        $this->_processViewArray();

        if (false == $this->d3GetSet()->getLicenseConfigData('blUseMailSendOnly', 0)) {
            $oSmarty = $this->d3SendMailHook($oSmarty);
        }

        $aContent = $this->_d3GenerateUserManagerMailContent($aContent, $oSmarty);

        oxRegistry::getConfig()->setAdminMode(true);

        return $aContent;
    }

    /**
     * @param d3usermanager $oUserManager
     * @return string
     */
    public function getTemplateDir4UserManager($oUserManager)
    {
        if ($oUserManager->getValue('sSendMailFromTheme') == 'module') {
            /** @var oxmodule $oModule */
            $oModule = oxNew('oxmodule');
            /** @var d3str $oD3Str */
            $oD3Str = oxNew('d3str');
            $sModuleId = $oUserManager->getValue('sSendMailFromModulePath');

            /** @var d3ShopCompatibilityAdapterHandler $oD3CompatibilityAdapterHandler */
            $oD3CompatibilityAdapterHandler = oxNew('d3ShopCompatibilityAdapterHandler');
            $sModulePath = $oD3CompatibilityAdapterHandler->call(
                'oxmodule__getModuleFullPath',
                array($oModule, $sModuleId)
            );

            $sPath = $oD3Str->untrailingslashit($sModulePath);
        } else {
            $blAdmin = $oUserManager->getValue('sSendMailFromTheme') == 'admin' ? true : false;
            $sPath   = oxRegistry::getConfig()->getTemplateDir($blAdmin);
        }
        return $sPath;
    }

    /**
     * @param smarty $oSmarty
     * @return smarty
     */
    public function d3SendMailHook(smarty $oSmarty)
    {
        // available objects:
        // oxEmail:                $this
        // Smarty:                 $oSmarty
        // Usermanager profile:    $this->oUserManager
        // oxuser:                 inside smarty

        return $oSmarty;
    }

    /**
     * @param               $aContent
     * @param smarty        $oSmarty
     *
     * @return mixed
     */
    protected function _d3GenerateUserManagerMailContent($aContent, smarty $oSmarty)
    {
        $aEditedValues = $this->oUserManager->getEditedValues();

        if ($this->d3HasUserManagerEditorMailContent($aEditedValues)) {
            $aContent = $aEditedValues['mail'];
        } elseif ($this->oUserManager->getValue('sSendMailFromSource') == 'cms') {
            $oLang        = oxRegistry::getLang();
            $iUserLangId = $oLang->getTplLanguage();
            $iCurrentLang = $oLang->getTplLanguage();
            $oLang->setTplLanguage($iUserLangId);

            /** @var oxUtilsView $oUtilsView */
            $oUtilsView = oxRegistry::get('oxUtilsView');
            /** @var $oContent oxcontent */
            $oContent = oxNew('oxcontent');
            $oContent->setLanguage($iUserLangId);
            $oContent->load($this->oUserManager->getValue('sSendMailFromContentname'));

            $aContent['html']    = $oUtilsView->parseThroughSmarty(
                $oContent->getFieldData('oxcontent'),
                $oContent->getId() . 'oxcontent'
            );

            $aContent['subject'] = $oContent->getFieldData('oxtitle');
            $oContent->load($this->oUserManager->getValue('sSendMailFromContentnamePlain'));
            $aContent['plain'] = $oUtilsView->parseThroughSmarty(
                $oContent->getFieldData('oxcontent'),
                $oContent->getId() . 'oxcontent'
            );
            $oLang->setTplLanguage($iCurrentLang);
        } elseif ($this->oUserManager->getValue('sSendMailFromSource') == 'template') {
            $aContent['html']    = $oSmarty->fetch($this->oUserManager->getValue('sSendMailFromTemplatename'));
            $aContent['plain']   = $oSmarty->fetch($this->oUserManager->getValue('sSendMailFromTemplatenamePlain'));
            $aContent['subject'] = $oSmarty->fetch($this->oUserManager->getValue('sSendMailFromSubject'));
        }

        return $aContent;
    }

    /**
     * @param $aEditedValues
     *
     * @return bool
     */
    public function d3HasUserManagerEditorMailContent($aEditedValues)
    {
        return $this->isArrayEditorMailContent($aEditedValues) &&
               $aEditedValues['mail']['subject'] &&
               $aEditedValues['mail']['html'] &&
               $aEditedValues['mail']['plain'];
    }

    /**
     * @param $aEditedValues
     *
     * @return bool
     */
    public function isArrayEditorMailContent($aEditedValues)
    {
        return is_array($aEditedValues) && is_array($aEditedValues['mail']);
    }

    /**
     * @param oxshop        $oShop
     *
     * @return oxremark
     */
    protected function _d3sendUserManagerMailToCustomer(oxshop $oShop)
    {
        $sFullName = $this->oUserManager->getCurrentItem()->__get('oxuser__oxfname')->getRawValue() . " " .
            $this->oUserManager->getCurrentItem()->__get('oxuser__oxlname')->getRawValue();
        $this->setRecipient($this->oUserManager->getCurrentItem()->getFieldData('oxusername'), $sFullName);

        if ($this->_d3hasUserManagerOwnerRecipient()) {
            $this->AddBcc($oShop->getFieldData('oxinfoemail'), $oShop->__get('oxshops__oxname')->getRawValue());
        }

        if ($this->_d3HasUserManagerCustomMailAddresses()) {
            foreach ($this->_d3getUserManagerCustomMailAddressList() as $sMailAdr) {
                $this->AddBcc(trim($sMailAdr), trim($sMailAdr));
            }
        }

        // add user history
        /** @var oxremark $oRemark */
        $oRemark                       = oxNew("oxremark");
        $aRemarkContent = array(
            'oxtext'        => $this->getAltBody(),
            'oxparentid'    => $this->oUserManager->getCurrentItem()->getId(),
            'oxtype'        => 'o',
        );
        $oRemark->assign($aRemarkContent);
        return $oRemark;
    }

    /**
     * @param oxshop        $oShop
     */
    protected function _d3sendUserManagerMailToOwner(oxshop $oShop)
    {
        $sFullName = $oShop->__get('oxshops__oxname')->getRawValue();
        $this->setRecipient($oShop->getFieldData('oxinfoemail'), $sFullName);

        if ($this->_d3HasUserManagerCustomMailAddresses()) {
            foreach ($this->_d3getUserManagerCustomMailAddressList() as $sMailAdr) {
                $this->AddBcc(trim($sMailAdr), trim($sMailAdr));
            }
        }
    }

    protected function _d3sendUserManagerMailToCustom()
    {
        if ($this->_d3hasUserManagerCustomMailAddresses()) {
            foreach ($this->_d3getUserManagerCustomMailAddressList() as $sMailAdr) {
                $this->setRecipient(trim($sMailAdr), trim($sMailAdr));
            }
        }
    }

    /**
     * @return array
     */
    protected function _d3getUserManagerCustomMailAddressList()
    {
        $aMailAddressList = array();

        foreach (explode(';', $this->_d3getUserManagerCustomRecipientList()) as $sAddress) {
            if (strlen(trim($sAddress))) {
                $aMailAddressList[] = $sAddress;
            }
        }

        return $aMailAddressList;
    }

    /**
     * @return bool
     */
    public function _d3HasUserManagerCustomMailAddresses()
    {
        return $this->_d3hasUserManagerCustomRecipient() && $this->_d3getUserManagerCustomRecipientList();
    }

    /**
     * @param d3usermanager $oUserManager
     * @param oxshop $oShop
     */
    protected function _d3SetUserManagerReplyAddress(d3usermanager $oUserManager, $oShop)
    {
        if (strlen(trim($oUserManager->getValue('sSendMailReplyAddress')))) {
            $this->setFrom(trim($oUserManager->getValue('sSendMailReplyAddress')));
            $this->setReplyTo(
                trim($oUserManager->getValue('sSendMailReplyAddress')),
                $oShop->__get('oxshops__oxname')->getRawValue()
            );
        } else {
            $this->setReplyTo($oShop->getFieldData('oxinfoemail'), $oShop->__get('oxshops__oxname')->getRawValue());
        }
    }
}
