<?php

namespace KupShop\BalikonosBundle\BalikobotAdapters;

use KupShop\OrderingBundle\Exception\UnknownAttachmentTypeException;
use KupShop\OrderingBundle\Util\Attachment\AttachmentLocator;

class BalikobotFedexAdapter implements IBalikobotAdapter
{
    private $attachmentLocator;

    public function __construct(AttachmentLocator $attachmentLocator)
    {
        $this->attachmentLocator = $attachmentLocator;
    }

    public function transformOrderData(\Order $order, array $data, array &$custom_data): array
    {
        $contentData = [];

        foreach ($order->fetchItems() as $item) {
            if (!empty($item['product'])) {
                /** @var \Product $product */
                $product = $item['product'];
                $contentData[] = [
                    'content_weight' => $product->weight,
                    'content_pieces' => $item['pieces'],
                    'content_price' => $item['total_price']['value_with_vat']->asFloat(),
                    'content_description' => substr($item['descr'], 0, 60),
                    'content_country' => 'CZ',
                    'content_currency' => $order->getCurrency(),
                ];
            }
        }

        $data['ins_currency'] = $order->getCurrency();
        $data['content_data'] = $contentData;

        if (!empty($order->delivery_state)) {
            $data['rec_region'] = $order->delivery_state;
        }

        $data['invoice_pdf'] = $this->generateBase64Invoice($order);

        return $data;
    }

    public function generateBase64Invoice(\Order $order): string
    {
        try {
            $attachment = $this->attachmentLocator->getServiceByType('order_invoice', $order);

            return base64_encode($attachment->getAttachment()['attachment']);
        } catch (UnknownAttachmentTypeException $e) {
            return '';
        }
    }
}
