<?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\ViisonPickwareCommon\Classes\ApiRequestCompatibility\Layers;

use Shopware\Plugins\ViisonPickwareCommon\Classes\ApiRequestCompatibility\Layer;

class Orders20190328 extends Layer
{
    /**
     * @inheritdoc
     */
    public function getVersion()
    {
        return '2019-03-28';
    }

    /**
     * post GET /api/orders
     */
    public function postIndexAction()
    {
        $data = $this->view->data;
        if (!is_array($data)) {
            return;
        }

        foreach ($data as &$order) {
            if (!isset($order['details'])) {
                continue;
            }
            foreach ($order['details'] as &$orderDetail) {
                // Until PickwareERP version 5 the shipped value was reduced when a return shipment was created. This
                // semantic has been removed in PickwareERP version 6.
                $orderDetail['shipped'] = $orderDetail['shipped'] - $orderDetail['pickwareReturnedQuantity'];

                // Until PickwareERP version 5 return shipments were cancelled immediately after their creation.
                // Cancelling a return shipment position reduces the quantity counter of the corresponding order detail.
                // In PickwareERP 6 there can be a return shipment that has been created but not cancelled yet. For each
                // order detail in this state a cancellation of the orderDetail is faked by reducing the quantity by
                // the number of item returned but not cancelled
                // (pickwareReturnedQuantity - pickwareCancelledReturnedQuantity).
                $orderDetail['quantity'] = $orderDetail['quantity'] - $orderDetail['pickwareReturnedQuantity'] + $orderDetail['pickwareCancelledReturnedQuantity'];
            }
            unset($orderDetail);
        }
        unset($order);

        $this->view->data = $data;
    }
}
