<?php
declare(strict_types=1);

namespace FiloBlu\Rma\Plugin;

use FiloBlu\Rma\Model\OrderLocator;
use Magento\Framework\App\RequestInterface;
use Psr\Log\LoggerInterface;

class SetFreeReturnShipping
{
    /**
     * @var OrderLocator
     */
    private $orderLocator;
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param \FiloBlu\Rma\Model\OrderLocator $orderLocator
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(
        OrderLocator     $orderLocator,
        LoggerInterface  $logger
    )
    {
        $this->orderLocator = $orderLocator;
        $this->logger = $logger;
    }

    /**
     * @param $subject
     * @param $result
     * @return float|mixed
     */
    public function afterSimulateEasyReturnShippingCost($subject, $result)
    {
        try {
            if (!$subject->getOrderItemsId()) {
                return $result;
            }

            if (!$this->orderLocator->hasOrder()) {
                $this->orderLocator->load();
            }

            $order = $this->orderLocator->getCurrentOrder();
            $items = $order->getItems();
            $orderItemsId = $subject->getOrderItemsId();

            foreach ($items as $item) {
                if (!array_intersect($orderItemsId, [$item->getItemId(), $item->getParentItemId()])) {
                    continue;
                }
                if ($item->getFreeReturnShipping()) {
                    return 0.0;
                }
            }

            return $result;

        } catch (\Exception $e) {
            $errorMessage = 'Error while checking/setting free_return_shipping on rma. Error: ' . $e->getMessage();
            $this->logger->error($errorMessage);
            return $result;
        }
    }
}
