<?php

namespace Drupal\materio_mailjet\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\simplenews_mailjet_subscriptions\Entity\SimplenewsMailjetSubscriptionEntity;
use Drupal\simplenews\Entity\Subscriber;
use Drupal\simplenews\Subscription\SubscriptionManagerInterface;

/**
 * Module callback Controller.
 */
class MaterioMailjetWebhookCallbackController extends ControllerBase {

  /**
   * The subscription manager.
   *
   * @var \Drupal\simplenews\Subscription\SubscriptionManagerInterface
   */
  protected $subscriptionManager;

  /**
   * Constructs a \Drupal\simplenews\Controller\ConfirmationController object.
   *
   * @param \Drupal\simplenews\Subscription\SubscriptionManagerInterface $subscription_manager
   *   The subscription manager service.
   */
  public function __construct(SubscriptionManagerInterface $subscription_manager) {
    $this->subscriptionManager = $subscription_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('simplenews.subscription_manager')
    );
  }

  /**
   * Callback for uninstall the module.
   */
  public function callback() {
    
    // No Event sent.
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
      print 'No data';
      // return false;
    }

    $post = trim(file_get_contents('php://input'));

    $this->getLogger('materio_mailjet')->notice(print_r($post, TRUE));

    $event = json_decode($post);

    // $event = $json_post[0];
    
    // No information sent with the Event.
    if (!is_object($event) && !isset($event)) {
      $this->getLogger('materio_mailjet')
        ->error('No Informations sent with the Event.');
      // return false;
    }

    switch ($event->event) {
      case 'unsub':
        $this->unsub($event);
        break;
    };

    return [];
  }

  private function unsub($event) {
    // \Drupal::logger('simplenews_mailjet_subscriptions')->info("Unsubscribe webhook triggered");
    
    $MjlistID = $event->mj_list_id;
    $email = $event->email;

    // find corresponding simplenews list from mailjet listID    
    $newsletter_id = null;
    $entities = SimplenewsMailjetSubscriptionEntity::loadMultiple();
    foreach ((array) $entities as $entity) {
      $listID = (int)$entity->getID();
      if ($listID === $MjlistID) {
        $table = $entity->get('mapping_table');
        if (is_array($table)) {
          foreach ($table as $category) {
            $newsletter_id = $category['simplenews_news'];
            break;
          }
        }    
        break;
      }
    }

    // \Drupal::logger('simplenews_mailjet_subscriptions')->info("Unsubscribe webhook triggered for listID: " . $listID . "and email: " . $email . ".");

    // get subscriber entity
    // Load entities by their property values.
    $subscribers = \Drupal::entityTypeManager()->getStorage('simplenews_subscriber')->loadByProperties(['mail' => $email]);

    // unsubscribe subscriber from simplenews list
    if (is_array($subscribers) && count($subscribers) && $newsletter_id) {
      $subscriber = array_shift($subscribers);
      if ($subscriber instanceof Subscriber) {
        // $subscriber->unsubscribe($simplenews_news, 'mailjet');
        $this->subscriptionManager->unsubscribe($subscriber->getMail(), $newsletter_id, FALSE, 'materio_mailjet');
      }
    }
  }

}
