<?php

namespace YSquare\GiftCert\Core;

use OxidEsales\Eshop\Core\Field;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\EshopCommunity\Internal\Framework\Templating\TemplateRendererBridgeInterface;

class Email extends Email_parent{

//    protected $_sFilePath = "";

    protected $_aFiles = null;

    protected $ys_giftcert_attachments = [];

    /**
     * @param $oOrder
     * @param null $sSubject
     * @return mixed
     */
    public function sendOrderEmailToUser($oOrder, $sSubject = null)
    {
//        $this->_sFilePath = getShopBasePath() . "tmp/";
        $aCodes = $oOrder->getGiftCertsToDirectlySend();
        $giftcertHandler = oxNew(GiftCertHandler::class);

        $iCount = 1;
        foreach ($aCodes as $sCode => $aValues) {
            $fileToAttach = $giftcertHandler->generateAttachmentPDF($aValues["giftcert"], $aValues["sImage"]);
            $this->_aFiles[] = $fileToAttach;
            $iCount++;
        }

        $ret = parent::sendOrderEmailToUser($oOrder, $sSubject);

        //delete pdf files after email sending
        if($this->_aFiles){
            foreach($this->_aFiles as $sFile){
                unlink($sFile);
            }
        }

        return $ret;
    }

    public function sendOrderEmailToOwner($order, $subject = null)
    {
        $aCodes = $order->getGiftCertsToDirectlySend();
        $giftcertHandler = oxNew(GiftCertHandler::class);

        $iCount = 1;
        foreach ($aCodes as $sCode => $aValues) {
            $fileToAttach = $giftcertHandler->generateAttachmentPDF($aValues["giftcert"], $aValues["sImage"]);
            $this->_aFiles[] = $fileToAttach;
            $iCount++;
        }

        $ret = parent::sendOrderEmailToOwner($order, $subject);

        //delete pdf files after email sending
        if($this->_aFiles){
            foreach($this->_aFiles as $sFile){
                unlink($sFile);
            }
        }

        return $ret;
    }


    /**
     * Set view data to email view.
     *
     * @param string $sKey   key value
     * @param object $sValue item value
     */
    public function setViewData($sKey, $sValue)
    {
        $result = parent::setViewData($sKey, $sValue);

        if ($sKey == "order") {
            if ($this->_aFiles) {
                foreach ($this->_aFiles as $sFile) {
                    $this->addAttachment($sFile);
                }
            }
        }

        return $result;
    }


    /**
     *
     * @param $entry
     * @return mixed
     */
    public function sendGiftcertEmailToRecipient($giftcert, $filesToAttach=[], $langId = null, $shopId = null, $purchaserFirstName = "", $purchaserLastName = "") {

        // shop info + lang settings
        $config = Registry::getConfig();
        $config->setShopId($shopId);
        $config->onShopChange();
        $config->reinitialize();
        $oShop = oxNew(\OxidEsales\Eshop\Application\Model\Shop::class);
        if ($shopId !== null) {
            $oShop->setShopId($shopId);
        }
        if ($langId !== null) {
            $oShop->setLanguage($langId);
        }
        if(!$oShop->load($shopId)) {
            $oShop = $this->_getShop();
        }
        $lang = Registry::getLang();
        $lang->setTplLanguage($langId);
        $lang->setBaseLanguage($langId);

        // Attachments
        $this->ys_giftcert_attachments = array_merge($this->ys_giftcert_attachments, $filesToAttach);

        // giftcert info
        $options = json_decode($giftcert->ysgiftcert__ysindividualoptions->rawValue,true);

        //set mail params (from, fromName, smtp )
        $this->_setMailParams( $oShop );

        // create messages
        $bridge = $this->getContainer()->get(TemplateRendererBridgeInterface::class);
        $bridge->setEngine($this->_getSmarty());
        $renderer = $bridge->getTemplateRenderer();

        $this->setViewData('oEmailView', $this);
        $this->setViewData('oViewConf', $this->getViewConfig());
        $this->setViewData('purchaserFirstName', $purchaserFirstName);
        $this->setViewData('purchaserLastName', $purchaserLastName);
        $this->setViewData('message', $options['recipientText']);

        // Process view data array through oxOutput processor
        $this->_processViewArray();

        $this->setSubject(vsprintf(Registry::getLang()->translateString('YS_GIFTCERT_MAIL_SUBJECT_TO_RECIPIENT') , [$purchaserFirstName." ".$purchaserLastName]));
        $this->setBody( $renderer->renderTemplate("email/html/ys_giftcert_to_recipient.tpl", $this->getViewData() ) );
        $this->setAltBody( $renderer->renderTemplate("email/plain/ys_giftcert_to_recipient.tpl", $this->getViewData() ) );

        $this->setRecipient( $options['recipientMail'] );
        $this->setReplyTo( $oShop->oxshops__oxorderemail->value, $oShop->oxshops__oxname->getRawValue() );

        return $this->send();

    }

    /**
     *
     * @param $entry
     * @return mixed
     */
    public function sendGiftcertEmailToPurchaser($giftcert, $filesToAttach=[], $langId = null, $shopId = null) {

        // shop info + lang settings
        $config = Registry::getConfig();
        $config->setShopId($shopId);
        $config->onShopChange();
        $config->reinitialize();
        $oShop = oxNew(\OxidEsales\Eshop\Application\Model\Shop::class);
        if ($shopId !== null) {
            $oShop->setShopId($shopId);
        }
        if ($langId !== null) {
            $oShop->setLanguage($langId);
        }
        if(!$oShop->load($shopId)) {
            $oShop = $this->_getShop();
        }
        $lang = Registry::getLang();
        $lang->setTplLanguage($langId);
        $lang->setBaseLanguage($langId);

        // Attachments
        $this->ys_giftcert_attachments = array_merge($this->ys_giftcert_attachments, $filesToAttach);

        // giftcert info
        $options = json_decode($giftcert->ysgiftcert__ysindividualoptions->rawValue,true);

        //set mail params (from, fromName, smtp )
        $this->_setMailParams( $oShop );

        // create messages
        $bridge = $this->getContainer()->get(TemplateRendererBridgeInterface::class);
        $bridge->setEngine($this->_getSmarty());
        $renderer = $bridge->getTemplateRenderer();

        $this->setViewData('oEmailView', $this);
        $this->setViewData('oViewConf', $this->getViewConfig());

        // Process view data array through oxOutput processor
        $this->_processViewArray();

        $this->setSubject( Registry::getLang()->translateString('YS_GIFTCERT_MAIL_SUBJECT_TO_PURCHASER') );
        $this->setBody( $renderer->renderTemplate("email/html/ys_giftcert_to_purchaser.tpl", $this->getViewData() ) );
        $this->setAltBody( $renderer->renderTemplate("email/plain/ys_giftcert_to_purchaser.tpl", $this->getViewData() ) );

        $this->setRecipient( $options['purchaserMail'] );
        $this->setReplyTo( $oShop->oxshops__oxorderemail->value, $oShop->oxshops__oxname->getRawValue() );

        return $this->send();

    }

    /**
     *
     * @param $entry
     * @return mixed
     */
    public function sendGiftcertEmailToShopOwner($giftcert, $filesToAttach=[], $langId = null, $shopId = null) {

        // shop info + lang settings
//        $config = Registry::getConfig();
//        $config->setShopId($shopId);
        $oShop = oxNew(\OxidEsales\Eshop\Application\Model\Shop::class);
        if ($shopId !== null) {
            $oShop->setShopId($shopId);
        }
        if(!$oShop->load($shopId)) {
            $oShop = $this->_getShop();
        }
//        $lang = Registry::getLang();
//        $lang->setTplLanguage($langId);
//        $lang->setBaseLanguage($langId);


        // Attachments
        $this->ys_giftcert_attachments = array_merge($this->ys_giftcert_attachments, $filesToAttach);

        // giftcert info
        $options = json_decode($giftcert->ysgiftcert__ysindividualoptions->rawValue,true);

        //set mail params (from, fromName, smtp )
        $this->_setMailParams( $oShop );

        // create messages
        $bridge = $this->getContainer()->get(TemplateRendererBridgeInterface::class);
        $bridge->setEngine($this->_getSmarty());
        $renderer = $bridge->getTemplateRenderer();

        $this->setViewData('oEmailView', $this);
        $this->setViewData('oViewConf', $this->getViewConfig());

        // Process view data array through oxOutput processor
        $this->_processViewArray();

        $this->setSubject( Registry::getLang()->translateString('YS_GIFTCERT_MAIL_SUBJECT_TO_SHOPOWNER') );
        $this->setBody( $renderer->renderTemplate("email/html/ys_giftcert_to_purchaser.tpl", $this->getViewData() ) );
        $this->setAltBody( $renderer->renderTemplate("email/plain/ys_giftcert_to_purchaser.tpl", $this->getViewData() ) );

        $this->setRecipient( $oShop->oxshops__oxorderemail->value );
        $this->setReplyTo( $oShop->oxshops__oxorderemail->value, $oShop->oxshops__oxname->getRawValue() );

        return $this->send();

    }

    public function send() {
        $ys_giftcert_count = 0;
        foreach (array_unique($this->ys_giftcert_attachments) as $sFilename) {
            $ys_giftcert_count++;
            $this->addAttachment($sFilename, "Gutschein-".$ys_giftcert_count.".pdf");
//            print "ADDING: ".$sFilename."\n";
        }

        $ret = parent::send();

        return $ret;
    }
}