<?php

namespace Autogedal\Helper\Model;

use Magento\Framework\Filesystem;
use Magento\Framework\ObjectManagerInterface;
use Mageplaza\EmailAttachments\Helper\Data;
use Mageplaza\EmailAttachments\Model\Mail;
use Mageplaza\EmailAttachments\Model\MailEvent;
use SmartBill\Integration\Model\ResourceModel\Invoice\CollectionFactory as InvoiceCollectionFactory;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Mail\MailMessageInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Creditmemo;
use Magento\Sales\Model\Order\Invoice;
use Magento\Sales\Model\Order\Shipment;
use Magento\Store\Model\Store;
use Laminas\Mail\Message;
use Laminas\Mime\Mime;
use Laminas\Mime\Part;
use Zend_Mail;
use Zend_Mime;
use Zend_Mime_Decode;
use Zend_Pdf;
use Zend_Pdf_Exception;

class MPMailEventOverride extends MailEvent
{
    public $parts = [];
    public $objectManager;
    public $dataHelper;
    public $invoiceCollectionFactory;

    public $mail;

    public function __construct(Mail $mail, Data $dataHelper, Filesystem $filesystem, ObjectManagerInterface $objectManager, InvoiceCollectionFactory $invoiceCollectionFactory, SessionManagerInterface $coreSession)
    {
        $this->mail = $mail;
        $this->dataHelper = $dataHelper;

        $this->invoiceCollectionFactory = $invoiceCollectionFactory;
        parent::__construct($mail, $dataHelper, $filesystem, $objectManager, $coreSession);
    }

    public function dispatch($message)
    {
        $emailType = "invoice";
        $templateVars = $this->mail->getTemplateVars();
        $obj = $templateVars[$emailType];

        $invoiceCollectionFactoryResults = $this->invoiceCollectionFactory->create()->getItemByColumnValue('order_id', $obj->getOrderId());
        $documentUrl = null;
        if ($invoiceCollectionFactoryResults != null && $invoiceCollectionFactoryResults->getData('order_id') == $obj->getOrderId()){
            $invoiceFactory = $invoiceCollectionFactoryResults;
            if (null !== $invoiceFactory->getData('smartbill_document_url')) {
                $documentUrl = $invoiceFactory->getData('smartbill_document_url');
            }
        }

        $this->setPdfAttachment($emailType, $message, $obj);
    }

    private function setPdfAttachment($emailType, $message, $obj, $documentUrl = null)
    {
        if (empty($documentUrl)) {
            $pdfModel = 'Magento\Sales\Model\Order\Pdf\\' . ucfirst($emailType);
            /** @var Zend_Pdf $pdf */
            $pdf = $this->objectManager->create($pdfModel)->getPdf([$obj]);
            $pdfContent = $pdf->render();
        } else {
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $filesystem = $objectManager->get('\Magento\Framework\Filesystem');
            $varPath = $filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR)->getAbsolutePath();
            $pdfContent = file_get_contents($varPath . ltrim($documentUrl, '/'));

        }

        if ($this->dataHelper->versionCompare('2.2.9')) {
            $attachment              = new Part($pdfContent);
            $attachment->type        = 'application/pdf';
            $attachment->encoding    = Zend_Mime::ENCODING_BASE64;
            $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
            $attachment->filename    = $emailType . $obj->getIncrementId() . '.pdf';

            $this->parts[] = $attachment;

            return;
        }

        $message->createAttachment(
            $pdfContent,
            'application/pdf',
            Zend_Mime::DISPOSITION_ATTACHMENT,
            Zend_Mime::ENCODING_BASE64,
            $emailType . $obj->getIncrementId() . '.pdf'
        );
    }
}