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

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

class Orders20181217 extends Layer
{
    /**
     * @inheritdoc
     */
    public function getVersion()
    {
        return '2018-12-17';
    }

    /**
     * Traverses the response data and ensures that all article details contain non-null `supplierNumber` and supplier
     * `name` fields. This works around a problem in the Stocking app (v5.1.0), which cannot handle null values for
     * these fields.
     *
     * pre 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) {
                if (!isset($orderDetail['articleDetail'])) {
                    continue;
                }
                // Use empty string for missing supplier number
                if (!isset($orderDetail['articleDetail']['supplierNumber'])) {
                    $orderDetail['articleDetail']['supplierNumber'] = '';
                }

                // Use empty string for missing supplier name
                if (!isset($orderDetail['articleDetail']['article'])) {
                    $orderDetail['articleDetail']['article'] = [];
                }
                if (!isset($orderDetail['articleDetail']['article']['supplier'])) {
                    $orderDetail['articleDetail']['article']['supplier'] = [];
                }
                if (!isset($orderDetail['articleDetail']['article']['supplier']['name'])) {
                    $orderDetail['articleDetail']['article']['supplier']['name'] = '';
                }
            }
        }
        unset($order);

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