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

use Shopware\Models\Order\Detail as OrderDetail;
use Shopware\Plugins\ViisonCommon\Classes\Subscribers\AbstractBaseSubscriber;
use Shopware\Plugins\ViisonPickwareERP\Components\OrderDetailQuantityCalculator\OrderDetailQuantityCalculator;
use Shopware\Plugins\ViisonPickwareERP\Components\OrderDetailQuantityValidator\OrderDetailQuantityValidatorService;

class OrderDetailQuantityValidatorSubscriber extends AbstractBaseSubscriber
{
    /**
     * @inheritDoc
     */
    public static function getSubscribedEvents()
    {
        return [
            OrderDetailQuantityValidatorService::class . '::isQuantityAndShippedQuantityCombinationValid::after' => 'onAfterIsQuantityAndShippedQuantityCombinationValid',
        ];
    }

    /**
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onAfterIsQuantityAndShippedQuantityCombinationValid(\Enlight_Hook_HookArgs $args)
    {
        $return = $args->getReturn();
        if (!$return) {
            return;
        }

        // In ViisonPickwareMobile shipped must not be greater than quantity + cancelledReturned - pickedQuantity because
        // picked items cannot be shipped via ViisonPickwareERP (to avoid duplicate stock changes)

        /** @var OrderDetailQuantityCalculator $orderDetailQuantityCalculator */
        $orderDetailQuantityCalculator = $this->get('pickware.erp.order_detail_quantity_calculator_service');
        /** @var OrderDetail $orderDetail */
        $orderDetail = $args->get('orderDetail');

        $shipped = $args->get('shippedQuantity');
        $quantity = $args->get('quantity');
        $cancelledReturned = $orderDetailQuantityCalculator->calculateCancelledQuantityOfReturnShipmentItems($orderDetail);
        $pickedQuantity = $orderDetail->getAttribute()->getPickwarePickedQuantity();

        $return = $shipped + $pickedQuantity <= $quantity + $cancelledReturned;

        $args->setReturn($return);
    }
}
