<?php

/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 21/04/20
 * Time: 11.57
 */

namespace FiloBlu\Rma\Handlers;

use Exception;
use Magento\Rma\Api\RmaRepositoryInterface;
use Magento\Rma\Model\Rma;
use Magento\Sales\Model\OrderFactory;
use Psr\Log\LoggerInterface;
use Throwable;

/**
 *
 */
class CancelChangeSizeOrderHandler
{
    /**
     * @var RmaRepositoryInterface
     */
    private $rmaRepository;

    /**
     * @var OrderFactory
     */
    private $orderFactory;

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

    /**
     * CancelChangeSizeOrderHandler constructor.
     * @param RmaRepositoryInterface $rmaRepository
     * @param OrderFactory $orderFactory
     * @param LoggerInterface $logger
     */
    public function __construct(
        RmaRepositoryInterface $rmaRepository,
        OrderFactory $orderFactory,
        LoggerInterface $logger
    ) {
        $this->rmaRepository = $rmaRepository;
        $this->orderFactory = $orderFactory;
        $this->logger = $logger;
    }


    /**
     * @param Rma $subject
     * @param $result
     * @return mixed
     */
    public function cancelChangeSizeOrder(Rma $subject, $result)
    {
        try {
            $changeSizeOrdersCount = 0;

            $rma = $this->rmaRepository->get($subject->getEntityId());
            $rma->setStatus($result->getStatus());
            foreach ($rma->getItems() as $rmaItem) {
                $attributes = $rmaItem->getExtensionAttributes();
                if ($attributes === null) {
                    continue;
                }

                if (!in_array($rma->getStatus(), ['closed', 'rejected_on_item'])) {
                    continue;
                }

                $changeSizeOrderIncrementId = $rmaItem->getExtensionAttributes()->getChangeSizeOrderIncrementId();

                if (empty($changeSizeOrderIncrementId)) {
                    continue;
                }


                $changeSizeOrder = $this->orderFactory->create()->loadByIncrementId($changeSizeOrderIncrementId);

                if ($changeSizeOrder->getStatus() == 'canceled') {
                    continue;
                }

                $changeSizeOrder->setStatus('canceled')->setState('canceled');
                $changeSizeOrder->save();

                $changeSizeOrdersCount++;

            }

            $result->setData('change_size_orders_count', $changeSizeOrdersCount);

            return $result;
        } catch (Exception $exception) {
            $this->logger->critical($exception->getMessage(), ['exception' => $exception]);
            return $result;
        } catch (Throwable $throwable) {
            $this->logger->critical($throwable->getMessage(), ['exception' => $throwable]);
            return $result;
        }
    }
}
