<?php

namespace Rvsitebuilder\Wysiwyg\Process\SaveSite;

use Lib\Util\RVLog;
use SRIO\ChainOfResponsibility\ChainContext;
use SRIO\ChainOfResponsibility\ChainProcessInterface;

class RemoveScriptTagProcess implements ChainProcessInterface
{
    /**
     * FOR:: Change img tag to script/style only viewmode.
     *
     * @param ChainContext $context
     */
    public function execute(ChainContext $context)
    {
        try {
            foreach ($context as $k => $v) {
                if ('sidebar' == $k) {
                    $context[$k]['left_content_view'] = $this->replace_script($v['left_content_view']);
                    $context[$k]['right_content_view'] = $this->replace_script($v['right_content_view']);
                } elseif ('global_post' == $k && !empty($v)) {
                    $context[$k]['header_content_view'] = $this->replace_script($v['header_content_view']);
                    $context[$k]['footer_content_view'] = $this->replace_script($v['footer_content_view']);
                } elseif (isset($v['content_edit']) && isset($v['content_view'])) {
                    $context[$k]['content_view'] = $this->replace_script($v['content_view']);
                }
            }
            $status = 'success';
            $msg = 'Remove Script tag success';
        } catch (\Exception $e) {
            $errorMsg = 'false:'.$e->getMessage().' at line:'.$e->getLine();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));
            $status = 'error';
            $msg = $errorMsg;
        }
        $context['response']['remove_scripttag']['status'] = $status;
        $context['response']['remove_scripttag']['response_msg'] = $msg;
    }

    public function replace_script($content)
    {
        $pat = '/<img[^>]*type=\"(script|style)\".*?data=\"(.*?)\".*?>/is';

        return preg_replace_callback($pat, function ($match) {
            if ($match[1]) {
                return '<'.$match[1].'>'.$match[2].'</'.$match[1].'>';
            }

            return $match[0];
        }, $content);
    }
}
