<?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.

use Doctrine\ORM\Query;
use Shopware\Components\Model\QueryBuilder;
use Shopware\CustomModels\ViisonPickwareERP\StockLedger\StockItemPropertyValue;
use Shopware\Plugins\ViisonCommon\Controllers\ViisonCommonBaseController;

class Shopware_Controllers_Backend_ViisonPickwareCommonOrderItemProperties extends ViisonCommonBaseController
{
    /**
     * Responds a filtered and sorted list of stock item property values.
     */
    public function getStockItemPropertyValuesAction()
    {
        $filter = $this->Request()->getParam('filter', []);
        $orderBy = $this->Request()->getParam('sort', []);

        /** @var QueryBuilder $builder */
        $builder = $this->get('models')->createQueryBuilder();
        $builder
            ->setAlias('property')
            ->select(
                'property',
                'itemProperty'
            )
            ->from(StockItemPropertyValue::class, 'property')
            ->join('property.itemProperty', 'itemProperty')
            ->join('property.stockItem', 'stockItem')
            ->join('stockItem.stockLedgerEntry', 'stockLedgerEntry')
            ->addFilter($filter)
            ->addOrderBy($orderBy);

        $query = $builder->getQuery();
        $result = $query->getResult(Query::HYDRATE_ARRAY);
        $total = count($result);

        $this->View()->assign([
            'success' => true,
            'data' => $result,
            'total' => $total,
        ]);
    }

    /**
     * Finds the property type entities for all POSTed data entries and updates their values.
     */
    public function updateStockItemPropertyValuesAction()
    {
        $data = $this->Request()->getParam('data');
        $updatedStockEntryPropertyTypes = [];
        foreach ($data as $stockEntryItemPropertyData) {
            $stockEntryItemProperty = $this->get('models')->find(
                StockItemPropertyValue::class,
                $stockEntryItemPropertyData['id']
            );
            if ($stockEntryItemProperty) {
                $stockEntryItemPropertyData = array_filter($stockEntryItemPropertyData, function ($key) {
                    return $key !== 'itemProperty';
                }, ARRAY_FILTER_USE_KEY);
                $stockEntryItemProperty->fromArray($stockEntryItemPropertyData);
                $updatedStockEntryPropertyTypes[] = $stockEntryItemProperty;
            }
        }
        $this->get('models')->flush($updatedStockEntryPropertyTypes);

        // Respond with the updated types
        $this->Request()->setParam('filter', [
            [
                'property' => 'property.id',
                'value' => array_map(
                    function (StockItemPropertyValue $stockEntryItemProperty) {
                        return $stockEntryItemProperty->getId();
                    },
                    $updatedStockEntryPropertyTypes
                ),
                'expression' => 'IN',
            ],
        ]);
        $this->Request()->setParam('sort', [
            [
                'property' => 'stockItem.id',
                'direction' => 'ASC',
            ],
        ]);
        $this->getStockItemPropertyValuesAction();
    }
}
