<?php

namespace Autogedal\Helper\Model;
use Magento\Sales\Model\Order\Pdf\Config;
use Magento\Sales\Model\Order\Pdf\Invoice;
use SmartBill\Integration\Model\ResourceModel\Invoice\CollectionFactory as InvoiceCollectionFactory;
use Magento\Framework\App\Filesystem\DirectoryList;

class MagentoInvoiceOverride extends Invoice
{
    protected $_filesystem;
    public $invoiceCollectionFactory;
    public function __construct(
        \Magento\Payment\Helper\Data $paymentData,
        \Magento\Framework\Stdlib\StringUtils $string,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Filesystem $filesystem, Config $pdfConfig,
        \Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory,
        \Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Sales\Model\Order\Address\Renderer $addressRenderer,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Store\Model\App\Emulation $appEmulation,
        InvoiceCollectionFactory $invoiceCollectionFactory,
        array $data = []
    )
    {
        $this->_filesystem = $filesystem;
        $this->invoiceCollectionFactory = $invoiceCollectionFactory;
        parent::__construct($paymentData, $string, $scopeConfig, $filesystem, $pdfConfig, $pdfTotalFactory, $pdfItemsFactory, $localeDate, $inlineTranslation, $addressRenderer, $storeManager, $appEmulation, $data);
    }

    public function getPdf($invoices = [])
    {
        $varpath = $this->_filesystem->getDirectoryRead(DirectoryList::VAR_DIR)->getAbsolutePath();

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

        return new \Zend_Pdf($varpath . ltrim($documentUrl, '/'), null, true);
    }
}