<?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\Subscribers\Backend;

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base as BaseSubscriber;

class Order extends BaseSubscriber
{
    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Backend_Order::getListAction::after' => 'onAfterGetList',
        ];
    }

    /**
     * Add a field to each orderDetail, that tells whether the orderDetail has stockEntryItemProperties
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onAfterGetList(\Enlight_Hook_HookArgs $args)
    {
        $orders = $args->getSubject()->View()->data;
        $success = $args->getSubject()->View()->success;

        if (!$orders || !$success) {
            return;
        }

        $orderDetailIds = [];
        foreach ($orders as $order) {
            foreach ($order['details'] as $orderDetail) {
                if ($orderDetail['mode'] !== 0) {
                    continue;
                }
                $orderDetailIds[$orderDetail['id']] = true;
            }
        }
        $orderDetailIds = array_keys($orderDetailIds);

        // If none of the orders has details, the query below will fail
        if (empty($orderDetailIds)) {
            return;
        }

        /** @var \Enlight_Components_Db_Adapter_Pdo_Mysql $db */
        $db = $this->get('db');
        $numberOfStockItemPropertiesPerOrderDetail = $db->fetchPairs(
            'SELECT
                `stockLedgerEntries`.`orderDetailId`,
                COUNT(`stockItemPropertyValues`.`id`)
            FROM `pickware_erp_stock_ledger_entries` AS `stockLedgerEntries`
            LEFT JOIN `pickware_erp_stock_items` AS `stockItems`
                ON `stockItems`.`stockLedgerEntryId` = `stockLedgerEntries`.`id`
            LEFT JOIN `pickware_erp_stock_item_property_values` AS `stockItemPropertyValues`
                ON `stockItemPropertyValues`.`stockItemId` = `stockItems`.`id`
            WHERE `stockLedgerEntries`.`orderDetailId` IN (' . implode(',', $orderDetailIds) . ')
            GROUP BY `stockLedgerEntries`.`orderDetailId`'
        );

        foreach ($orders as &$order) {
            foreach ($order['details'] as &$orderDetail) {
                if (isset($numberOfStockItemPropertiesPerOrderDetail[$orderDetail['id']])) {
                    $orderDetail['viisonNumberOfStockEntryItemProperties'] = $numberOfStockItemPropertiesPerOrderDetail[$orderDetail['id']];
                } else {
                    $orderDetail['viisonNumberOfStockEntryItemProperties'] = 0;
                }
            }
        }

        $args->getSubject()->View()->data = $orders;
    }
}
