<?php

declare(strict_types=1);

namespace External\HannahBundle\SAP\Util\DataFactory;

use KupShop\KupShopBundle\Context\CountryContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\ReturnsBundle\Entity\ReturnEntity;
use KupShop\ReturnsBundle\Util\ReturnsUtil;
use Symfony\Contracts\Service\Attribute\Required;

class ReturnDataFactory extends AbstractDataFactory
{
    public ?ReturnsUtil $returnsUtil = null;

    #[Required]
    final public function setReturnsUtil(?ReturnsUtil $returnsUtil = null): void
    {
        $this->returnsUtil = $returnsUtil;
    }

    public static function getRequiredArguments(): array
    {
        return [
            'return' => ReturnEntity::class,
        ];
    }

    protected function createData(array $arguments): array
    {
        /** @var ReturnEntity $return */
        $return = $arguments['return'];

        $order = $this->returnsUtil->getReturnOrder($return->getId());

        $iban = '';
        $bankNumber = '';
        $accountNumber = '';
        if ((new \PHP_IBAN\IBAN($return->getBankAccount()))->Verify()) {
            $iban = str_replace(' ', '', $return->getBankAccount());
        } else {
            [$accountNumber, $bankNumber] = explode('/', $return->getBankAccount());
        }

        return [
            'OrderId' => $order?->order_no ?: $return->getCode(),
            'Bankcountry' => $order?->invoice_country ?: Contexts::get(CountryContext::class)->getDefaultId(),
            'Bankn' => $accountNumber,
            'Bankl' => $bankNumber,
            'Iban' => $iban,
            'ReturnItems' => $this->getReturnItems($return),
        ];
    }

    private function getReturnItems(ReturnEntity $return): array
    {
        $items = [];

        foreach ($return->getItems() as $item) {
            if (empty($item['product'])) {
                continue;
            }

            $items[] = [
                'Matnr' => $item['product']?->code,
                'ReturnQuantity' => $item['pieces'],
                'ItemUom' => 'PCE',
                'Reason' => $this->getReturnReasonSapId($return, $item),
            ];
        }

        if ($deliveryReturnPrice = $this->returnsUtil->getReturnTotals($return->getId())['delivery_price'] ?? null) {
            // vracime dopravne
            if ($deliveryReturnPrice->isPositive()) {
                $items[] = [
                    'Matnr' => 'S0000000064',
                    'ReturnQuantity' => 1,
                    'ItemUom' => 'PCE',
                    'Reason' => 'XX',
                ];
            }
        }

        return $items;
    }

    private function getReturnReasonSapId(ReturnEntity $return, array $item): string
    {
        $reasonsByName = array_flip(array_map(fn ($x) => mb_strtolower($x), static::getSapReturnReasons()));

        return (string) ($reasonsByName[mb_strtolower($item['reason_name'] ?: '')] ?? 'XX');
    }

    private static function getSapReturnReasons(): array
    {
        return [
            '01' => 'Produkt je moc malý',
            '02' => 'Produkt je moc velký',
            '03' => 'Produkt se mi nelíbí',
            '04' => 'Boží neodpovídá popisu a obrá',
            '05' => 'Nevyhovující velikost/střih',
            '06' => 'Přišlo jiné zboží, než jsem si objednal/a ',
            '07' => 'Zboží přišlo poškozené',
            '99' => 'Storno služby',
            'XX' => 'Jiné',
        ];
    }
}
