<?php

declare(strict_types=1);

namespace MNM\Spitzner\Plugin\Quote\Model\Quote\Address;

use Magento\Quote\Model\Quote\Address;
use Magento\Customer\Model\Options;

class PrefixPatch
{
    protected Options $options;

    public function __construct(Options $options)
    {
        $this->options = $options;
    }

    public function afterGetData(Address $subject, $result)
    {
        if (is_array($result) && array_key_exists('prefix', $result)
            && (!empty($result['prefix'])
                || $result['prefix'] === "0")) {
            $result['prefix'] = $this->formatPrefix($result['prefix']);
        }

        if (is_array($result) && array_key_exists('suffix', $result)
            && (!empty($result['suffix'])
                || $result['suffix'] === "0")) {
            $result['suffix'] = $this->formatSuffix($result['suffix']);
        }

        return $result;
    }

    public function afterGetPrefix(Address $subject, $result)
    {
        return $this->formatPrefix($result);
    }

    public function afterGetSuffix(Address $subject, $result)
    {
        return $this->formatSuffix($result);
    }

    private function formatPrefix(?string $prefixValue): ?string
    {
        if($prefixValue == '3' || $prefixValue == 'keine Angabe') {
            return '';
        }

        if (array_key_exists($prefixValue, $prefixOptions = $this->options->getNamePrefixOptions())) {
            return $prefixOptions[$prefixValue];
        }

        return $prefixValue;
    }

    private function formatSuffix(?string $suffixValue): ?string
    {
        if (array_key_exists($suffixValue, $suffixOptions = $this->options->getNameSuffixOptions())) {
            return $suffixOptions[$suffixValue];
        }

        return $suffixValue;
    }
}