<?php

namespace FiloBlu\ActiveCampaign\Controller\Webhook;

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 FiloBlu\ActiveCampaign\Model\Config\Source\Type;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Controller\Result\JsonFactory;

/**
 * Class BaseUnsubscribe
 * @package FiloBlu\ActiveCampaign\Controller\Webhook
 */
class BaseUnsubscribe implements ActionInterface
{
    /**
     * @var Data
     */
    protected $helperData;
    /**
     * @var JobsRepositoryInterface
     */
    protected $jobsRepository;
    /**
     * @var JobsInterfaceFactory
     */
    protected $jobsFactory;
    /**
     * @var ResourceConnection
     */
    protected $resourceConnection;
    /**
     * @var RequestInterface
     */
    protected $request;
    /**
     * @var ResultInterfaceFactory
     */
    protected $resultInterfaceFactory;

    /**
     * Unsubscribe constructor.
     * @param Data $helperData
     * @param JobsRepositoryInterface $jobsRepository
     * @param JobsInterfaceFactory $jobsFactory
     * @param ResourceConnection $resourceConnection
     * @param RequestInterface $request
     * @param JsonFactory $resultInterfaceFactory
     */
    public function __construct(
        Data $helperData,
        JobsRepositoryInterface $jobsRepository,
        JobsInterfaceFactory $jobsFactory,
        ResourceConnection $resourceConnection,
        RequestInterface $request,
        JsonFactory $resultInterfaceFactory
    ) {
        $this->helperData = $helperData;
        $this->jobsRepository = $jobsRepository;
        $this->jobsFactory = $jobsFactory;
        $this->resourceConnection = $resourceConnection;
        $this->request = $request;
        $this->resultInterfaceFactory = $resultInterfaceFactory;
    }

    /**
     * @return bool
     */
    public function execute()
    {
        if (!$this->helperData->isUnsubscriberWebhookEnabled()) {
            return $this->resultInterfaceFactory->create()->setData(['result' => false]);
        }
        $code = $this->request->getParam('code');
        //if code is ok
        if (!$this->helperData->checkWebhookCode($code)) {
            return $this->resultInterfaceFactory->create()->setData(['result' => false]);
        }
        $post = $this->request->getPost();
        if (count($post)) {
            if (!isset($post['contact']['email']) || empty($post['contact']['email'])) {
                return $this->resultInterfaceFactory->create()->setData(['result' => false]);
            }
            $subscribers = $this->getSubscriberIdsByEmail($post['contact']['email']);
            if (count($subscribers) == 0) {
                return $this->resultInterfaceFactory->create()->setData(['result' => false]);
            }
            foreach ($subscribers as $subscriber) {
                $job = $this->jobsFactory->create();
                $job->setEntity(EntityType::ENTITY_SUBSCRIBER)->setEntityId($subscriber)->setDirection(
                        DirectionType::DIRECTION_IMPORT
                    )->setType(Type::TYPE_REST)->setStatus(JobStatus::JOB_STATUS_WAITING)->setRequest(
                        $this->helperData->serializer->serialize($post)
                    );
                $this->jobsRepository->saveWithRequest($job);
            }
            return $this->resultInterfaceFactory->create()->setData(['result' => true]);
        }
        return $this->resultInterfaceFactory->create()->setData(['result' => false]);
    }

    /**
     * @param $email
     * @return array
     */
    public function getSubscriberIdsByEmail($email)
    {
        $connection = $this->resourceConnection->getConnection();
        $tableName = $this->resourceConnection->getTableName('newsletter_subscriber');
        $sql = "SELECT subscriber_id FROM {$tableName} WHERE subscriber_email = ?";

        return $connection->fetchCol($sql, [trim(strtolower($email))]);
    }

    /**
     * @return RequestInterface
     */
    public function getRequest()
    {
        return $this->request;
    }
}


