<?php

namespace FiloBlu\Storelocator\Model\Plugin\Rma;

use FiloBlu\Rma\Model\Rma\Status\HistoryFactory;
use FiloBlu\Rma\Model\RmaEmailManagment;
use FiloBlu\Storelocator\Helper\Data;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class RmaEmailManagement
{
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var HistoryFactory
     */
    protected $historyFactory;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

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

    /**
     * @param RmaEmailManagment $subject
     * @param callable $proceed
     * @param $rmaEntityId
     * @param $status
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function  aroundSendRmaEmail(RmaEmailManagment $subject, callable $proceed, $rmaEntityId = null, $status = null) {

        $storeId = $this->storeManager->getStore()->getId();

        if (!$this->helper->getReturnToStoreEnabled($storeId)) {
            return $proceed($rmaEntityId, $status);
        }

        if ($this->helper->getReturnToStoreEnabled($storeId) && $this->helper->getUseStandardRmaMailFlow($storeId)) {
            return $proceed($rmaEntityId, $status);
        }

        if ($status !== 'received') {
            return $proceed($rmaEntityId, $status);
        }

        // TODO: wrong logic.
        $path = RmaEmailManagment::XML_PATH_STATE_PREFIX . "_$status";
        if($status == 'authorized'){
            $path = RmaEmailManagment::XML_PATH_STATE_PREFIX . '_auth';
        }

        if($status == 'pending'){
            $path = RmaEmailManagment::XML_PATH_STATE_PREFIX ;
        }

        $statusHistory = $this->historyFactory->create();
        $statusHistory->setRmaEntityId($rmaEntityId);

        return $statusHistory->sendRmaEmail($path);
    }
}