<?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\Frontend;

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

class AdminSubscriber extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'sAdmin::sGetDispatchBasket::after' => 'onBeforeGetDispatchBasket',
        ];
    }

    /**
     * Fix the calculated weight of the basked by modifying the set article weight. We need this since Shopware uses the
     * weights of all article details directly from db, not what is displayed in the frontend. That is the reason the
     * other Subscriber of Checkout cannot influence the shipping cost by simply modifying the weight.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onBeforeGetDispatchBasket(\Enlight_Hook_HookArgs $args)
    {
        $result = $args->getReturn();
        $basketItems = $this->get('models')->getRepository('Shopware\\Models\\Order\\Basket')->findBy([
            'sessionId' => Shopware()->Session()->get('sessionId'),
        ]);

        foreach ($basketItems as $item) {
            $articleDetail = $this->get('models')->getRepository(
                'Shopware\\Models\\Article\\Detail'
            )->findOneBy([
                'number' => $item->getOrderNumber(),
            ]);
            if (!$articleDetail) {
                // Shipping cost, discounts etc. have no corresponding article detail
                continue;
            }

            if ($articleDetail->getAttribute() && $articleDetail->getAttribute()->getViisonSetarticleActive()) {
                $setArticleWeight = $this->get('models')->getRepository(
                    'Shopware\\CustomModels\\ViisonSetArticles\\SetArticle'
                )->getSetArticleWeight($articleDetail->getId());

                // Add the new calculated weight to the whole order weight
                $result['weight'] += $setArticleWeight * $item->getQuantity();
            }
        }

        $args->setReturn($result);
    }
}
