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

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\AbstractBaseSubscriber;
use Shopware\Plugins\ViisonCommon\Classes\Util\Document as DocumentUtil;
use Shopware\Plugins\ViisonSetArticles\Components\DocumentManipulationService;
use Shopware\Plugins\ViisonSetArticles\Components\PluginConfigService;
use Shopware_Components_Document;

class DocumentSubscriber extends AbstractBaseSubscriber
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Components_Document::assignValues::after' => [
                'onAfterAssignValues',
                999,
            ],
        ];
    }

    /**
     * Manipulates the template variables (order positions) of a document before it is created.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onAfterAssignValues(\Enlight_Hook_HookArgs $args)
    {
        /** @var Shopware_Components_Document $documentComponent */
        $documentComponent = $args->getSubject();
        /** @var DocumentManipulationService $documentManipulationService */
        $documentManipulationService = $this->get('viison_set_articles.document_manipulation_service');

        // Add set article attributes to order positions in any case
        $pages = $documentComponent->_view->tpl_vars['Pages']->value;
        $pages = $documentManipulationService->addSetArticleAttributes($pages);
        $args->getSubject()->_view->assign('Pages', $pages);

        /** @var PluginConfigService $pluginConfigService */
        $pluginConfigService = $this->get('viison_set_articles.plugin_config');
        $subArticleDisplayConfiguration = $pluginConfigService->getDisplaySubArticlesOnDocuments();

        // If sub articles are always shown, do no further manipulation.
        if ($subArticleDisplayConfiguration === PluginConfigService::ALWAYS_SHOW_SUB_ARTICLES_ON_DOCUMENTS) {
            return;
        }

        $documentTypeId = DocumentUtil::getDocumentTypeId($documentComponent);

        // If this document is a pick list, return early, since sub articles are always shown on pick lists.
        if ($this->getContainer()->has('pickware.erp.plugin_config_service')) {
            $pickListDocumentTypeId = $this->get('pickware.erp.plugin_config_service')->getPickListDocumentType()->getId();
        }
        if ($pickListDocumentTypeId && ($documentTypeId === $pickListDocumentTypeId)) {
            return;
        }

        // This is a fix for (partial) delivery notes that may have been created with the shipping app of Pickware
        // Mobile.
        $isDeliveryNote = $documentTypeId === DocumentUtil::DOCUMENT_TYPE_ID_DELIVERY_NOTE;
        $pageBreak = (int) $documentComponent->_view->tpl_vars['Document']->value['pagebreak'];
        if ($isDeliveryNote) {
            // Replace sub articles of a complete set with their respective set article
            $pages = $documentManipulationService->substituteCompleteSubArticlesWithSetArticle(
                (int) $documentComponent->_order->__get('id'),
                $pages,
                $pageBreak
            );

            // Keep or remove sub articles of incomplete sets
            $pages = $documentManipulationService->removeIncompleteSubArticlesIfNecessary($pages);
        }

        // At this point remove any sub articles that are left on the document.
        $pages = $documentManipulationService->removeSubArticles($pages, $pageBreak);
        $args->getSubject()->_view->assign('Pages', $pages);
    }
}
