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

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

class ArticleSubscriber extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'sArticles::sGetArticlesByCategory::after' => 'onAftersGetArticlesByCategory',
        ];
    }

    /**
     * Reacts to the event that is fired by the sArticles Core Component. This hook manipulates the availability
     * information of set articles in the listing view (e.g. frontend category view).
     *
     * @param \Enlight_Event_EventArgs $args
     * @return array
     */
    public function onAftersGetArticlesByCategory(\Enlight_Event_EventArgs $args)
    {
        $return = $args->getReturn();

        foreach ($return['sArticles'] as &$product) {
            if (!$product['viison_setarticle_active']) {
                continue;
            }

            $setArticleAvailability = $this->get('models')->getRepository('Shopware\\CustomModels\\ViisonSetArticles\\SetArticle')
                ->getCombinedSetArticleDetailsData($product['articleDetailsID']);
            $product['instock'] = $setArticleAvailability['instock'];
            $product['shippingtime'] = $setArticleAvailability['shippingtime'];
            $product['maxpurchase'] = $setArticleAvailability['maxpurchase'];
            $product['sReleasedate'] = $setArticleAvailability['releasedate'] ? $setArticleAvailability['releasedate']->format('d.m.Y') : null;
            $product['laststock'] = $setArticleAvailability['laststock'];
            $product['available'] = $setArticleAvailability['available'];
        }

        return $return;
    }
}
