<?php
namespace FiloBlu\Rma\Block\Sales;

use FiloBlu\Rma\Model\Payment\ChangeSizePay;
use Magento\Framework\View\Element\Template;
use Magento\Framework\DataObject;
use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderPaymentInterface;

/**
 *
 */
class Cashondelivery extends Template
{
    /**
     * @return bool
     */
    public function displayFullSummary()
    {
        return true;
    }

    /**
     * @return $this
     */
    public function initTotals()
    {
        $parent = $this->getParentBlock();
        $source = $parent->getSource();

        $payment = $this->getPayment($source);
        if ($payment && $payment->getMethod() == ChangeSizePay::PAYMENT_CODE) {
            if($source->getBaseMspCodAmount() > 0){
                $fee = new DataObject(
                    [
                        'code' => 'filoblu_rma_msp_cashondelivery',
                        'strong' => false,
                        'value' => $source->getBaseMspCodAmount(),
                        'label' => __('Cash on delivery'),
                    ]
                );
                $parent->addTotalBefore($fee, 'grand_total');
            }
        }

        return $this;
    }

    /**
     * @param $source
     * @return false|float|DataObject|OrderPaymentInterface|mixed|null
     */
    protected function getPayment($source)
    {
        if ($source instanceof InvoiceInterface) {
            return $source->getOrder()->getPayment();
        }

        if ($source instanceof OrderInterface) {
            return $source->getPayment();
        }

        if ($source instanceof CreditmemoInterface) {
            return $source->getOrder()->getPayment();
        }

        return null;
    }
}
