<?php

namespace FiloBlu\Flow\Model\Actions\From;


use Magento\Framework\App\ObjectManager;
use Magento\Newsletter\Model\Subscriber;
use Magento\Newsletter\Model\SubscriberFactory;

/**
 * Class SubscribeNewsletter
 * @package FiloBlu\Flow\Model\Actions\From
 * @input json_data -> {"subscribed":true,"date":"2021-05-21 07:13:17"}
 */
class Subscribenewsletter
{

    protected $subscriberFactory;
    protected $subscriberModel;

    public function __construct(
        SubscriberFactory $subscriberFactory,
        Subscriber $subscriberModel
    ) {
        $this->subscriberFactory = $subscriberFactory;
        $this->subscriberModel = $subscriberModel;
    }

    /**
     * @param $customer
     * @param $json_data
     * @param $storeId
     * @return bool
     */
    public function process($customer, $json_data, $storeId)
    {
        $json_decoded = json_decode($json_data, true);
        if (!$json_decoded) {
            return false;
        }
        $subscribed = $json_decoded['subscribed'] ?? null;
        $date = $json_decoded['date'] ?? '01-01-1980 00:00:01';

        if ($subscribed === null || !$customer->getEmail()) {
            return false;
        }
        $status = $subscribed ? Subscriber::STATUS_SUBSCRIBED : Subscriber::STATUS_UNSUBSCRIBED;

        // This will give me always the same $subscriber
        //$subscriber = $this->subscriberModel->loadByEmail($customer->getEmail());

        $objectManager = ObjectManager::getInstance();
        $subscriberModelNewInstance = $objectManager->create('Magento\Newsletter\Model\Subscriber');
        $subscriber = $subscriberModelNewInstance->loadByEmail($customer->getEmail());

        if (!$subscriber->getSubscriberId()) {
            // Then this is a create
            $subscriber->setEmail($customer->getEmail());
            $subscriber->setCustomerId($customer->getId());
            $subscriber->setStoreId($customer->getStoreId());
            $subscriber->setStatus($status);
            $subscriber->save();
            return true;
        }

        $last_update = $subscriber->getChangeStatusAt();
        $current_status = $subscriber->getStatus();

        if (!$subscriber->getCustomerId()) {
            $subscriber->setCustomerId($customer->getId());
        }

        if ($last_update > $date) {
            # Magento database info is more recent, just execute a save to trigger esb
            $subscriber->save();
            return true;
        }

        if ($current_status != $status) {
            $subscriber->setStatus($status);
        }

        $subscriber->save();
        return true;
    }

}
