<?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 Variants20200301 extends Layer
{
    /**
     * @inheritdoc
     */
    public function getVersion()
    {
        return '2020-03-01';
    }

    /**
     * Moves the binLocation.code and binLocation.warehouseId nested filter to the top level in the filter array and
     * sets the `isPickwareBinLocationFilter` key to identify it in the main action.
     *
     * pre GET /api/variants
     */
    public function preIndexAction()
    {
        $filter = $this->request->getParam('filter', []);

        // Find the binLocation filter if present and replace it with our magic filter
        if (isset($filter[0]['children'])) {
            $filteredChildren = [];
            foreach ($filter[0]['children'] as $child) {
                if (!isset($child['children'])) {
                    $filteredChildren[] = $child;
                    continue;
                }
                $children = $child['children'];
                $isBinLocationFilter = count($children) === 2 && $children[0]['property'] === 'binLocation.code' && $children[1]['property'] === 'binLocation.warehouseId';
                if ($isBinLocationFilter) {
                    $child['isPickwareBinLocationFilter'] = true;
                    $filter[] = $child;
                } else {
                    $filteredChildren[] = $child;
                }
            }
            $filter[0]['children'] = $filteredChildren;
        }

        $this->request->setParam('filter', $filter);
    }
}
