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

use Doctrine\ORM\Query;
use Shopware\Components\Model\ModelManager;
use Shopware\CustomModels\ViisonShippingCommon\Shipment\Document;
use Shopware\Models\Order\Order;
use Shopware\Plugins\ViisonShippingCommon\Classes\Communication\Communication;
use Shopware\Plugins\ViisonShippingCommon\Classes\PluginInfo;

class ModelBasedReturnLabelCreator implements ReturnLabelCreator
{
    /**
     * @var ModelManager
     */
    private $entityManager;

    /**
     * @var PluginInfo
     */
    private $pluginInfo;

    /**
     * @var Communication
     */
    private $communication;

    /**
     * @param ModelManager $entityManager
     * @param PluginInfo $pluginInfo
     * @param Communication $communication
     */
    public function __construct($entityManager, PluginInfo $pluginInfo, Communication $communication)
    {
        $this->entityManager = $entityManager;
        $this->pluginInfo = $pluginInfo;
        $this->communication = $communication;
    }

    /**
     * @inheritdoc
     */
    public function createReturnLabel(
        $orderId,
        array $receiverAddress,
        $weightInKg,
        array $configuration = null
    ) {
        $shipment = $this->communication->createReturnLabel(
            $orderId,
            $weightInKg,
            false, // useItemWeights
            $receiverAddress,
            $configuration ?: [], // shippingSettings
            [] // extraSettings
        );

        // Fetch shipment as array data
        $queryBuilder = $this->entityManager->createQueryBuilder();
        $queryBuilder
            ->select(
                'shipment',
                'documents'
            )
            ->from($this->pluginInfo->getShipmentModelName(), 'shipment')
            ->leftJoin('shipment.documents', 'documents')
            ->where('shipment.id = :id')
            ->setParameter('id', $shipment->getId());
        $result = $queryBuilder->getQuery()->getOneOrNullResult(Query::HYDRATE_ARRAY);

        $result['documentIdentifier'] = $shipment->getDocumentByType(Document::DOCUMENT_TYPE_RETURN_LABEL)->getId();

        /** @var Order $order */
        $order = $this->entityManager->find(Order::class, $orderId);
        $returnLabelTrackingCodes = $order->getAttribute()->getViisonReturnLabelTrackingId();
        $newReturnLabelTrackingCodes = explode(',', $returnLabelTrackingCodes);
        $newReturnLabelTrackingCodes[] = $result['trackingCode'];
        $newReturnLabelTrackingCodes = array_filter($newReturnLabelTrackingCodes, 'strlen');
        $newReturnLabelTrackingCodes = implode(',', $newReturnLabelTrackingCodes);
        $order->getAttribute()->setViisonReturnLabelTrackingId($newReturnLabelTrackingCodes);
        $this->entityManager->flush($order->getAttribute());

        return $result;
    }
}
