<?php

namespace YSquare\GiftCert\Core;

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

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/";
        // Start with an empty list — the Email instance is reused between
        // sendOrderEmailToUser() and sendOrderEmailToOwner() in the same request,
        // so leftover entries from a previous call would otherwise be re-attached.
        $this->_aFiles = [];

        $aCodes = $oOrder->getGiftCertsToDirectlySend();
        $giftcertHandler = oxNew(GiftCertHandler::class);

        DebugLogger::debug('Email::sendOrderEmailToUser', 'enter', [
            'orderId'        => $oOrder ? $oOrder->getId() : null,
            'sess_challenge' => Registry::getSession()->getVariable('sess_challenge'),
            'request_cl'     => Registry::getRequest()->getRequestParameter('cl'),
            'request_fnc'    => Registry::getRequest()->getRequestParameter('fnc'),
            'certCount'      => is_array($aCodes) ? count($aCodes) : 0,
            'callers'        => DebugLogger::callers(10),
        ]);

        $iCount = 1;
        foreach ($aCodes as $sCode => $aValues) {
            $fileToAttach = $giftcertHandler->generateAttachmentPDF($aValues["giftcert"], $aValues["sImage"]);
            if ($fileToAttach === null) {
                DebugLogger::error('Email::sendOrderEmailToUser', 'PDF generation returned null — attachment skipped', [
                    'certNr'  => $sCode,
                    'orderId' => $oOrder ? $oOrder->getId() : null,
                ]);
                $iCount++;
                continue;
            }
            $this->_aFiles[] = $fileToAttach;
            DebugLogger::debug('Email::sendOrderEmailToUser', 'PDF generated for attachment', [
                'certNr'   => $sCode,
                'filename' => $fileToAttach,
                'size'     => file_exists($fileToAttach) ? filesize($fileToAttach) : 0,
            ]);
            $iCount++;
        }

        $ret = parent::sendOrderEmailToUser($oOrder, $sSubject);
        DebugLogger::debug('Email::sendOrderEmailToUser', 'parent::sendOrderEmailToUser returned', [
            'orderId' => $oOrder ? $oOrder->getId() : null,
            'result'  => $ret,
        ]);

        //delete pdf files after email sending
        if($this->_aFiles){
            foreach($this->_aFiles as $sFile){
                $unlinked = @unlink($sFile);
                if (!$unlinked) {
                    DebugLogger::warning('Email::sendOrderEmailToUser', 'pdf cleanup unlink failed', [
                        'filename' => $sFile,
                        'exists'   => file_exists($sFile),
                    ]);
                }
            }
            $this->_aFiles = [];
        }

        return $ret;
    }

    public function sendOrderEmailToOwner($order, $subject = null)
    {
        // Reset attachment list — see comment in sendOrderEmailToUser().
        $this->_aFiles = [];

        $aCodes = $order->getGiftCertsToDirectlySend();
        $giftcertHandler = oxNew(GiftCertHandler::class);

        DebugLogger::debug('Email::sendOrderEmailToOwner', 'enter', [
            'orderId'        => $order ? $order->getId() : null,
            'sess_challenge' => Registry::getSession()->getVariable('sess_challenge'),
            'request_cl'     => Registry::getRequest()->getRequestParameter('cl'),
            'request_fnc'    => Registry::getRequest()->getRequestParameter('fnc'),
            'certCount'      => is_array($aCodes) ? count($aCodes) : 0,
            'callers'        => DebugLogger::callers(10),
        ]);

        $iCount = 1;
        foreach ($aCodes as $sCode => $aValues) {
            $fileToAttach = $giftcertHandler->generateAttachmentPDF($aValues["giftcert"], $aValues["sImage"]);
            if ($fileToAttach === null) {
                DebugLogger::error('Email::sendOrderEmailToOwner', 'PDF generation returned null — attachment skipped', [
                    'certNr'  => $sCode,
                    'orderId' => $order ? $order->getId() : null,
                ]);
                $iCount++;
                continue;
            }
            $this->_aFiles[] = $fileToAttach;
            DebugLogger::debug('Email::sendOrderEmailToOwner', 'PDF generated for attachment', [
                'certNr'   => $sCode,
                'filename' => $fileToAttach,
                'size'     => file_exists($fileToAttach) ? filesize($fileToAttach) : 0,
            ]);
            $iCount++;
        }

        $ret = parent::sendOrderEmailToOwner($order, $subject);
        DebugLogger::debug('Email::sendOrderEmailToOwner', 'parent::sendOrderEmailToOwner returned', [
            'orderId' => $order ? $order->getId() : null,
            'result'  => $ret,
        ]);

        //delete pdf files after email sending
        if($this->_aFiles){
            foreach($this->_aFiles as $sFile){
                $unlinked = @unlink($sFile);
                if (!$unlinked) {
                    DebugLogger::warning('Email::sendOrderEmailToOwner', 'pdf cleanup unlink failed', [
                        'filename' => $sFile,
                        'exists'   => file_exists($sFile),
                    ]);
                }
            }
            $this->_aFiles = [];
        }

        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) {
                DebugLogger::debug('Email::setViewData', 'attaching gift cert PDFs', [
                    'count' => count($this->_aFiles),
                ]);
                foreach ($this->_aFiles as $sFile) {
                    $exists = file_exists($sFile);
                    DebugLogger::debug('Email::setViewData', 'addAttachment', [
                        'filename' => $sFile,
                        'exists'   => $exists,
                        'size'     => $exists ? filesize($sFile) : 0,
                    ]);
                    if (!$exists) {
                        DebugLogger::error('Email::setViewData', 'attachment file missing at addAttachment time', [
                            'filename' => $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() {
        $cronAttachments = array_unique($this->ys_giftcert_attachments);
        DebugLogger::debug('Email::send', 'enter', [
            'recipients'           => method_exists($this, 'getAllRecipientAddresses') ? $this->getAllRecipientAddresses() : null,
            'subject'              => $this->getSubject(),
            'cronAttachmentCount'  => count($cronAttachments),
            'directAttachmentCount' => is_array($this->_aFiles) ? count($this->_aFiles) : 0,
        ]);

        $ys_giftcert_count = 0;
        foreach ($cronAttachments as $sFilename) {
            $ys_giftcert_count++;
            $exists = file_exists($sFilename);
            DebugLogger::debug('Email::send', 'cron addAttachment', [
                'filename' => $sFilename,
                'exists'   => $exists,
                'size'     => $exists ? filesize($sFilename) : 0,
                'asName'   => "Gutschein-".$ys_giftcert_count.".pdf",
            ]);
            if (!$exists) {
                DebugLogger::error('Email::send', 'cron attachment file missing at addAttachment time', [
                    'filename' => $sFilename,
                ]);
            }
            $this->addAttachment($sFilename, "Gutschein-".$ys_giftcert_count.".pdf");
//            print "ADDING: ".$sFilename."\n";
        }

        $ret = parent::send();
        DebugLogger::debug('Email::send', 'parent::send returned', ['result' => (bool) $ret]);
        if (!$ret) {
            DebugLogger::error('Email::send', 'parent::send returned false', [
                'subject' => $this->getSubject(),
            ]);
        }

        return $ret;
    }
}