<?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 SearchSubscriber extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Frontend_Search::defaultSearchAction::after' => 'afterSearchIndexAction',
        ];
    }

    /**
     * Manipulates the frontend search view. Fix set article properties in the search result.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function afterSearchIndexAction(\Enlight_Hook_HookArgs $args)
    {
        // Find set articles in the serach result
        $sSearchResults = $args->getSubject()->View()->sSearchResults;

        // Return early if the search result holds no articles
        if (empty($sSearchResults['sArticles'])) {
            return;
        }

        $setArticles = array_values(array_filter($sSearchResults['sArticles'], static function ($article) {
            return intval($article['viison_setarticle_active']) === 1;
        }));
        $setArticleDetailIds = array_map(static function ($setArticle) {
            return $setArticle['articleDetailsID'];
        }, $setArticles);

        // Return early if the search result holds no set articles
        if (count($setArticleDetailIds) === 0) {
            return;
        }

        $setArticleAvailabilities = $this->get('models')
            ->getRepository('Shopware\\CustomModels\\ViisonSetArticles\\SetArticle')
            ->getCombinedSetArticleDetailsBatchData($setArticleDetailIds);
        foreach ($setArticles as &$setArticle) {
            if (!array_key_exists($setArticle['articleDetailsID'], $setArticleAvailabilities)) {
                continue;
            }
            $setArticleAvailability = $setArticleAvailabilities[$setArticle['articleDetailsID']];

            $setArticle['instock'] = $setArticleAvailability['instock'];
            $setArticle['shippingtime'] = $setArticleAvailability['shippingtime'];
            $setArticle['maxpurchase'] = $setArticleAvailability['maxpurchase'];
            $setArticle['laststock'] = $setArticleAvailability['laststock'];
            $setArticle['available'] = $setArticleAvailability['available'];
            $setArticle['weight'] = $setArticleAvailability['weight'];
            $setArticle['releasedate'] = $setArticleAvailability['releasedate'];
        }
        unset($setArticle);

        // Set new search result
        $args->getSubject()->View()->sSearchResults = $sSearchResults;
    }
}
