<?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 Warehouses20181217 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/warehouse/{id}/binLocations
     */
    public function postGetBinLocationsIndexAction()
    {
        $data = $this->view->data;
        if (!is_array($data)) {
            return;
        }

        foreach ($data as &$binLocation) {
            if (!isset($binLocation['articleDetailBinLocationMappings'])) {
                continue;
            }
            foreach ($binLocation['articleDetailBinLocationMappings'] as &$binLocationMapping) {
                if (!isset($binLocationMapping['articleDetail'])) {
                    continue;
                }
                // Use empty string for missing supplier number
                if (!isset($binLocationMapping['articleDetail']['supplierNumber'])) {
                    $binLocationMapping['articleDetail']['supplierNumber'] = '';
                }

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

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