<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonPickwareMobile\Classes\SmartyOutputFilter;

use DOMDocument;
use Smarty;
use Smarty_Internal_Template;

/**
 * Injects a barcode into the HTML element with id 'head_right' of a given smarty output.
 */
class BarcodeInjectionOutputFilter
{
    /**
     * @var DOMDocument
     */
    protected $barcode;

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

    /**
     * @param Smarty $templateEngine
     */
    public function registerInSmarty(Smarty $templateEngine)
    {
        $templateEngine->registerFilter(
            'output',
            [
                $this,
                'filter',
            ]
        );
    }

    /**
     * @param string $templateOutput
     * @param Smarty_Internal_Template $template
     * @return string
     */
    public function filter($templateOutput, Smarty_Internal_Template $template)
    {
        // When rendering a document, the document boxes are rendered before the actual document. However, since we only
        // want to inject the barcode in the main document template, we try to detect any document box templates before
        // even trying to find the target element.
        if (mb_strpos($template->template_resource, 'string:') === 0) {
            return $templateOutput;
        }

        // Try to find a 'head_right' element
        $domDocument = new DOMDocument();
        $domDocument->loadHTML(mb_convert_encoding($templateOutput, 'HTML-ENTITIES', 'UTF-8'));
        /** @var \DOMElement $headRightElement */
        $headRightElement = $domDocument->getElementById('head_right');
        if (!$headRightElement) {
            return $templateOutput;
        }

        // Inject the barcode as an SVG
        $xml = $this->barcode->saveXML();
        $barcodeData = base64_encode($xml);
        $barcodeElement = $domDocument->createElement('img');
        $barcodeElement->setAttribute('src', sprintf('data:image/svg+xml;base64,%s', $barcodeData));
        $headRightElement->appendChild($barcodeElement);
        $headRightElement->appendChild($domDocument->createElement('br'));

        return $domDocument->saveHTML();
    }
}
