<?php

namespace FiloBlu\Storelocator\Model\Plugin\Rma\Item;

use FiloBlu\Storelocator\Helper\Data;
use Magento\Rma\Model\Rma\Source\Status as StatusAlias;
use Magento\Store\Model\StoreManagerInterface;

use function in_array;

/**
 *
 */
class Status
{
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param Data $helper
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Data $helper,
        StoreManagerInterface $storeManager
    ) {
        $this->helper = $helper;
        $this->storeManager = $storeManager;
    }

    /**
     * @param \Magento\Rma\Model\Item\Status $subject
     * @param $result
     * @return array|mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function afterGetAllowedStatuses(\Magento\Rma\Model\Item\Status $subject, $result)
    {
        $storeId = $this->storeManager->getStore()->getId();

        if (!$this->helper->getReturnToStoreEnabled($storeId)) {
            return $result;
        }

        if (in_array(
            $subject->getStatus(),
            ['authorized', 'received', \FiloBlu\Storelocator\Model\Plugin\Rma\Source\Status::STATE_RECEIVED_IN_STORE]
        )) {
            if (count($result)) {
                $result[\FiloBlu\Storelocator\Model\Plugin\Rma\Source\Status::STATE_RECEIVED_IN_STORE] = __(
                    \FiloBlu\Storelocator\Model\Plugin\Rma\Source\Status::STATE_RECEIVED_IN_STORE_PHRASE
                );
            } else {
                $result = [
                    StatusAlias::STATE_RECEIVED => ucfirst(
                        StatusAlias::STATE_RECEIVED
                    ),
                    StatusAlias::STATE_APPROVED => ucfirst(
                        StatusAlias::STATE_APPROVED
                    ),
                    StatusAlias::STATE_REJECTED => ucfirst(
                        StatusAlias::STATE_REJECTED
                    ),
                    \FiloBlu\Storelocator\Model\Plugin\Rma\Source\Status::STATE_RECEIVED_IN_STORE => \FiloBlu\Storelocator\Model\Plugin\Rma\Source\Status::STATE_RECEIVED_IN_STORE_PHRASE
                ];
            }
        }

        return $result;
    }

    /**
     * @param \Magento\Rma\Model\Item\Status $subject
     * @param $result
     * @param $attribute
     * @return bool|mixed
     */
    public function afterGetAttributeIsEditable(\Magento\Rma\Model\Item\Status $subject, $result, $attribute = null)
    {
        if ($subject->getStatus() == \FiloBlu\Storelocator\Model\Plugin\Rma\Source\Status::STATE_RECEIVED_IN_STORE) {
            return true;
        }

        return $result;
    }
}