<?php
declare(strict_types=1);

namespace FiloBlu\Rma\Plugin;

use FiloBlu\Rma\Helper\OfflinePaymentMethodsHelper;
use Magento\Sales\Api\Data\OrderExtension;
use Magento\Sales\Api\Data\OrderExtensionFactory;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\ResourceModel\Order\Collection;

class AddIbanRequiredFlagToOrder
{
    /**
     * @var OfflinePaymentMethodsHelper
     */
    private $helper;
    /**
     * @var OrderExtensionFactory
     */
    private $orderExtensionFactory;

    /**
     * @param OfflinePaymentMethodsHelper $helper
     * @param OrderExtensionFactory $orderExtensionFactory
     */
    public function __construct(
        OfflinePaymentMethodsHelper $helper,
        OrderExtensionFactory $orderExtensionFactory
    ) {
        $this->helper = $helper;
        $this->orderExtensionFactory = $orderExtensionFactory;
    }

    public function afterGet(OrderRepositoryInterface $subject, OrderInterface $order): OrderInterface
    {
        if (!$this->helper->isIbanOfflinePaymentsEnabled()) {
            return $order;
        }

        $extensionAttributes = $order->getExtensionAttributes();

        /** @var OrderExtension $orderExtension */
        $orderExtension = $extensionAttributes ?: $this->orderExtensionFactory->create();
        $orderExtension->setIbanRequiredForReturn($this->helper->isIbanRequired($order));

        $order->setExtensionAttributes($orderExtension);
        return $order;
    }

    /**
     * @param OrderRepositoryInterface $subject
     * @param Collection $resultOrder
     * @return Collection
     */
    public function afterGetList(
        OrderRepositoryInterface $subject,
        Collection $resultOrder
    ) {
        /** @var  $order */
        foreach ($resultOrder->getItems() as $order) {
            $this->afterGet($subject, $order);
        }
        return $resultOrder;
    }
}
