<?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\ViisonPickwareMobile\Subscribers\Api;

use Shopware\Models\Article\Detail as ArticleDetail;
use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;

class VariantsSubscriber extends Base
{
    /**
     * @see \Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base::getSubscribedEvents()
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Api_Variants::putAction::after' => 'onAfterPutAction',
        ];
    }

    /**
     * Determines whether the updated variant is part of a multi variant article and, if it is NOT,
     * activates/deactivates the main article based on the 'active' field of the variant. This ensures
     * a behaviour consistent to activating/deactivating single variant articles in the backend.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onAfterPutAction(\Enlight_Hook_HookArgs $args)
    {
        // Check status of previous computation
        $view = $args->getSubject()->View();
        if (!$view->success) {
            return;
        }

        // Find the updated variant
        $variantId = $args->getSubject()->Request()->getParam('id');
        $variant = $this->get('models')->find(ArticleDetail::class, $variantId);
        if ($variant && $variant->getArticle()->getDetails()->count() === 1) {
            // Updated variant is the only variant of its main article, hence activate/deactivate the article
            $variant->getArticle()->setActive($variant->getActive());
            $this->get('models')->flush($variant->getArticle());
        }
    }
}
