<?php

namespace FiloBlu\Rma\Block\Adminhtml\Order\Creditmemo\Create;

use FiloBlu\Rma\Helper\RefundParentOrderHelper;

class Items extends \Magento\Sales\Block\Adminhtml\Order\Creditmemo\Create\Items
{
    /**
     * @var RefundParentOrderHelper
     */
    private $refundHelper;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
        \Magento\CatalogInventory\Api\StockConfigurationInterface $stockConfiguration,
        \Magento\Framework\Registry $registry,
        \Magento\Sales\Helper\Data $salesData,
        RefundParentOrderHelper $refundHelper,
        array $data = []
    ) {
        parent::__construct($context, $stockRegistry, $stockConfiguration, $registry, $salesData, $data);
        $this->refundHelper = $refundHelper;
    }

    protected function _prepareLayout()
    {
        $order = $this->getOrder();
        $payment = $order->getPayment();
        $refundParentOrder = false;
        if ($payment->getMethod() == 'changesizepay') {
            $parentPayment = $this->refundHelper->getParentOrderPayment($payment);
            if ($this->refundHelper->isOnlinePaymentRefundForParentEnabled() && $this->refundHelper->isOrderAllowedToRefund($payment, $parentPayment)) {
                $refundParentOrder = true;
            }
        }

        if ($refundParentOrder) {
            $onclick = "submitAndReloadArea($('creditmemo_item_container'),'" . $this->getUpdateUrl() . "')";
            $this->addChild(
                'update_button',
                \Magento\Backend\Block\Widget\Button::class,
                ['label' => __('Update Qty\'s'), 'class' => 'update-button', 'onclick' => $onclick]
            );

            $this->addChild(
                'submit_button',
                \Magento\Backend\Block\Widget\Button::class,
                [
                    'label' => __('Refund'),
                    'class' => 'save submit-button refund primary',
                    'onclick' => 'disableElements(\'submit-button\');submitCreditMemo()'
                ]
            );

            $this->addChild(
                'submit_offline',
                \Magento\Backend\Block\Widget\Button::class,
                [
                    'label' => __('Refund Offline'),
                    'class' => 'save submit-button primary',
                    'onclick' => 'disableElements(\'submit-button\');submitCreditMemoOffline()'
                ]
            );

            return $this;
        }
        else {
            return parent::_prepareLayout();
        }
    }
}
