<?php
declare(strict_types=1);

namespace FiloBlu\Rma\Observer\Sales\Order;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\SalesRule\Model\Rule;
use Psr\Log\LoggerInterface;

class FreeReturnShipping implements ObserverInterface
{
    /**
     * @var Rule
     */
    private $rule;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param Rule $rule
     * @param LoggerInterface $logger
     */
    public function __construct(Rule $rule, LoggerInterface $logger)
    {
        $this->rule = $rule;
        $this->logger = $logger;
    }

    /**
     * This Observer is responsible to check Free Return Shipping flag on Cart Price Rule of order
     * and set to sales_order_item level the free return shipping
     * MNTFOS-419
     * @param Observer $observer
     * @throws LocalizedException
     */
    public function execute(Observer $observer)
    {
        /** @var \Magento\Sales\Model\Order $order */
        $order = $observer->getEvent()->getOrder();
        $ruleIds = $order->getAppliedRuleIds();

        if (!is_array($ruleIds)) {
            $ruleIds = explode(",", $ruleIds);
        }

        foreach ($ruleIds as $ruleId) {
            $appliedRule = $this->rule->load($ruleId);
            if ($appliedRule->getFreeReturnShipping()) {
                $this->setFreeReturnShippingOnOrderItem($order);
            }
        }
    }

    /**
     * Set in sales_order_item, on column free_return_shipping, value to true
     * @param OrderInterface $order
     * @return void
     */
    public function setFreeReturnShippingOnOrderItem(OrderInterface $order)
    {
        try {
            $items = $order->getItems();
            foreach ($items as $item) {
                $item->setFreeReturnShipping(1);
                $item->save();
            }
        } catch (\Exception $e) {
            $errorMessage = 'Error while setting free_return_shipping on item. Error: ' . $e->getMessage();
            $this->logger->error($errorMessage);
        }
    }
}
