<?php

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

namespace FiloBlu\Esb\Plugin\PrintDocument;

use Magento\Backend\Block\Widget\Button\ButtonList;
use Magento\Backend\Block\Widget\Button\Toolbar;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\View\Element\AbstractBlock;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Block\Adminhtml\Order\View;
use Magento\Store\Model\ScopeInterface;


/**
 * Plugin that adds Print Document button.
 */
class Plugin
{

    /**
     * @var AbstractBlock
     */
    protected $_context;

    /**
     * @var OrderRepositoryInterface
     */
    protected $_orderRepository;

    /**
     * @var ScopeConfigInterface
     */
    protected $_scopeConfig;

    /**
     * @param OrderRepositoryInterface $orderRepository
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        ScopeConfigInterface $scopeConfig
    )
    {
        $this->_orderRepository = $orderRepository;
        $this->_scopeConfig = $scopeConfig;
    }

    /**
     * Add Print Document Button
     *
     * @param Toolbar $subject
     * @param AbstractBlock $context
     * @param ButtonList $buttonList
     * @return void
     */
    public function beforePushButtons(
        Toolbar $subject,
        AbstractBlock $context,
        ButtonList $buttonList
    )
    {
        $this->_context = $context;
        if ($context instanceof View) {
            $order = $this->_orderRepository->get($this->_context->getRequest()->getParam('order_id'));
            $invoices = $order->getInvoiceCollection();
            if($order->getIsVirtual()){
                $shipping_country = ($order->getBillingAddress()) ? $order->getBillingAddress()->getCountryId() : 'none';
            }else{
                $shipping_country = ($order->getShippingAddress()) ? $order->getShippingAddress()->getCountryId() : 'none';
            }
            $enabled_countries = explode(',', $this->_scopeConfig->getValue(
                'esb/print_documents/enabled_countries',
                ScopeInterface::SCOPE_STORE,
                $order->getStoreId()
            ));
            if (count($invoices) > 0 && in_array($shipping_country, $enabled_countries, true)) {
                $invoice_id = $invoices->getFirstItem()->getId();
                $buttonList->add(
                    'print_documents',
                    [
                        'label' => __('Print Documents'),
                        'class' => 'primary',
                        'onclick' => 'setLocation("' . $this->_context->getUrl('esb/externalInvoice/print', ['order_id' => $order->getId(), 'redirect_path' => 'order']) . '")',
                    ]
                );
            }
        }

    }
}
