<?php declare(strict_types=1);
namespace ImnxxCustomerHelper\Subscriber;
use ImnxxCustomerHelper\Service\HelperService;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use stdClass;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AddressSubscriber implements EventSubscriberInterface
{
private HelperService $helperService;
public function __construct(HelperService $helperService)
{
$this->helperService = $helperService;
}
public static function getSubscribedEvents(): array
{
return [
GenericPageLoadedEvent::class => 'onPageLoaded',
CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlacedEvent',
];
}
public function onCheckoutOrderPlacedEvent(CheckoutOrderPlacedEvent $event)
{
$_SESSION['GET_ADDRESSES'] = true;
}
private function getNwbGuestAddresses($addressGroupId, $nwbService)
{
$curl = curl_init('https://'.$nwbService.'/customercare/api/addresses/GetVisitorAddresses/' . $addressGroupId);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$nwbAccountAddresses = json_decode(curl_exec($curl));
curl_close($curl);
return $nwbAccountAddresses;
}
private function getNwbAddresses($nwbAccountId, $nwbSessionId, $nwbService)
{
$curl = curl_init('https://'.$nwbService.'/customercare/api/addresses/GetUserAddresses/' . $nwbAccountId);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['x-nwb-sessionid: ' . $nwbSessionId]);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$nwbAccountAddresses = json_decode(curl_exec($curl));
curl_close($curl);
return $nwbAccountAddresses;
}
private function getAddressState($swAddresses, $nwbAddresses): stdClass
{
$addressStatus = new stdClass();
$addressStatus->delete = [];
$addressStatus->update = [];
$addressStatus->add = [];
$swAddressIds = [];
$nwbAddressIds = [];
foreach ($swAddresses as $swAddress) {
if($swAddress->getCustomFields()['custom_address_attributs_nwb_address_id'] !== 0) {
$swAddressIds[$swAddress->getCustomFields()['custom_address_attributs_nwb_address_id']] = $swAddress;
}
}
foreach ($nwbAddresses->Addresses as $nwbAddress) {
$nwbAddressIds[$nwbAddress->ID] = $nwbAddress;
}
foreach ($nwbAddressIds as $nwbId => $nwbAddress) {
if (isset($swAddressIds[$nwbId])) {
$addressStatus->update[$nwbId] = $swAddressIds[$nwbId];
} else {
$addressStatus->add[$nwbId] = $nwbAddress;
}
}
foreach ($swAddressIds as $nwbId => $swAddress) {
if (!isset($addressStatus->update[$nwbId])) {
$addressStatus->delete[$swAddress->getId()] = $swAddress;
}
}
return $addressStatus;
}
public function convertNwbAddressToSwAddress($nwbAddress, $customerId, $context): array
{
if ($nwbAddress->Country != 'DE') {
// get Country ID, when not germany
$nwbAddress->Country_id = $this->helperService->getCountryIdByIso($nwbAddress->Country, $context);
} else {
$nwbAddress->Country_id = $this->helperService->getCountryIdByIso('DE', $context);
}
if (strtolower($nwbAddress->Salutation) == 'herr') {
$nwbAddress->Salutation_id = '5d6a01a988104035adc1e822e2d2ca7e';
} elseif (strtolower($nwbAddress->Salutation) == 'frau') {
$nwbAddress->Salutation_id = '7ae9a14f06db435bbbd95bcb0a92cf17';
} else {
$nwbAddress->Salutation_id = '40a8fca759e04bb5a372711c7aa63e10';
}
$phoneNr = '';
if (
isset($nwbAddress->TelephoneCityPrefix) &&
$nwbAddress->TelephoneCityPrefix != '' &&
isset($nwbAddress->TelephoneNumber) &&
$nwbAddress->TelephoneNumber != ''
) {
$phoneNr = $nwbAddress->TelephoneCityPrefix . '/' . $nwbAddress->TelephoneNumber;
}
$street = $nwbAddress->Street;
$streetNumber = $nwbAddress->Streetnumber;
$salutationId = $nwbAddress->Salutation_id;
$address = [
'customerId' => $customerId,
'company' => isset($nwbAddress->Institution) ? $nwbAddress->Institution : '',
'department' => isset($nwbAddress->Department) ? $nwbAddress->Department : '',
'countryId' => $nwbAddress->Country_id,
'salutationId' => $salutationId,
'firstName' => $nwbAddress->Firstname,
'lastName' => $nwbAddress->Name,
'zipcode' => $nwbAddress->Postalcode,
'city' => $nwbAddress->City,
'street' => $street . ' ' . $streetNumber,
'phoneNumber' => $phoneNr,
'customFields' => [
'custom_address_attributs_nwb_address_id' => $nwbAddress->ID,
'acris_separate_street_address_street' => $street,
'acris_separate_street_address_house_number' => $streetNumber,
'iban' => isset($nwbAddress->IBAN) ? $nwbAddress->IBAN : '',
'account_holder' => isset($nwbAddress->AccountHolder) ? $nwbAddress->AccountHolder : '',
],
];
if ($nwbAddress->Type == 0) {
$address['customFields']['nwb_address_is_billing'] = true;
}
return $address;
}
public function onPageLoaded(GenericPageLoadedEvent $event)
{
$nwbService = $event->getSalesChannelContext()->getSalesChannel()->getCustomFields()['bis_url'];
if (
$event->getSalesChannelContext()->getCustomer() != null &&
(
(
isset($_SERVER['HTTP_REFERER']) &&
str_contains($_SERVER['HTTP_REFERER'], $nwbService)
) ||
(
isset($_SESSION['GET_ADDRESSES']) && !str_contains($_SERVER['REQUEST_URI'], '/checkout/finish')
)
)
) {
$customer = $this->helperService->getCustomerWithId(
$event->getContext(),
$event->getSalesChannelContext()->getCustomer()->getId()
);
$nwbAccountId = isset($customer->getCustomFields()['custom_customer_attributes_account_id'])
? $customer->getCustomFields()['custom_customer_attributes_account_id']
: null;
$nwbSessionId = isset($customer->getCustomFields()['custom_customer_attributes_session_id'])
? $customer->getCustomFields()['custom_customer_attributes_session_id']
: null;
$addressGroupId = $_SESSION['addressGroupId'] ?? null;
$nwbAddresses = null;
if ($addressGroupId != null) {
$nwbAddresses = $this->getNwbGuestAddresses($_SESSION['addressGroupId'], $nwbService);
}
if ($nwbAccountId) {
$nwbAddresses = $this->getNwbAddresses($nwbAccountId, $nwbSessionId, $nwbService);
}
if ($nwbAddresses != null) {
$swAddresses = $this->helperService->getCustomerAddresses($customer->getId(), $event->getContext());
$addressStatus = $this->getAddressState($swAddresses, $nwbAddresses);
foreach ($addressStatus->update as $nwbAddressId => $swAddress) {
$toUpdateNwbAddress = null;
foreach ($nwbAddresses->Addresses as $nwbAddress) {
if ($nwbAddressId == $nwbAddress->ID) {
$toUpdateNwbAddress = $nwbAddress;
}
}
$convertedAddress = $this->convertNwbAddressToSwAddress($toUpdateNwbAddress, $customer->getId(), $event->getContext());
$this->helperService->updateCustomerAddress($swAddress->getId(), $convertedAddress, $event->getContext());
}
foreach ($addressStatus->add as $nwbAddressId => $nwbAddress) {
$convertedAddress = $this->convertNwbAddressToSwAddress($nwbAddress, $customer->getId(), $event->getContext());
$this->helperService->addCustomerAddress($convertedAddress, $event->getContext());
}
if ($nwbSessionId) {
$swAddresses = $this->helperService->getCustomerAddresses($customer->getId(), $event->getContext());
$nwbAddressIdForDefaultBillingAddress = null;
$nwbAddressIdForDefaultShippingAddress = null;
$nwbShippingAddresses = [];
foreach ($nwbAddresses->Addresses as $nwbAddress) {
if ($nwbAddress->Type == 1) {
if ( $nwbAddress->IsDefaultAddress && is_null($nwbAddressIdForDefaultShippingAddress) ) {
$nwbAddressIdForDefaultShippingAddress = $nwbAddress->ID;
}
if ( isset($_GET['addressId']) && $_GET['addressId'] == $nwbAddress->ID ) {
$nwbAddressIdForDefaultShippingAddress = $nwbAddress->ID;
}
$nwbShippingAddresses[] = $nwbAddress;
}
if ($nwbAddress->Type == 0 /*&& $nwbAddress->IsDefaultAddress*/) {
$nwbAddressIdForDefaultBillingAddress = $nwbAddress->ID;
}
}
if ($nwbAddressIdForDefaultShippingAddress == null) {
$nwbAddressIdForDefaultShippingAddress = array_shift($nwbShippingAddresses);
if($nwbAddressIdForDefaultShippingAddress == null){
$nwbAddressIdForDefaultShippingAddress = $nwbAddressIdForDefaultBillingAddress;
}
}
foreach ($swAddresses as $swAddress) {
if ($swAddress->getCustomFields()['custom_address_attributs_nwb_address_id'] == $nwbAddressIdForDefaultBillingAddress) {
$paymentId = $this->helperService->getPaymentMethodIdByName('Kauf auf Rechnung', $event->getContext());
$this->helperService->updateCustomer(
$customer->getId(),
[
'defaultBillingAddressId' => $swAddress->getId(),
'defaultPaymentMethodId' => $paymentId
],
$event->getContext()
);
}
if (
$nwbAddressIdForDefaultShippingAddress != null &&
$swAddress->getCustomFields()['custom_address_attributs_nwb_address_id'] == $nwbAddressIdForDefaultShippingAddress
) {
$this->helperService->updateCustomer(
$customer->getId(),
['defaultShippingAddressId' => $swAddress->getId()],
$event->getContext()
);
}
}
}
foreach ($addressStatus->delete as $swId => $swAddress) {
$this->helperService->deleteCustomerAddress($swId, $event->getContext());
}
}
if(isset($_SESSION['GET_ADDRESSES'])){
unset($_SESSION['GET_ADDRESSES']);
}
header('Refresh: 0');
die();
}
}
}