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

use Shopware\Models\Order\Order as OrderModel;
use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;
use Shopware\Plugins\ViisonPickwareERP\Components\Warehouse\WarehouseIntegrityService;

class ViisonPickwareERPWarehouseManagementSubscriber extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            WarehouseIntegrityService::EVENT_NAME_COLLECT_WAREHOUSE_DELETION_CONSTRAINT_VIOLATIONS => 'onCollectWarehouseDeletionConstraintViolations',
        ];
    }

    /**
     * Checks whether any orders are currently being processed in the given warehouse and,
     * in case there are orders, returns a respective message.
     *
     * @param \Enlight_Event_EventArgs $args
     * @return string|null
     */
    public function onCollectWarehouseDeletionConstraintViolations(\Enlight_Event_EventArgs $args)
    {
        // Try to find any picked orders
        $builder = $this->get('models')->createQueryBuilder();
        $builder->select(
            'COUNT(_order.id)'
        )->from(OrderModel::class, '_order')
            ->join('_order.attribute', 'attribute')
            ->where('attribute.pickwareProcessingWarehouseId = :warehouseId')
            ->setParameter('warehouseId', $args['warehouse']->getId());
        $processedOrders = $builder->getQuery()->getSingleScalarResult();
        if (intval($processedOrders) > 0) {
            return $this->get('snippets')->getNamespace('subscribers/backend/viison_pickware_erp_warehouse_management')->get('can_delete_warehouse/issue/warehouse_is_processing_orders');
        }
    }
}
