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

use Exception;
use Shopware\Plugins\ViisonShippingCommon\Classes\PluginInfo;
use Zend_Db;
use Zend_Db_Adapter_Abstract;

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

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

    /**
     * @param PluginInfo $pluginInfo
     * @param int $orderId
     * @param string|ShippingLabelCreationResult $shipment
     * @return array
     */
    public function generateOrderShipmentData(PluginInfo $pluginInfo, $orderId, $shipment)
    {
        // $shipment can be string because some adapters already return a document identifier and not a
        // ShippingLabelCreationResult
        if (is_string($shipment)) {
            $shipmentId = null;
            $trackingCode = $shipment;
        } else {
            $shipmentId = $shipment->getShippingLabelId();
            $trackingCode = $shipment->getNewTrackingCode();
        }

        $queryBuilder = $this->database
            ->select()
            ->from(
                $pluginInfo->getOrderTableName(),
                [
                    'id',
                    'orderId',
                    'trackingCode',
                    'url',
                    'DATE_FORMAT(created, "%Y-%m-%dT%H:%i:%sZ") AS created',
                    'exportDocumentUrl',
                    'returnShipment',
                ]
            )->where(
                'url LIKE ?',
                '%' . ($shipmentId ?: $trackingCode)
            );
        if ($orderId !== null && $orderId !== 0) {
            $queryBuilder->where(
                'orderId = ?',
                $orderId
            );
        }
        // In case the order contains another label with the same trackingcode fetch the latest
        $queryBuilder->order('created DESC');

        return $queryBuilder->query()->fetch(Zend_Db::FETCH_ASSOC);
    }
}
