<?php

namespace FiloBlu\Rma\Observer;

use FiloBlu\Rma\Helper\ChangeSizeOrder;
use FiloBlu\Rma\Helper\SerializerHelper;
use FiloBlu\Rma\Logger\Logger;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;

use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface;
use function is_array;

/**
 *
 */
class UpdateStatusVerify implements ObserverInterface
{
    /** @var string */
    const ALLOWED_ORDER_STATUS_PATH = 'filoblu_disablerma_section/rma_group/allowed_change_size_order_status';
    /**
     * @var Logger
     */
    private $logger;
    /**
     * @var ChangeSizeOrder
     */
    private $changeSizeOrder;
    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;
    /**
     * @var SerializerHelper
     */
    private $serializerHelper;
    /**
     * @var OrderStatusHistoryRepositoryInterface
     */
    private $orderStatusHistoryRepository;


    /**
     * UpdateStatusVerify constructor.
     * @param Logger $logger
     * @param ChangeSizeOrder $changeSizeOrder
     * @param ScopeConfigInterface $scopeConfig
     * @param SerializerHelper $serializerHelper
     * @param OrderStatusHistoryRepositoryInterface $orderStatusHistoryRepository
     */
    public function __construct(
        Logger $logger,
        ChangeSizeOrder $changeSizeOrder,
        ScopeConfigInterface $scopeConfig,
        SerializerHelper $serializerHelper,
        OrderStatusHistoryRepositoryInterface $orderStatusHistoryRepository
    ) {
        $this->logger = $logger;
        $this->changeSizeOrder = $changeSizeOrder;
        $this->scopeConfig = $scopeConfig;
        $this->serializerHelper = $serializerHelper;
        $this->orderStatusHistoryRepository = $orderStatusHistoryRepository;
    }

    /**
     * @param Observer $observer
     * @throws LocalizedException
     */
    public function execute(Observer $observer)
    {
        /** @var \Magento\Sales\Model\Order $order */
        $order = $observer->getEvent()->getOrder();

        if (!$order || !$order->getId() || !$this->changeSizeOrder->isChangeSizeOrder($order)) {
            return;
        }

        $fromStatus = $order->getOrigData("status");
        $toStatus = $order->getData('status');
        if ($fromStatus == $toStatus) {
            return;
        }

        $allowedStatus = $this->scopeConfig->getValue(self::ALLOWED_ORDER_STATUS_PATH);

        if (!is_array($allowedStatus)) {
            $allowedStatus = $this->serializerHelper->unserialize($allowedStatus);
        }

        $allowed = false;

        foreach ($allowedStatus as $item) {
            if ($item['allowed_status'] == $toStatus) {
                $allowed = true;
                break;
            }
        }
        // LESS BUGGY CODE
        if (!$allowed && $toStatus != 'waiting_for_rma_receiving' && !$this->changeSizeOrder->isValidForUpdateStatus($order)) {
            $incrementId = $order->getIncrementId();
            $this->logger->debug(
                "FiloBlu\Rma\Observer: Order Status for order $incrementId cannot be updated before linked RMA is processed"
            );

            $history = $order->addStatusHistoryComment(
                __('Order cannot change status because linked RMA is still processing')
            );
            $this->orderStatusHistoryRepository->save($history);

            throw new LocalizedException(__('Status update not allowed. RMA not closed yet?'));
        }
    }
}
