<?php

namespace KupShop\BalikonosBundle\BalikobotAdapters;

use KupShop\OrderingBundle\Util\Invoice\PdfGenerator;

class BalikobotDHLAdapter implements IBalikobotAdapter
{
    private $dhlContent;
    private $pdfGenerator;

    public function __construct(PdfGenerator $pdfGenerator)
    {
        $this->pdfGenerator = $pdfGenerator;
    }

    public function transformOrderData(\Order $order, array $data, array &$custom_data): array
    {
        $pieces_count = $custom_data['packages'] ?? 1;
        if ($pieces_count > 1) {
            $data['pieces_count'] = $pieces_count;
            $custom_data['packages'] = 1;
        }

        $data['rec_region'] = $order->delivery_state;
        $data['content'] = $this->dhlContent;

        if (isset($data['weight'])) {
            $data['weight'] = max($data['weight'], 0.1);
        }

        // DHL Paperless Trade service
        $PLT = $order->getData('balikobot', false)['PLT'] ?? null;
        if (!in_array($PLT, ['Y', 'N'])) {
            $PLT = (in_array($data['rec_country'], static::getUnsupportedCountries()) ? 'N' : 'Y');
        }
        if ($PLT == 'Y') {
            $pdfContent = $this->pdfGenerator->getInvoicePDFContent($order->id);
            $data['services'] = 'WY';
            $data['invoice_pdf'] = base64_encode($pdfContent);
        }

        if (!empty($data['content_data'])) {
            // zásilka mimo EU
            // price - Declared Value for Customs, odecist cenu dopravy
            $delivery_price = $order->getDeliveryPrice();
            $price = $order->total_price->sub($delivery_price['value_with_vat']);
            $data['price'] = \Decimal::max($price, \DecimalConstants::one())->printFloatValue(0);

            // pro DHL Express content_price – hodnota (cena) jednoho produktu
            $data['content_data'] = array_map(function ($d) {
                $d['content_price'] = $d['content_price'] / $d['content_pieces'];
                if (!empty($d['content_price_eur'])) {
                    $d['content_price_eur'] = $d['content_price_eur'] / $d['content_pieces'];
                }

                return $d;
            }, $data['content_data']);
        }

        return $data;
    }

    public function setDHLContent($content)
    {
        $this->dhlContent = $content;
    }

    // Countries that do not support papper less trade
    public static function getUnsupportedCountries()
    {
        return [
            'AF', 'AM', 'AZ', 'BD', 'BR', 'BN',
            'BY', 'CL', 'CR', 'DZ', 'EG',
            'GE', 'GT', 'HN', 'ID', 'IN',
            'IQ', 'IR', 'KG', 'KW', 'KZ',
            'LB', 'LY', 'MA', 'MD', 'NI',
            'PE', 'PH', 'PK', 'QA', 'RU',
            'SV', 'SY', 'TJ', 'TN', 'UA',
            'UZ', 'VN', 'YE', 'TR', 'ZA',
            'LK', 'CU', 'BO', 'MN', 'MX',
        ];
    }
}
