<?php
/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 19/04/19
 * Time: 8.13
 */

namespace FiloBlu\Rma\Plugin;

use Magento\Framework\App\RequestInterface;
use Magento\Framework\Message\ManagerInterface;
use Magento\Rma\Controller\Returns\Create;

/**
 *
 */
class ShowCustomErrorMessageForRma
{
    /**
     * @var ManagerInterface
     */
    protected $messageManager;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * ShowCustomErrorMessageForRma constructor.
     * @param ManagerInterface $messageManager
     * @param RequestInterface $request
     */
    public function __construct(
        ManagerInterface $messageManager,
        RequestInterface $request
    ) {
        $this->messageManager = $messageManager;
        $this->request = $request;
    }

    /**
     * @param Create $subject
     */
    public function afterExecute(Create $subject)
    {
        $content = $subject->getResponse()->getContent();

        $personalizedItems = $this->request->getParam('personalizedItems');

        // Remove personalized items from select if any
        if (isset($personalizedItems) && count($personalizedItems) > 0) {
            foreach ($personalizedItems as $item) {
                $strToSearch = "<option value=\"$item\" id=\"item:order_item_id<%- data._index_ %>_$item\"";
                $start = stripos($content, $strToSearch);
                $end = stripos($content, '</option>', $start);

                if ($start && $end) {
                    $length = $end - $start + strlen('</option>');
                    $option = substr($content, $start, $length);
                    $content = str_replace($option, '', $content);
                }
            }
            $subject->getResponse()->setContent($content);
            $this->messageManager->addNoticeMessage(
                'Personalized items was been removed from product list as described in the returns policy'
            );
        }

        // Check if it is a rma personalized order request
        $isPersonalized = $this->request->getParam('isPersonalized') ?? 0;
        // Show error from plugin if any
        $pluginErrorMsg = $this->request->getParam('errorMessageFromPlugin');
        if (isset($pluginErrorMsg)) {
            $this->messageManager->addErrorMessage($this->request->getParam('errorMessageFromPlugin'));
        }
        if ($isPersonalized) {
            // Show custom error message
            $this->messageManager->addErrorMessage(
                'Rma not applicable on personalized orders. Try to remove personalized order from yuor RMA request.'
            );
        }
    }

}
