<?php

namespace FiloBlu\Esb\Plugin\Magento\Sales\Model\ResourceModel\Order\Handler;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Order\Handler\State;
use Magento\Store\Model\ScopeInterface;

class StatePlugin
{
    const XML_ESB_GIFT_CARD_PROCESSING_STATUS = 'esb/gift_card_setting/gift_card_processing_status';
    const ORDER_INVOICED = 'invoiced';

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var SessionManagerInterface
     */
    private $sessionManager;

    public function __construct(
        ScopeConfigInterface $scopeConfig,
        SessionManagerInterface $sessionManager
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->sessionManager = $sessionManager;
    }

    /**
     * @return bool
     */
    public function setGiftCardProcessingStatusAfterInvoiceEnable()
    {
        return $this->scopeConfig->isSetFlag(self::XML_ESB_GIFT_CARD_PROCESSING_STATUS,ScopeInterface::SCOPE_STORE);
    }

    public function beforeCheck(State $subject, Order $order)
    {
        if (!$this->setGiftCardProcessingStatusAfterInvoiceEnable()) {
            return [$order];
        }

        if ($order->getIsNotVirtual()) {
            return [$order];
        }

        if ($order->canShip()) {
            return [$order];
        }

        $this->sessionManager->setPreviousOrderStatus($order->getStatus());
        $this->sessionManager->setPreviousOrderState($order->getState());

        return [$order];
    }

    public function afterCheck(State $state, $result, Order $order){
        if (!$this->setGiftCardProcessingStatusAfterInvoiceEnable()) {
            return $result;
        }

        if ($order->getIsNotVirtual()) {
            return $result;
        }

        if (!$order->canShip()) {
            $previousOrderStatus = $this->sessionManager->getPreviousOrderStatus();
            $previousOrderState = $this->sessionManager->getPreviousOrderState();
            $state = $order->getState();
            $status = $order->getStatus();

            if ($status == Order::STATE_COMPLETE && $state == Order::STATE_COMPLETE) {
                if ($previousOrderStatus != $status && $previousOrderStatus != self::ORDER_INVOICED) {
                    if ($previousOrderStatus == Order::STATE_CLOSED) {
                        if ($previousOrderState != Order::STATE_CLOSED) {
                            $previousOrderState = Order::STATE_CLOSED;
                        }
                    }
                    $order->setState($previousOrderState)
                        ->setStatus($previousOrderStatus);
                }
            }

            $this->sessionManager->unsPreviousOrderStatus();
            $this->sessionManager->unsPreviousOrderState();
        }

        return $result;
    }
}
