<?php

namespace FiloBlu\ActiveCampaign\Observer;

use FiloBlu\ActiveCampaign\Api\Data\JobsInterface;
use FiloBlu\ActiveCampaign\Model\Config\Source\DirectionType;
use FiloBlu\ActiveCampaign\Model\Config\Source\EntityType;
use Magento\Framework\Event\Observer;

class CustomerSave extends AbstractObserver
{

    /**
     * @var string
     */
    protected $entity = EntityType::ENTITY_CUSTOMER;

    /**
     * @param Observer $observer
     */
    public function execute(Observer $observer)
    {
        $entityId = $observer->getData($this->entity)->getId();

        // IF MODULE IS ENABLED
        if(!$this->helperData->isEnabled()){
            return;
        }
        // IF OBSERVER IS ENABLED
        if (!$this->helperData->isObserverEnabled()) {
            return;
        }
        // IF CUSTOMER EXPORT ENABLED
        if (!$this->helperData->isCustomerEnabled()) {
            return;
        }
        // FILTER ENABLED STORES
        $customerStoreId = $observer->getData($this->entity)->getStoreId();
        if (!in_array($customerStoreId, explode(',', $this->helperData->getEnabledStoreViews()))) {
            return;
        }
        // AND observer enabled for every save customer
        if (!$this->helperData->isCustomerSaveObserverEnabled()) {
            if($this->jobsRepository->checkIfExist([
                JobsInterface::DIRECTION => DirectionType::DIRECTION_EXPORT,
                JobsInterface::ENTITY => EntityType::ENTITY_CUSTOMER,
                JobsInterface::ENTITY_ID => $entityId
            ])) {
                return;
            }
        }

        $this->writeJob($entityId);
    }

}
