<?php

namespace MNM\Spitzner\Observer;

/**
 * Check if orders/quote billingaddress is set correctly. Correct/copy over from shipping address otherwise.
 * Should not happen anyway
 */

use Magento\Framework\Event\ObserverInterface;

use MNM\Spitzner\Plugin\Checkout\ShippingInformationManagementPlugin;

class CheckOrderAddresses implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $order = $observer->getData('order');

        $billingAddress = $order->getBillingAddress();
        $shippingAddress = $order->getShippingAddress();

        if(empty($billingAddress->getFirstname()) || empty($billingAddress->getLastname()))
        {
            $billingAddress->setFirstname($shippingAddress->getFirstname());
            $billingAddress->setLastname($shippingAddress->getLastname());
            $billingAddress->setPrefix($shippingAddress->getPrefix());
            $billingAddress->setStreet($shippingAddress->getStreet());
            $billingAddress->setPostcode($shippingAddress->getPostcode());
            $billingAddress->setCity($shippingAddress->getCity());
            $billingAddress->setCountryId($shippingAddress->getCountryId());
        }
        else
        {
            $streetShipping = $shippingAddress->getStreet();
            $streetBilling =  $billingAddress->getStreet();

            //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];

                $billingAddress->setStreet($streetBilling);
            }
        }

        $repertusType = $shippingAddress->getDataByKey('repertus_address_type');

        if(($repertusType == '2' || $repertusType == 2) && strpos($streetShipping[0], 'Packstation') === 0)
        {
            $streetShipping = [
                'Packstation Nr. '.$shippingAddress->getDataByKey('repertus_number'),
                __('Postnummer').' '.$shippingAddress->getDataByKey('repertus_post_number')];

            $shippingAddress->setStreet($streetShipping);
        }
    }
}
