<?php

namespace MNM\Spitzner\Plugin\Customer\Api;

use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\Data\AddressInterface;
use Magento\Framework\Message\ManagerInterface;
use Psr\Log\LoggerInterface;

class AddressRepositoryPlugin
{
    /** @var LoggerInterface  */
    private $logger;

    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    public function __construct(LoggerInterface $logger, ManagerInterface $messageManager)
    {
        $this->logger = $logger;
        $this->messageManager = $messageManager;
    }

    public function beforeSave(AddressRepositoryInterface $subject, AddressInterface $address)
    {
//MNM - add check if custom attribute exists
        $repertus_address_type = $address->getCustomAttribute('repertus_address_type')
                                    ? (int)$address->getCustomAttribute('repertus_address_type')->getValue()
                                    : null;
        $repertus_post_number = $address->getCustomAttribute('repertus_post_number')
                                    ? $address->getCustomAttribute('repertus_post_number')->getValue()
                                    : null;
        $repertus_number = $address->getCustomAttribute('repertus_number')
                            ? $address->getCustomAttribute('repertus_number')->getValue()
                            : null;

        $this->logger->debug(__METHOD__, [
            'type' => $repertus_address_type,
            'post_number' => $repertus_post_number,
            'number' => $repertus_number,
        ]);
//MNM

        $repertusAddressType = $address->getCustomAttribute('repertus_address_type') ? (int)$address->getCustomAttribute('repertus_address_type')->getValue() : 0;


        if ($repertusAddressType != 0 && $address->isDefaultBilling()) {
            $this->logger->debug('Unset defaultBilling cause address is a Packstation or Post Office');

            $address->setIsDefaultBilling(false);
            $this->messageManager->addNoticeMessage(__('Packstation or Post office can not be saved as billing address.'));
        }
        // TODO: [mka, 11.03.2020] reset postnumber and number for address
    }
}
