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

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

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

    /**
     * Adds a new field 'hasDHLDispatchMethod' to every order, which is contained
     * in the view's data field. This field is true, if the order's dispatch method
     * is assigned to a DHL product, otherwise it's false.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onAfterGetListAction(\Enlight_Hook_HookArgs $args)
    {
        // Check if original method was successful and if there are any orders
        $view = $args->getSubject()->View();
        if (!$view->success || !$view->data) {
            return;
        }

        // Load all dispatch Ids, which are associated with a DHL product
        $dispatchIds = $this->get('db')->fetchCol(
            'SELECT dispatchId
            FROM s_premium_dispatch_viison_dhl
            WHERE productId != 0'
        );

        // Save in every order, if it has one of these dispatch methods assigned
        $orders = $view->data;
        foreach ($orders as &$order) {
            $order['hasDHLDispatchMethod'] = in_array($order['dispatchId'], $dispatchIds);
            $order['hasDispatchMethod'] |= $order['hasDHLDispatchMethod'];
        }
        $view->data = $orders;
    }
}
