<?php

namespace FiloBlu\Rma\Plugin\Helper;

use Adyen\Payment\Helper\Creditmemo;
use Adyen\Payment\Model\ResourceModel\Order\Payment as OrderPaymentResourceModel;
use FiloBlu\Rma\Helper\RefundParentOrderHelper;
use FiloBlu\Rma\Model\Payment\ChangeSizePay;
use Magento\Framework\App\ObjectManager;
use Magento\Sales\Model\Order\Payment;

class RmaHelperCreditmemoProcessor
{
    /**
     * @var OrderPaymentResourceModel|null
     */
    protected $orderPaymentResourceModel = null;

    /**
     * @var RefundParentOrderHelper
     */
    protected $refundOrderHelper;

    /**
     * @param OrderPaymentResourceModel $orderPaymentResourceModel
     * @param RefundParentOrderHelper $refundOrderHelper
     */
    public function __construct(
        RefundParentOrderHelper   $refundOrderHelper
    )
    {
        if (class_exists(OrderPaymentResourceModel::class)) {
            $this->orderPaymentResourceModel = ObjectManager::getInstance()->get(OrderPaymentResourceModel::class);

        }
        $this->refundOrderHelper = $refundOrderHelper;
    }

    /**
     * @param Creditmemo $creditmemo
     * @param Payment $payment
     * @param string $pspReference
     * @param string $originalReference
     * @param float $refundAmount
     * @return array|null
     */
    public function beforeCreateAdyenCreditMemo(
        Creditmemo $creditmemo,
        Payment    $payment,
        string     $pspReference,
        string     $originalReference,
        float      $refundAmount
    )
    {

        if (!class_exists(OrderPaymentResourceModel::class)) {
            return [$payment, $pspReference, $originalReference, $refundAmount];
        }

        if ($payment->getMethod() == ChangeSizePay::PAYMENT_CODE && $this->refundOrderHelper->isOnlinePaymentRefundForParentEnabled()) {
            $adyenOrderPayment = $this->orderPaymentResourceModel->getOrderPaymentDetails($originalReference, $payment->getEntityId());

            if (is_null($adyenOrderPayment)) {
                $parentOrderPayment = $this->refundOrderHelper->getParentOrderPayment($payment);
                if(!is_null($parentOrderPayment) && $this->refundOrderHelper->isOrderAllowedToRefund($payment, $parentOrderPayment))
                {
                    return [$parentOrderPayment, $pspReference, $originalReference, $refundAmount];
                }
            }
        }

        return null;
    }
}
