<?php


namespace Magetop\Advancepreview\Observer\Adminhtml;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class AfterSaveCustomer implements ObserverInterface
{
    protected $customerFactory;
    protected $resCustomerFactory;
    public function __construct(
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Model\ResourceModel\CustomerFactory $resCustomerFactory
    )
    {
        $this->customerFactory = $customerFactory;
        $this->resCustomerFactory = $resCustomerFactory;
    }

    public function execute(Observer $observer)
    {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/adm_customer_save.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);

       try {
           /** @var \Magento\Customer\Model\Data\Customer $customerData */
           $customerData = $observer->getData('customer');
           $group = $customerData->getGroupId();
           $cusomerId = $customerData->getId();
           $customer = $this->customerFactory->create()->load($cusomerId);
           $dataCustomer = $customer->getDataModel();
           if($group != 2) {
               $dataCustomer->setTaxvat('');
               $customer->updateData($dataCustomer);
               $customerRes = $this->resCustomerFactory->create();
               $customerRes->save($customer);
               $logger->info('Update Ok '. $dataCustomer->getTaxvat(). ' -> '. $cusomerId);
           }
       }
       catch (\Exception $exception) {
           $logger->info('Update error '. $exception->getMessage());
       }

    }
}
