<?php

namespace MNM\Spitzner\Plugin\Checkout;

use Magento\Checkout\Api\Data\ShippingInformationExtensionInterface;
use Magento\Checkout\Api\Data\ShippingInformationInterface;
use Magento\Checkout\Model\ShippingInformationManagement;
use Magento\Quote\Model\QuoteRepository;

class ShippingInformationManagementPlugin
{
    protected $quoteRepository;

    protected $checkoutSession;

    protected $customerSession;

    protected $messageManager;

    public function __construct(
        QuoteRepository $quoteRepository
        ) {
            $this->quoteRepository = $quoteRepository;
    }

    /**
     * @param ShippingInformationManagement $subject
     * @param $cartId
     * @param ShippingInformationInterface $addressInformation
     *
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function beforeSaveAddressInformation(
        ShippingInformationManagement $subject,
        $cartId,
        ShippingInformationInterface $addressInformation)
    {
        $shippingAddress =          $addressInformation->getShippingAddress();
        $billingAddress =           $addressInformation->getBillingAddress();
        $streetShipping =           $shippingAddress->getStreet();
        $streetBilling =            $billingAddress->getStreet();
        $quote =                    $this->quoteRepository->getActive($cartId);
        $quoteShippingAddress =     $quote->getShippingAddress();
        $quoteBillingAddress =      $quote->getBillingAddress();
        $shippingSameAsBilling =    $quoteShippingAddress->getSameAsBilling();

        self::removeStreetDuplicates($streetBilling);

        if(!$shippingSameAsBilling)
        {
            $shippingExtensionSttributes =  $addressInformation->getExtensionAttributes();
            $repertusAddressType =          $shippingExtensionSttributes->getRepertusAddressType();
            $repertusPostNumber =           $shippingExtensionSttributes->getRepertusPostNumber();
            $repertusNumber =               $shippingExtensionSttributes->getRepertusNumber();

            //update labels if is packstation
            if(     is_array($streetShipping)
                &&  strpos($streetShipping[0], 'Packstation') === 0)
            {
                $streetShipping[0] = 'Packstation Nr. '.$repertusNumber;
                $streetShipping[1] = __('Postnummer').' '.$repertusPostNumber;
            }
            else
            {
                //check if shipping has housenumber and billing not (bug)
                if(     $streetBilling[0] != $streetShipping[0]
                    &&  strncasecmp($streetBilling[0], $streetShipping[0], 5) === 0
                    &&  !preg_match('/\d+/', $streetBilling[0])
                    &&  preg_match('/\d+/', $streetShipping[0]))
                {
                    $streetBilling[0] = $streetShipping[0];
                }

                if($repertusAddressType == "2")
                {
                    $streetShipping[0] = 'Packstation Nr. '.$repertusNumber;
                    $streetShipping[1] = __('Postnummer').' '.$repertusPostNumber;
                }
                else
                {
                    self::removeStreetDuplicates($streetShipping);
                }
            }
        }
        else
        {
            $streetShipping = $streetBilling;
        }

        $shippingAddress->setStreet($streetShipping);
        $quoteShippingAddress->setStreet($streetShipping);
        $billingAddress->setStreet($streetBilling);
        $quoteBillingAddress->setStreet($streetBilling);

        $addressInformation->setShippingAddress($shippingAddress);
        $addressInformation->setBillingAddress($billingAddress);
        $quote->setShippingAddress($quoteShippingAddress);
        $quote->setBillingAddress($quoteBillingAddress);
    }

    /**
     * remove duplicates
     *
     * @param unknown $street
     */
    protected static function removeStreetDuplicates(&$street)
    {
        //check if address line 1 and 2 are equal
        if(is_array($street) && !empty($street[1]))
        {
            if($street[0] == $street[1])
            {
                $street[1] = '';
            }
            else
            {
                preg_match('/([^\d]+)\s?(.+)/i', $street[0], $result0);
                preg_match('/([^\d]+)\s?(.+)/i', $street[1], $result1);

                if(count($result0) > 1 && count($result1) > 1)
                {
                    if(     mb_stripos(trim($result1[1]), trim($result0[1])) === 0
                        &&  $result1[2] == $result0[2])
                    {
                        $street[1] = '';
                    }
                }
            }
        }

        //remove duplicates in single line
        if(is_array($street) && isset($street[0]))
        {
            $street[0] = implode(' ', array_unique(explode(' ', $street[0])));
        }

        if(is_array($street) && isset($street[1]))
        {
            $street[1] = implode(' ', array_unique(explode(' ', $street[1])));
        }
    }
}