<?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 Enlight_Event_EventArgs;
use Shopware\CustomModels\ViisonPickwareERP\Warehouse\BinLocation;
use Shopware\Plugins\ViisonCommon\Classes\Subscribers\AbstractBaseSubscriber;
use Shopware\Plugins\ViisonPickwareERP\Controllers\ControllerEvents;

class BinLocationsSubscriber extends AbstractBaseSubscriber
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            ControllerEvents::NOTIFY_UNTIL_PREVENT_BIN_LOCATION_DELETION => 'onPreventBinLocationDeletion',
        ];
    }

    /**
     * @param Enlight_Event_EventArgs $args
     * @return string|null The reason for preventing the bin location deletion or `null`, if the deletion is allowed.
     */
    public function onPreventBinLocationDeletion(Enlight_Event_EventArgs $args)
    {
        /** @var BinLocation $binLocation */
        $binLocation = $args->get('binLocation');

        $pickedQuantityCount = $this->get('db')->fetchOne(
            'SELECT COUNT(*)
            FROM `pickware_wms_picked_quantities`
            WHERE `binLocationId` = :binLocationId',
            [
                'binLocationId' => $binLocation->getId(),
            ]
        );
        if (intval($pickedQuantityCount) === 0) {
            return null;
        }

        return 'It is temporarily locked by picked quantities of "Shopware WMS powered by Pickware".';
    }
}
