<?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\ViisonPickwareMobile\Components;

use \Zend_Db_Adapter_Abstract;
use Shopware\Models\Order\Order;

class OrderPickingService
{
    /**
     * @var Zend_Db_Adapter_Abstract
     */
    private $database;

    /**
     * @param Zend_Db_Adapter_Abstract $database
     */
    public function __construct($database)
    {
        $this->database = $database;
    }

    /**
     * Returns an associative array containing the IDs (key) and picked quantities (value) of all picked order items of
     * the passed `$order`.
     *
     * @param Order $order
     * @return array
     */
    public function getPickedItemQuantitiesOfOrder(Order $order)
    {
        $result = $this->database->fetchAssoc(
            'SELECT
                `s_order_details`.`id` AS `id`,
                `s_order_details_attributes`.`pickware_picked_quantity` AS `pickedQuantity`
            FROM `s_order_details`
            INNER JOIN `s_order_details_attributes`
                ON `s_order_details`.`id` = `s_order_details_attributes`.`detailID`
            WHERE
                `s_order_details`.`orderID` = :orderId
                AND `s_order_details_attributes`.`pickware_picked_quantity` > 0',
            [
                'orderId' => $order->getId(),
            ]
        );

        return array_combine(
            array_keys($result),
            array_map('intval', array_column($result, 'pickedQuantity'))
        );
    }
}
