<?php
/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 11/11/19
 * Time: 15.24
 */

namespace FiloBlu\Rma\Model;

use Exception;
use FiloBlu\Rma\Helper\RmaHelper;
use FiloBlu\Rma\Model\Rma\Status\HistoryFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Rma\Api\Data\RmaInterface;
use Magento\Rma\Model\Rma;
use Magento\Store\Model\ScopeInterface;
use Psr\Log\LoggerInterface;

/**
 *
 */
class RmaEmailManagment
{
    /** @var string */
    const XML_PATH_STATE_PREFIX = 'sales_email/magento_rma';


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

    /**
     * @var HistoryFactory
     */
    protected $historyFactory;

    /**
     * @var LoggerInterface
     */
    protected $logger;
    /**
     * @var \FiloBlu\Rma\Helper\RmaHelper
     */
    protected $rmaHelper;
    /**
     * @var \Magento\Framework\Serialize\SerializerInterface
     */
    protected $serializer;

    protected $wrongOrDamagedItems = [];

    /**
     * RmaEmailManagment constructor.
     * @param ScopeConfigInterface $scopeConfig
     * @param HistoryFactory $historyFactory
     * @param LoggerInterface $logger
     * @param RmaHelper $rmaHelper
     * @param SerializerInterface $serializer
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        HistoryFactory $historyFactory,
        LoggerInterface $logger,
        RmaHelper $rmaHelper,
        SerializerInterface $serializer
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->historyFactory = $historyFactory;
        $this->logger = $logger;
        $this->rmaHelper = $rmaHelper;
        $this->serializer = $serializer;
    }

    /** TODO: Wrong name, logic duplicated in \FiloBlu\Rma\Model\RmaEmailManagment::sendRmaEmail
     * @param \Magento\Rma\Model\Rma $rma
     * @return \FiloBlu\Rma\Model\Rma\Status\History|null
     */
    public function checkIfSendRmaEmail(Rma $rma)
    {
        $storeId = $rma->getStoreId();
        $suffix = $status = $rma->getStatus();

        if ($status === 'pending') {
            return null;
        }

        if ($status === 'authorized') {

            $suffix = 'auth';

            if (!$this->rmaHelper->mustSendRmaAuthEmail()) {
                return null;
            }
        }

        if (in_array($status,  ['closed', 'rejected_on_item'])) {
            $suffix = 'closed';
        }

        $path = self::XML_PATH_STATE_PREFIX . "_$suffix/enabled";
        $sendEmail = $this->scopeConfig->isSetFlag($path, ScopeInterface::SCOPE_STORE, $storeId);

        if (!$this->rmaHelper->isRmaStatusAllowedToSendEmail($rma)) {
            $sendEmail = false;
        }

        if ($sendEmail) {
            return $this->sendRmaEmail($rma->getEntityId(), $status);
        }

        return null;
    }

    /**
     * @param $rmaEntityId
     * @param $status
     * @return null|\FiloBlu\Rma\Model\Rma\Status\History
     */
    public function sendRmaEmail($rmaEntityId, $status)
    {
        try {
            $path = self::XML_PATH_STATE_PREFIX . "_$status";
            if ($status === 'authorized') {
                $path = self::XML_PATH_STATE_PREFIX . '_auth';
            }

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

            if (in_array($status ,['closed', 'rejected_on_item'])) {
                $path = self::XML_PATH_STATE_PREFIX . '_closed';
            }

            /** @var \FiloBlu\Rma\Model\Rma\Status\History $statusHistory */
            $statusHistory = $this->historyFactory->create();
            $statusHistory->setRmaEntityId($rmaEntityId);
            return $statusHistory->sendRmaEmail($path);
        } catch (Exception $e) {
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
        }

        return null;
    }

    public function getWrongOrDamagedRmaItems(Rma $rma)
    {
        $reasons = $this->rmaHelper->getWrongOrDamageRmaItemsMapping();

        foreach ($rma->getItems() ?? [] as $rmaItemId => $rmaItem) {
            if (array_key_exists($rmaItem->getReason(), $reasons)) {
                $reason = $reasons[$rmaItem->getReason()];
                $this->wrongOrDamagedItems[$reason][$rmaItem->getEntityId()] = $rmaItem;
            }
        }

        return count($this->wrongOrDamagedItems);
    }

    /**
     * @param \Magento\Rma\Model\Rma $rma
     * @return bool
     */
    public function sendWrongOrDamagedRmaEmail(Rma $rma)
    {
        if ($rma->getStatus() != 'pending') {
            return false;
        }

        if (!$this->getWrongOrDamagedRmaItems($rma)) {
            return false;
        }

        if (array_key_exists('damaged_item', $this->wrongOrDamagedItems)) {
            $path = "sales_email/filoblu_extrma_damaged_item_email";

            $this->sendEmail($rma, $path, 'damaged_item' );
        }

        if (array_key_exists('wrong_item', $this->wrongOrDamagedItems)) {
            $path = "sales_email/filoblu_extrma_wrong_item_email";

            $this->sendEmail($rma, $path, 'wrong_item' );
        }

        return true;
    }

    /**
     * @param $rma
     * @param $path
     * @param $type
     * @return void
     */
    protected function sendEmail($rma, $path, $type)
    {
        /** @var \FiloBlu\Rma\Model\Rma\Status\History $statusHistory */
        $statusHistory = $this->historyFactory->create();
        $statusHistory->setRmaEntityId($rma->getEntityId());
        $statusHistory->sendWrongOrDamagedItemsEmail($path, $this->wrongOrDamagedItems[$type]);
    }
}
