<?php

namespace FiloBlu\ActiveCampaign\Model\Entity\Import;

use FiloBlu\ActiveCampaign\Api\Data\JobsInterface;
use FiloBlu\ActiveCampaign\Api\Data\JobsInterfaceFactory;
use FiloBlu\ActiveCampaign\Api\JobsRepositoryInterface;
use FiloBlu\ActiveCampaign\Helper\Data;
use FiloBlu\ActiveCampaign\Model\Config\Source\DirectionType;
use FiloBlu\ActiveCampaign\Model\Config\Source\EntityType;
use FiloBlu\ActiveCampaign\Model\Config\Source\JobStatus;
use Magento\Framework\App\ResourceConnection;
use Magento\Newsletter\Model\SubscriberFactory as MagentoSubscriber;
use Magento\Setup\Exception;
use Magento\Newsletter\Model\Subscriber as MSubscriber;

/**
 * Class Subscriber
 * @package FiloBlu\ActiveCampaign\Model\Entity\Import
 */
class Subscriber extends AbstractEntityImport {
    /**
     * @var MagentoSubscriber
     */
    protected $subscriber;
    /**
     * @var string
     */
    protected $entity = EntityType::ENTITY_SUBSCRIBER;
    /**
     * @var string
     */
    protected $direction = DirectionType::DIRECTION_IMPORT;

    /**
     * Subscriber constructor.
     * @param ResourceConnection $resourceConnection
     * @param Data $helperData
     * @param JobsRepositoryInterface $jobsRepository
     * @param JobsInterfaceFactory $jobsFactory
     * @param MagentoSubscriber $subscriber
     */
    public function __construct(
        ResourceConnection $resourceConnection,
        Data $helperData,
        JobsRepositoryInterface $jobsRepository,
        JobsInterfaceFactory $jobsFactory,
        MagentoSubscriber $subscriber
    )
    {
        parent::__construct($resourceConnection, $helperData, $jobsRepository, $jobsFactory);
        $this->subscriber = $subscriber;
    }

    /**
     * @param $job
     */
    public function executeProcess($job) {
        if(!$this->helperData->isUnsubscriberWebhookEnabled()) {
            $this->jobsRepository->setStatus($this->options,$job['entity_id'],JobStatus::JOB_STATUS_SKIPPED,'The unsubscribe webhook is not active');
            return false;
        }
        $subscriber = $this->subscriber->create()->load($job['entity_id']);
        $data = $this->helperData->serializer->unserialize($job['request']);
        if($data['type']=='unsubscribe' && trim(strtolower($data['contact']['email'])) == trim(strtolower($subscriber->getEmail()))){
            $response = [
                'initial_status' => (int)$subscriber->getSubscriberStatus(),
                'final_status' => MSubscriber::STATUS_UNSUBSCRIBED,
                'processed_at' => date('Y-m-d H:i:s')
            ];
            if ($subscriber->getSubscriberStatus() != MSubscriber::STATUS_UNSUBSCRIBED) {
                $subscriber->setSubscriberStatus(MSubscriber::STATUS_UNSUBSCRIBED)->save();
            }
            $this->jobsRepository->updateJobs([JobsInterface::RESPONSE => $this->helperData->serializer->serialize($response)],'id = "'.$job['id'].'"');
            return true;
        }
        throw new Exception("There was an error with payload");
        return false;
    }

}
