<?php

namespace FiloBlu\Rma\Plugin;

use FiloBlu\Rma\Model\Payment\ChangeSizePay;
use Magento\Sales\Api\Data\OrderExtension;
use Magento\Sales\Api\Data\OrderExtensionFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;

/**
 *
 */
class OrderGet
{
    /**
     * @var OrderExtensionFactory
     */
    private $orderExtensionFactory;

    /**
     * OrderGet constructor.
     * @param OrderExtensionFactory $orderExtensionFactory
     */
    public function __construct(OrderExtensionFactory $orderExtensionFactory)
    {
        $this->orderExtensionFactory = $orderExtensionFactory;
    }

    /**
     * @param OrderRepositoryInterface $subject
     * @param OrderInterface $order
     * @return OrderInterface
     */
    public function afterGet(OrderRepositoryInterface $subject, OrderInterface $order)
    {
        $extensionAttributes = $order->getExtensionAttributes();

        if ($extensionAttributes && method_exists(
            $extensionAttributes,
            'getPaymentFeeAmount'
        ) && $extensionAttributes->getPaymentFeeAmount()) {
            return $order;
        }

        if (!$order->getPayment()) {
            return $order;
        }

        if ((string)$order->getPayment()->getMethod() === ChangeSizePay::PAYMENT_CODE) {
            /** @var OrderExtension $orderExtension */
            $orderExtension = $extensionAttributes ?: $this->orderExtensionFactory->create();

            if ($this->exists($orderExtension, ['setPaymentFeeAmount']) && $this->exists($order, ['getMspCodAmount', 'getMspCodTaxAmount'])) {
                $orderExtension->setPaymentFeeAmount((float)$order->getMspCodAmount() - (float)$order->getMspCodTaxAmount());
            }

            if ($this->exists($orderExtension, ['setBasePaymentFeeAmount']) && $this->exists($order, ['getBaseMspCodAmount', 'getBaseMspCodTaxAmount'])) {
                $orderExtension->setBasePaymentFeeAmount((float)$order->getBaseMspCodAmount() - (float)$order->getBaseMspCodTaxAmount());
            }

            if ($this->exists($orderExtension, ['setPaymentTaxAmount']) && $this->exists($order, ['getMspCodTaxAmount'])) {
                $orderExtension->setPaymentTaxAmount((float)$order->getMspCodTaxAmount());
            }

            if ($this->exists($orderExtension, ['setBasePaymentTaxAmount']) && $this->exists($order, ['getBaseMspCodTaxAmount'])) {
                $orderExtension->setBasePaymentTaxAmount((float)$order->getBaseMspCodTaxAmount());
            }
            $order->setExtensionAttributes($orderExtension);
        }
        return $order;
    }

    /**
     * @param $subject
     * @param $methods
     * @return bool
     */
    public function exists($subject, $methods)
    {
        foreach ($methods as $method) {
            if (!method_exists($subject, $method)) {
                return false;
            }
        }
        return true;
    }
}
