<?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\Subscribers\Components;

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;
use Shopware\Plugins\ViisonPickwareMobile\Classes\ShippingProvider\ShippingProvider as PickwareMobileShippingProvider;
use Shopware\Plugins\ViisonPickwareMobile\Classes\SmartyOutputFilter\BarcodeInjectionOutputFilter;
use Zend\Barcode\Barcode;

class DocumentSubscriber extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Components_Document::render::before' => 'onBeforeRender',
        ];
    }

    /**
     * Injects a barcode into any documents of type 'invoice' (ID 1) and 'delivery note' (ID 2) by registering a
     * resective Smarty output filter.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onBeforeRender(\Enlight_Hook_HookArgs $args)
    {
        /** @var \Shopware_Components_Document $subject */
        $subject = $args->getSubject();

        $reflectionObject = new \ReflectionObject($subject);
        $documentIdProperty = $reflectionObject->getProperty('_typID');
        $documentIdProperty->setAccessible(true);
        $documentId = $documentIdProperty->getValue($subject);

        if (in_array($documentId, [1, 2])) {
            $barcode = $this->createBarcode($subject->_order->order->id);
            $outputFilter = new BarcodeInjectionOutputFilter($barcode);
            $outputFilter->registerInSmarty($subject->_template);
        }
    }

    /**
     * Tries to find a shipping provider for the order with the given `$orderId` and, if found, creates a new action
     * barcode, which contains the 'create shipping label' action (code 2). If the shipping provider is the dummy
     * provider of this plugin, the 'dispatch' action (code 1) is used instead. Finally the barcode is rendered to SVG
     * and returned.
     *
     * @param int $orderId
     * @return \DOMDocument
     */
    private function createBarcode($orderId)
    {
        // Define barcode action (2 = create shipping label)
        $action = '2';

        // Try to get the shipping provider for the order
        $shippingProvider = $this->get('viison_pickware_mobile.shipping_provider_repository')->findProviderForOrderWithId($orderId);
        if ($shippingProvider && $shippingProvider instanceof PickwareMobileShippingProvider) {
            // Use the 'dispatch wihtout shipping provider' (code 6) action for orders, whose shipping is provided by
            // the Pickware Mobile plugin
            $action = '6';
        }

        // Draw a new barcode image using the Zend_Barcode class of the custom Library
        $config = new \Zend_Config([
            'barcode' => 'code128',
            'barcodeParams' => [
                'text' => ('^' . $action . $orderId),
                'barHeight' => 20,
                'withQuietZones' => false,
                'drawText' => false,
            ],
            'renderer' => 'svg',
        ]);
        $barcodeImage = Barcode::factory($config)->draw();

        return $barcodeImage;
    }
}
