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

use Shopware\Plugins\ViisonCommon\Classes\Installation\SQLHelper;
use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;
use Shopware\Plugins\ViisonSetArticles\Classes;

class PluginInstallationSubscriber extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Plugin_PostInstall' => 'onPluginPostInstall',
        ];
    }

    /**
     * @param \Enlight_Event_EventArgs $args
     */
    public function onPluginPostInstall(\Enlight_Event_EventArgs $args)
    {
        $pluginName = $args->get('plugin')->getName();
        switch ($pluginName) {
            case 'RedMagnalister':
                $this->onMagnalisterInstall();
                break;
            case 'ViisonPickwareERP':
                $this->onPickwareERPInstall();
                break;
            default:
                return;
        }
    }

    /**
     * When Magnalister is installed: execute the Magnalister patch.
     */
    private function onMagnalisterInstall()
    {
        $magnalisterPatcher = new Classes\MagnalisterPatcher($this->get('models'));
        $magnalisterPatcher->doPatch();
    }

    /**
     * When PickwareERP is installed: disable stock management for all set articles.
     */
    private function onPickwareERPInstall()
    {
        $sqlHelper = new SQLHelper($this->get('db'));
        if ($sqlHelper->doesColumnExist('s_articles_attributes', 'pickware_stock_management_disabled')) {
            $this->get('db')->query(
                'UPDATE s_articles_attributes
                SET pickware_stock_management_disabled = 1
                WHERE viison_setarticle_active = 1'
            );
        } elseif ($sqlHelper->doesColumnExist('s_articles_attributes', 'viison_not_relevant_for_stock_manager')) {
            // Legacy (< 5.0.0) Pickware
            $this->get('db')->query(
                'UPDATE s_articles_attributes
                SET viison_not_relevant_for_stock_manager = 1
                WHERE viison_setarticle_active = 1'
            );
        }
    }
}
