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

namespace FiloBlu\Esb\Controller\Invoice;

use Magento\Framework\App\Filesystem\DirectoryList;

class PrintAction extends \Magento\Framework\App\Action\Action
{

    protected $_scopeConfig;

    /**
     * @var \Magento\Framework\App\Response\Http\FileFactory
     */
    protected $_fileFactory;

    /**
     * @var \Magento\Backend\Model\View\Result\ForwardFactory
     */
    protected $resultForwardFactory;

    protected $_filesystem;


    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Controller\Result\ForwardFactory $resultForwardFactory,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Filesystem $filesystem
    ) {
        $this->_fileFactory = $fileFactory;
        $this->_resultForwardFactory = $resultForwardFactory;
        $this->_scopeConfig = $scopeConfig;
        $this->_filesystem = $filesystem;
        parent::__construct($context);
    }

    public function execute(){

        $document = $this->getRequest()->getParam('document');

        if ($document) {
            $documentFolder = $this->_scopeConfig->getValue(
                'esb/print_documents/document_folder',
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            );

            $file = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR)->getAbsolutePath($documentFolder.$document);

            if(file_exists($file)){
                $this->_fileFactory->create(
                    $document,
                    array(
                        'type'  => "filename",
                        'value' => $documentFolder.$document
                    ),
                    DirectoryList::VAR_DIR,
                    'application/pdf'
                );
            }else{
                $this->_resultForwardFactory->create()->forward('noroute');
            }
        }
    }
}
