<?php
declare(strict_types=1);

namespace FiloBlu\Rma\Plugin\Sales\Model;

use FiloBlu\Rma\Model\ResourceModel\ChangeSizeItems\CollectionFactory as ChangeSizeItemsCollectionFactory;
use FiloBlu\Rma\Model\ResourceModel\ChangeSizeItems\Collection as ChangeSizeItemsCollection;
use Magento\Sales\Model\Order\Creditmemo;
use Magento\Sales\Model\Order\Email\Sender\CreditmemoSender;

/**
 * @class CreditMemoSenderManager
 * @package FiloBlu\Rma\Plugin
 */
class CreditMemoSenderManager
{

    /** @var string  */
    const ORDER_CHANGE_SIZE_STATUS = 'change_size';

    /**
     * @var ChangeSizeItemsCollectionFactory
     */
    public $changeSizeItemsCollectionFactory;

    public function __construct(ChangeSizeItemsCollectionFactory $changeSizeItemsCollectionFactory) {
        $this->changeSizeItemsCollectionFactory = $changeSizeItemsCollectionFactory;
    }

    /**
     * @return void
     * @see CreditmemoSender::send
     */
    public function aroundSend(
        CreditmemoSender $subject,
        callable $proceed,
        Creditmemo $creditmemo,
        $forceSyncMode = false
    ) {
        $order = $creditmemo->getOrder();

        /** @var ChangeSizeItemsCollection $collection */
        $collection = $this->changeSizeItemsCollectionFactory->create();
        $collection->addFieldToSelect('item_id')
            ->addFieldToFilter('parent_order_item', $order->getEntityId());

         if ($collection->count()) {
             return;
         }

        return $proceed($creditmemo, $forceSyncMode);
    }
}

