<?php
declare(strict_types=1);

namespace FiloBlu\Rma\Plugin\Sales\Controller\Adminhtml\Order\Creditmemo;

use Magento\Framework\App\Config\ScopeConfigInterface;

/**
 * @class Save
 * @package FiloBlu\Rma\Plugin
 */
class Save
{

    /** @var string  */
    const XML_PATH_CREDITMEMO_EMAIL_ENABLED = 'sales_email/creditmemo/enabled';
    const XML_PATH_CREDITMEMO_EMAIL_FORCE_SENDING = 'sales_email/creditmemo/force_sending';

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

    /**
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(ScopeConfigInterface $scopeConfig) {
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * This plugin forces the email sending if the configuration is enabled,
     * this allows the Netsuite Credit Memos to be notified to the customer
     *
     * @return void
     * @see \Magento\Sales\Controller\Adminhtml\Order\Creditmemo\Save::execute
     */
    public function beforeExecute(\Magento\Sales\Controller\Adminhtml\Order\Creditmemo\Save $subject)
    {
        $data = $subject->getRequest()->getPost('creditmemo');
        if ($data === null) {
            return;
        }

        if (!$this->isCreditMemoEmailEnabled()) {
            return;
        }

        if (!$this->isCreditMemoEmailForceSendingActive()) {
            return;
        }

        $data['send_email'] = 1;
        $subject->getRequest()->setPostValue('creditmemo', $data);
    }

    /**
     * @return bool
     */
    public function isCreditMemoEmailEnabled()
    {
        return (bool) $this->scopeConfig->getValue(self::XML_PATH_CREDITMEMO_EMAIL_ENABLED) ?? false;
    }

    /**
     * @return bool
     */
    public function isCreditMemoEmailForceSendingActive()
    {
        return (bool) $this->scopeConfig->getValue(self::XML_PATH_CREDITMEMO_EMAIL_FORCE_SENDING) ?? false;
    }
}

