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

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

class Order extends Base
{
    /**
     * @Override
     */
    public static function getSubscribedEvents()
    {
        return array(
            'Shopware_Controllers_Backend_Order::getListAction::after' => 'onAfterBackendOrderGetListAction'
        );
    }

    /**
     * Adds a new field 'hasUPSDispatchMethod' 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 UPS product, otherwise it's false.
     *
     * @param Enlight_Hook_HookArgs $args The arguments passed by the method triggering the hook.
     */
    public function onAfterBackendOrderGetListAction(\Enlight_Event_EventArgs $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 UPS product
        $dispatchIds = $this->get('db')->fetchCol(
            'SELECT dispatchId
             FROM s_premium_dispatch_viison_ups
             WHERE productId != 0'
        );

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

        // Write the results back to the view
        $view->data = $orders;
    }
}
