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

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

abstract class Order extends Base
{
    /**
     * NOTE: Needs to be override by every Adapter
     * @var string $premiumDispatchTable The premium dispatch table
     */
    protected $premiumDispatchTable = '';

    /**
     * NOTE: Needs to be override by every Adapter
     * @var string $dispatchMethodName The method dispatch name.
     */
    protected $dispatchMethodName = '';

    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return array(
            '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 Shipping Adapter product
        $premiumDispatchTable = new \Zend_Db_Table($this->premiumDispatchTable);
        $dispatchIds = $this->get('db')->fetchCol(
            $premiumDispatchTable->select()
                ->from($premiumDispatchTable, array('dispatchId'))
                ->where('productId != 0')
        );

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

        $view->data = $orders;
    }
}
