<?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\CustomModels\ViisonPickwareMobile\PickedQuantity;

use Shopware\Components\Model\ModelRepository;

class PickedQuantityRepository extends ModelRepository
{
    /**
     * Fetches the picked quantities of all order details having one of the passed $orderDetailIds and returns an array
     * that contains the results grouped by order detail ID. Please note that although stock entry items are associated
     * with picked quantities via stock entry mappings and stock entries, they are added as a top level
     * 'stockItems' entry to each picked quantity array.
     *
     * @param int[] $orderDetailIds
     * @return array
     */
    public function getPickedQuantityArrays(array $orderDetailIds)
    {
        if (count($orderDetailIds) === 0) {
            return [];
        }

        // Fetch all picked quantities incl. their stock entry items and property values
        $builder = $this->getEntityManager()->createQueryBuilder();
        $builder
            ->select(
                'pickedQuantity',
                'binLocation',
                'stockLedgerEntryMappings',
                'stockLedgerEntry',
                'stockItems',
                'propertyValues',
                'itemProperty'
            )
            ->from(PickedQuantity::class, 'pickedQuantity')
            ->leftJoin('pickedQuantity.binLocation', 'binLocation')
            ->leftJoin('pickedQuantity.stockLedgerEntryMappings', 'stockLedgerEntryMappings')
            ->leftJoin('stockLedgerEntryMappings.stockLedgerEntry', 'stockLedgerEntry')
            ->leftJoin('stockLedgerEntry.stockItems', 'stockItems')
            ->leftJoin('stockItems.propertyValues', 'propertyValues')
            ->leftJoin('propertyValues.itemProperty', 'itemProperty')
            ->where('pickedQuantity.orderDetailId IN (:orderDetailIds)')
            ->setParameter('orderDetailIds', $orderDetailIds);
        $result = $builder->getQuery()->getArrayResult();

        // Prepare the results array containing an empty array for each order detail ID
        $groupedResult = array_fill_keys(
            array_map(
                function ($orderDetailId) {
                    return $orderDetailId . '';
                },
                $orderDetailIds
            ),
            []
        );

        // Clean results to remove intermediary stock entries and stock entry mappings and group them by order detail ID
        foreach ($result as $row) {
            $stockEntryItems = [];
            foreach ($row['stockLedgerEntryMappings'] as $stockEntryMapping) {
                $stockEntryItems = array_merge($stockEntryItems, $stockEntryMapping['stockLedgerEntry']['stockItems']);
            }
            $row['stockItems'] = $stockEntryItems;
            unset($row['stockLedgerEntryMappings']);

            $groupKey = '' . $row['orderDetailId'];
            $groupedResult[$groupKey][] = $row;
        }

        return $groupedResult;
    }
}
