<?php

    namespace MNM\Spitzner\Plugin\Quote;

    use Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver;
    use Magento\Quote\Observer\Frontend\Quote\Address\VatValidator;
    use Magento\Framework\Event\Observer;

    class FixPaypalGuestCheckoutBug {
        /**
         * @var VatValidator
         */
        protected $vatValidator;

        /**
         * Initialize dependencies.
         *
         * @param VatValidator $vatValidator
         */
        public function __construct(
            VatValidator $vatValidator
            ) {
                $this->vatValidator = $vatValidator;
        }

        /**
         *
         * @param CollectTotalsObserver $subject
         * @param callable $proceed
         * @param Observer $observer
         * @return void
         */
        public function aroundExecute(CollectTotalsObserver $subject, callable $proceed, Observer $observer)
        {
            $proceed($observer);

            /** @var \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment */
            $shippingAssignment = $observer->getShippingAssignment();
            /** @var \Magento\Quote\Model\Quote $quote */
            $quote = $observer->getQuote();
            /** @var \Magento\Quote\Model\Quote\Address $address */
            $address = $shippingAssignment->getShipping()->getAddress();

            $customer = $quote->getCustomer();
            $storeId = $customer->getStoreId();

            if ($customer->getDisableAutoGroupChange()
                || false == $this->vatValidator->isEnabled($address, $storeId)
                ) {
                return;
            }

            if($quote->getCustomerGroupId() !== null)
            {
                $customer->setEmail($customer->getEmail() ?: $quote->getCustomerEmail());
                $quote->setCustomer($customer);
            }
        }
    }