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

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;

// Because Shopware doesn't allow that Controllers use the new PSR-4 namespace standard
// we need to require the class, because of Enlight_Class::Instance
require_once(__DIR__ . '/../../Controllers/Backend/ViisonDHLOrder.php');

class ViisonShippingCommonOrder extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Backend_ViisonShippingCommonOrder_GetMergedExportDocumentsAction' => 'onFilterGetMergedExportDocumentsAction',
            'Shopware_Controllers_Backend_ViisonShippingCommonOrder_GetMergedLabelsAction' => 'onFilterGetMergedLabelsAction',
        ];
    }

    /**
     * Adds DHL export document PDFs to the pdf list passed by the filter event.
     *
     * @param \Enlight_Event_EventArgs $args
     * @return array
     */
    public function onFilterGetMergedExportDocumentsAction(\Enlight_Event_EventArgs $args)
    {
        $controller = $this->createViisonDHLOrderController($args);
        $trackingCodes = $args->getSubject()->Request()->getParam('trackingCodes');

        return array_merge($args->getReturn(), $controller->getExportDocumentPDFs($trackingCodes));
    }

    /**
     * Adds DHL label PDFs to the pdf list passed by the filter event.
     *
     * @param \Enlight_Event_EventArgs $args
     * @return array
     */
    public function onFilterGetMergedLabelsAction(\Enlight_Event_EventArgs $args)
    {
        $controller = $this->createViisonDHLOrderController($args);
        $trackingCodes = $args->getSubject()->Request()->getParam('trackingCodes');

        return array_merge($args->getReturn(), $controller->getLabelPDFs($trackingCodes));
    }

    /**
     * @param \Enlight_Event_EventArgs $args
     * @return \Enlight_Class
     */
    private function createViisonDHLOrderController(\Enlight_Event_EventArgs $args)
    {
        return $this->get('viison_common.controller_factory_service')->getController(
            'Shopware_Controllers_Backend_ViisonDHLOrder',
            $args->getSubject()->Request(),
            $args->getSubject()->Response()
        );
    }
}
