<?php

namespace FiloBlu\Rma\Plugin\Model\Rma\Status;

use FiloBlu\Rma\Helper\RmaHelper;
use Magento\Sales\Api\OrderRepositoryInterface;

/**
 *
 */
class History
{
    /**
     * @var RmaHelper
     */
    protected $rmaHelper;

    /**
     * History constructor.
     * @param RmaHelper $rmaHelper
     */
    public function __construct(RmaHelper $rmaHelper) {
        $this->rmaHelper = $rmaHelper;
    }

    /**
     * @param \Magento\Rma\Model\Rma\Status\History $subject
     * @param callable $proceed
     * @return \Magento\Rma\Model\Rma\Status\History
     */
    public function aroundSendNewRmaEmail(\Magento\Rma\Model\Rma\Status\History $subject, callable $proceed)
    {
        if (!$this->rmaHelper->isRmaStatusAllowedToSendEmail($subject->getRma())) {
            return $subject;
        }

        if (!$this->rmaHelper->mustSendRmaAuthEmail()) {
            return $subject;
        }

        $order = $subject->getRma()->getOrder();
        if (!$order->getId()) {
            return $subject;
        }
        $itemToShip = false;
        $itemsOrdered = $order->getItems();
        foreach ($itemsOrdered as $item) {
            if ($item->getPrice() > 0) {
                if ($item->getQtyInvoiced() - $item->getQtyShipped() > 0) {
                    $itemToShip = true;
                    break;
                }
            }
        }
        if ($itemToShip) {
            return $subject;
        }
        return $proceed();
    }

    /**
     * @param $subject
     * @param callable $proceed
     * @return false
     */
    public function aroundSendAuthorizeEmail($subject, callable $proceed)
    {
        if ($subject->getRma()->getStatus() === 'closed') {
            return false;
        }

        return $proceed();
    }
}
