<?php
/**
 * Copyright © 2016 Filoblu S.r.l. All rights reserved.
 */

namespace FiloBlu\Esb\Controller\Adminhtml\ExternalInvoice;

use Exception;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\View\Result\ForwardFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Store\Model\ScopeInterface;

class PrintAction extends Action
{
    /**
     * Authorization level of a basic admin session
     *
     * @see _isAllowed()
     */
    const ADMIN_RESOURCE = 'Magento_Sales::sales_invoice';

    /**
     * @var FileFactory
     */
    protected $_fileFactory;

    /**
     * @var ForwardFactory
     */
    protected $resultForwardFactory;

    protected $_orderRepository;

    protected $_scopeConfig;

    /**
     * @param Context $context
     * @param FileFactory $fileFactory
     * @param ForwardFactory $resultForwardFactory
     * @param ScopeConfigInterface $scopeConfig
     * @param OrderRepositoryInterface $orderRepository
     */
    public function __construct(
        Context $context,
        FileFactory $fileFactory,
        ForwardFactory $resultForwardFactory,
        ScopeConfigInterface $scopeConfig,
        OrderRepositoryInterface $orderRepository
    ) {
        $this->_fileFactory = $fileFactory;
        $this->_orderRepository = $orderRepository;
        parent::__construct($context);
        $this->resultForwardFactory = $resultForwardFactory;
        $this->_scopeConfig = $scopeConfig;
    }

    /**
     * @return ResponseInterface|void
     * @throws Exception
     */
    public function execute()
    {
        $orderId = $this->getRequest()->getParam('order_id');
        if ($orderId) {
            $order = $this->_orderRepository->get($orderId);
            if ($order) {
                $extensionAttributes = $order->getExtensionAttributes();
                $additionalDataObject = $extensionAttributes->getFbOad();
                $additionalData = [];
                foreach ($additionalDataObject->getCustomAttributes() as $customAttribute) {
                    $additionalData[$customAttribute->getAttributeCode()] = $customAttribute->getValue();
                }

                $externalInvoices = $additionalData["external_invoices"];
                $invoice = current($externalInvoices);
                $documentFolder = $this->_scopeConfig->getValue(
                    'esb/print_documents/document_folder',
                    ScopeInterface::SCOPE_STORE
                );
                return $this->_fileFactory->create(
                    $invoice["document_pdf"],
                    [
                        'type' => "filename",
                        'value' => $documentFolder . "/" . $invoice["document_pdf"]
                    ],
                    DirectoryList::VAR_DIR,
                    'application/pdf'
                );
            }
        } else {
            return $this->resultForwardFactory->create()->forward('noroute');
        }
    }
}
