<?php

namespace FiloBlu\ActiveCampaign\Handler;

use FiloBlu\ActiveCampaign\Helper\Data;
use FiloBlu\ActiveCampaign\Model\Entity\Export\Subscriber;
use FiloBlu\ConsentsManager\Model\ConsentTypeRepository;
use FiloBlu\ActiveCampaign\Helper\ConsentsProfilingHelper;
use Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use Psr\Log\LoggerInterface;

class ConsentsSubscriptionHandler
{
    /**
     * @var Subscriber
     */
    protected $subscriberExportModel;
    /**
     * @var CollectionFactory
     */
    private $subscriberCollectionFactory;
    /**
     * @var SubscriberFactory
     */
    private $subscriberFactory;
    /**
     * @var ConsentsProfilingHelper
     */
    private $consentsProfilingHelper;
    /**
     * @var LoggerInterface
     */
    private $logger;
    /**
     * @var OrderCollectionFactory
     */
    private $orderCollectionFactory;
    /**
     * @var ConsentTypeRepository
     */
    private $consentTypeRepository;
    /**
     * @var Data
     */
    private $helper;

    /**
     * @param Subscriber $subscriberExportModel
     * @param CollectionFactory $subscriberCollectionFactory
     * @param SubscriberFactory $subscriberFactory
     * @param ConsentsProfilingHelper $consentsProfilingHelper
     * @param LoggerInterface $logger
     * @param OrderCollectionFactory $orderCollectionFactory
     * @param ConsentTypeRepository $consentTypeRepository
     * @param Data $helper
     */
    public function __construct(
        Subscriber $subscriberExportModel,
        CollectionFactory $subscriberCollectionFactory,
        SubscriberFactory $subscriberFactory,
        ConsentsProfilingHelper $consentsProfilingHelper,
        LoggerInterface $logger,
        OrderCollectionFactory $orderCollectionFactory,
        ConsentTypeRepository $consentTypeRepository,
        Data $helper
    )
    {
        $this->subscriberExportModel = $subscriberExportModel;
        $this->subscriberCollectionFactory = $subscriberCollectionFactory;
        $this->subscriberFactory = $subscriberFactory;
        $this->consentsProfilingHelper = $consentsProfilingHelper;
        $this->logger = $logger;
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->consentTypeRepository = $consentTypeRepository;
        $this->helper = $helper;
    }

    public function sendSubscriberData($email, $profileTypeId, $storeId = null)
    {
        $subscriberCollection = $this->subscriberCollectionFactory->create();
        $subscriberCollection->addFieldToFilter('subscriber_email', ['eq' => $email]);

        /** @var $subscriber \Magento\Newsletter\Model\Subscriber */
        $subscriber = $subscriberCollection->getFirstItem();

        $this->logger->debug('after consent subscription');

        //OnlyProfile
        if (!$subscriber->getSubscriberId()) {

            $job = $this->buildData($email, $profileTypeId, $storeId);

            $this->subscriberExportModel->executeProcess($job);
        }
    }

    public function buildData($email, $profileTypeId, $storeId)
    {
        $customer = $this->consentsProfilingHelper->getCustomerByEmail($email);

        $firstname = $customer->getFirstname() ?: null;
        $lastname = $customer->getLastname() ?: null;
        if (empty($storeId)) {
            $storeId = $customer->getStoreId() ?: null;
        }
        $customerId = $customer->getId() ?: null;
        $websiteId = $customer->getWebsiteId() ?: null;

        $order = $this->helper->getEmailLastOrder($email);

        $source = "REGISTRATION";

        if ($order && $order->getId()) {

            $source = "CHECKOUT";

            if (!$storeId) {
                $storeId = $order->getStoreId();
            }

            if (!$firstname) {
                $firstname = $order->getCustomerFirstname();
            }

            if (!$lastname) {
                $lastname = $order->getCustomerLastname();
            }

            if (!$order->getCustomerIsGuest()) {
                $customerId = $order->getCustomerId();
            }

            if (!$websiteId) {
                $websiteId = $order->getStore()->getWebsiteId();
            }

        }

        $data = [
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'direction' => 'export',
            'entity' => 'subscriber',
            'type' => 'rest',
            'log' => '',
            'request' => '',
            'response' => '',
            'status' => 'waiting',
            'profile_type_id' => $profileTypeId,
            'order' => $order,
            'website_id' => $websiteId
        ];

        /*
         * Request example:
         * {"create_update_contact":{"request":{"contact":{"email":"ciro.perna+dipeppe@filoblu.com","firstName":"Ciro","lastName":"Perna","fieldValues":[{"field":"3","value":"it_IT"},{"field":"1","value":"IT"},{"field":"10","value":"CUSTOMER"},{"field":"9","value":"REGISTRATION"},{"field":"45","value":"TRUE"}]}}},"list_subscription":{"request":{"contactList":{"contact":"168722"}}}}
         */

        return [
            'customer_id' => $customerId,
            'email' => $email,
            'store_id' => $storeId,
            'firstname' => $firstname,
            'lastname' => $lastname,
            'source' => $source,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'profile_type_id' => $profileTypeId,
            'order' => $order,
            'website_id' => $websiteId
        ];
    }
}
