<?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\ViisonDHL\Subscribers\Modules;

use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;
use Shopware\Plugins\ViisonCommon\Components\FileStorage\FileStorage;
use Shopware\Plugins\ViisonDHL\Classes\OnlineRetoureCommunication as RetoureCommunication;
use Shopware\Plugins\ViisonDHL\Util;
use Shopware\Plugins\ViisonDHL\Classes\ShippingUtil;

class Order extends Base
{
    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Modules_Order_SendMail_Send' => 'onSendMailSend',
        ];
    }

    /**
     * Adds the return label PDF to the confirmation email, if the plugin is configured to do so.
     *
     * @param \Enlight_Event_EventArgs $args
     */
    public function onSendMailSend(\Enlight_Event_EventArgs $args)
    {
        // Check whether a return label shall be added to the confirmation email
        $context = $args->getContext();
        $orderId = $this->get('db')->fetchOne(
            'SELECT id
            FROM s_order
            WHERE ordernumber = ?',
            [
                $context['sOrderNumber']
            ]
        );

        try {
            $autoSendReturnLabel = Util::instance()->config($context['sLanguage'], 'autoSendReturnLabel');
        } catch (\RuntimeException $e) {
            return;
        };
        if (!$autoSendReturnLabel) {
            return;
        }

        // Try to create a label
        $retoureCommunication = new RetoureCommunication();
        if (!$retoureCommunication->canCreateLabel($orderId)) {
            return;
        }

        // Calculate the shipment weight of the order to display it on the return label
        $shippingUtil = new ShippingUtil();
        $weight = $shippingUtil->determineShipmentWeight($orderId);

        try {
            $trackingCode = $retoureCommunication->createLabel($orderId, $weight);
        } catch (\Exception $exception) {
            // Do not break the Email sending by order checkout if something fails ...
            Util::instance()->log('Return label creation for order confirmation failed: ' . $exception->getMessage());
        };

        /** @var FileStorage $fileStorageService */
        $fileStorageService = $this->get('viison_common.document_file_storage_service');
        $documentFileName = Util::instance()->getDocumentFileName($trackingCode, ShippingUtil::DOCUMENT_TYPE_RETURN_LABEL);
        if (!$fileStorageService->doesFileExist($documentFileName)) {
            return;
        }

        // Add document as attachment
        if ($args->getMail()) {
            $args->getMail()->createAttachment(
                $fileStorageService->readFileContents($documentFileName),
                'application/pdf',
                \Zend_Mime::DISPOSITION_ATTACHMENT,
                \Zend_Mime::ENCODING_BASE64,
                'Retourenetikett.pdf'
            );
        }
    }
}
