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

use Shopware\Plugins\ViisonCommon\Classes\Util\Util as ViisonCommonUtil;
use Shopware\Plugins\ViisonShippingCommon\Subscriber\ShippingProviders as BaseShippingProviders;

class ShippingProviders extends BaseShippingProviders
{
    /**
     * @inheritdoc
     */
    public function onCollectShippingProviders(\Enlight_Event_EventArgs $args)
    {
        if ($this->isPickwareEvent($args) && !$this->hasDhlPremiumLicense()) {
            // Event was fired by Pickware, but the DHL premium support plugin is not available
            // or its license is invalid, hence don't return a shipping provider
            return null;
        }

        return parent::onCollectShippingProviders($args);
    }

    /**
     * Returns true when the event was thrown by PickwareMobile.
     *
     * @param \Enlight_Event_EventArgs $args
     * @return bool
     */
    private function isPickwareEvent(\Enlight_Event_EventArgs $args)
    {
        return mb_strpos($args->getName(), 'Pickware') !== false;
    }

    /**
     * @return bool True, if the ViisonDHLPremium plugin is licensed in this shop.
     */
    public function hasDhlPremiumLicense()
    {
        // In Shopware >= 5.5 we assume the plugin is licensed when it is installed and active.
        if (ViisonCommonUtil::assertMinimumShopwareVersion('5.5.0')) {
            return ViisonCommonUtil::isPluginInstalledAndActive('backend', 'ViisonDHLPremium');
        }

        // Otherwise use checkLicense()-method of DHLPremium Bootstrap
        /** @var \Shopware_Plugins_Backend_ViisonDHLPremium_Bootstrap $dhlPremiumBootstrap */
        $dhlPremiumBootstrap = $this->get('plugins')->get('Backend')->get('ViisonDHLPremium');

        return $dhlPremiumBootstrap && $dhlPremiumBootstrap->checkLicense(false);
    }
}
