<?php

namespace Autogedal\Helper\Controller;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Controller\AbstractController\OrderViewAuthorizationInterface;
use Magento\Sales\Controller\Order\PrintInvoice;
use Magento\Framework\Filesystem;
use Magento\Framework\Registry;
use Magento\Framework\Controller\Result\RawFactory;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use SmartBill\Integration\Model\ResourceModel\Invoice\CollectionFactory as InvoiceCollectionFactory;

class MagentoInvoicePrintOverride extends PrintInvoice
{
    protected $_filesystem;
    protected $_invoiceCollectionFactory;
    protected $resultRawFactory;
    protected $fileFactory;

    public function __construct(
        Context $context,
        OrderViewAuthorizationInterface $orderAuthorization,
        Registry $registry,
        PageFactory $resultPageFactory,
        Filesystem $filesystem,
        RawFactory $resultRawFactory,
        FileFactory $fileFactory,
        InvoiceCollectionFactory $invoiceCollectionFactory
    )
    {
        $this->_filesystem = $filesystem;
        $this->resultRawFactory      = $resultRawFactory;
        $this->fileFactory           = $fileFactory;
        $this->_invoiceCollectionFactory = $invoiceCollectionFactory;

        parent::__construct($context, $orderAuthorization, $registry, $resultPageFactory);
    }

    public function execute()
    {
        $mediapath = $this->_filesystem->getDirectoryRead(DirectoryList::VAR_DIR)->getAbsolutePath();
        $invoiceId = (int)$this->getRequest()->getParam('invoice_id');

        if ($invoiceId) {
            $invoice = $this->_objectManager->create(
                \Magento\Sales\Api\InvoiceRepositoryInterface::class
            )->get($invoiceId);
            $order = $invoice->getOrder();
        } else {
            $orderId = (int)$this->getRequest()->getParam('order_id');
            $order = $this->_objectManager->create(\Magento\Sales\Model\Order::class)->load($orderId);
        }

        if ($this->orderAuthorization->canView($order)) {
            $invoiceCollectionFactoryResults = $this->_invoiceCollectionFactory->create()->getItemByColumnValue('order_id', $order->getId());
            $documentUrl = null;
            if ($invoiceCollectionFactoryResults != null && $invoiceCollectionFactoryResults->getData('order_id') == $order->getId()) {
                $invoiceFactory = $invoiceCollectionFactoryResults;
                if (null !== $invoiceFactory->getData('smartbill_document_url')) {
                    $documentUrl = $invoiceFactory->getData('smartbill_document_url');
                }
            }

            $documentPath = $mediapath . ltrim($documentUrl, '/');

            $this->fileFactory->create(
                basename($documentUrl),
                file_get_contents($documentPath)
            );
            $resultRaw = $this->resultRawFactory->create();
            return $resultRaw;
        }
    }
}