<?php
namespace App\Service;
use App\Entity\Session;
use App\Entity\UserPlacementTest;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\SubscriptionOrder;
use App\Entity\SessionOrder;
use App\Entity\ActiveCampainUnsubscribeLog;
use App\Entity\ActiveCampainSubscribeLostLog;
use App\Repository\SubscriptionOrderRepository;
use App\Repository\SessionOrderRepository;
use TestMonitor\ActiveCampaign\Resources\Contact;
use TestMonitor\ActiveCampaign\Resources\CustomField;
class ActiveCampaignHelper
{
protected $container;
protected $em;
private $activeCampaign;
private $Activecampaign_url;
private $subscriptionOrderRepository;
private $sessionOrderRepository;
const ID_LIST_SUBSCRIBE_PRIVATE = 168; // List : élèves actuels = 168
const ID_LIST_SUBSCRIBE_GROUP = 169; // List : élèves Cours collectif = 169
const ID_LIST_UNSUBSCRIBE_PRIVATE = 140; // List : Anciens élèves = 140
const ID_LIST_UNSUBSCRIBE_GROUP = 167; // list : Anciens étudiants collectifs = 167
public function __construct(Container $container, EntityManagerInterface $entityManager, SubscriptionOrderRepository $subscriptionOrderRepository, SessionOrderRepository $sessionOrderRepository)
{
$this->container = $container;
$this->em = $entityManager;
$Activecampaign_url = $this->container->getParameter('ACTIVECAMPAIGN_URL');
$Activecampaign_api_key = $this->container->getParameter('ACTIVECAMPAIGN_API_KEY');
$activeCampaign = new ActiveCampaignApi($Activecampaign_url, $Activecampaign_api_key);
$this->activeCampaign = $activeCampaign;
$this->Activecampaign_url = $Activecampaign_url;
$this->subscriptionOrderRepository = $subscriptionOrderRepository;
$this->sessionOrderRepository = $sessionOrderRepository;
}
public function getAllListsByName($name)
{
$data = [];
$res = $this->activeCampaign->findListByLimit($name, 50);
return $res;
}
public function getAllListsChoiceField()
{
$data = [];
$res = $this->getAllListsByName('lists');
foreach ($res as $e) {
$data[$e->name] = $e->id;
}
return $data;
}
public function getAllTagsChoiceField()
{
$data = [];
$res = $this->getAllListsByName('tags');
//var_dump($res);
foreach ($res as $e) {
$data[$e->tag] = $e->tag;
}
return $data;
}
public function getOrCreateContact($order)
{
$contact = null;
if (
$order != null
) {
$lastName = "";
$firstName = "";
$email = "";
$phone = "";
$participant = null;
$user = null;
if ($order instanceof SubscriptionOrder) {
$participant = $order->getParticipant();
$user = $order->getUser();
}
if ($order instanceof SessionOrder) {
$participant = $order->getParticipant();
$user = $order->getStudents();
}
if ($order instanceof UserPlacementTest) {
$participant = $order->getParticipant();
$user = $order->getUser();
}
if ($user != null) {
$lastName = $user->getLastName();
$firstName = $user->getFirstName();
$email = $user->getEmail();
if ($participant != null && $participant->getLastName() != "" && $participant->getFirstName() != "") {
$lastName = $participant->getLastName();
$firstName = $participant->getFirstName();
}
$phone = "";
}
// Find or create a contact.
$contact = $this->activeCampaign->findOrCreateContact($email, $firstName, $lastName, $phone);
}
return $contact;
}
// Get Lists ID & TAGS to subscribe or unnsubscribe
public function getListsAndTags($order, $isUnsubscribe = false)
{
$addToListPrivate = false;
$addToListGroup = false;
$lists = [];
$tags = [];
// Attacher les listes par defaut selon le type Entity
$periods = [];
$subjects = [];
if ($order instanceof SubscriptionOrder) {
// Attacher Tag language
$user = $order->getUser();
if ($user != null) {
$tagLanguage = $user->getLanguage();
// Verifier si Abonnement
if (!$isUnsubscribe)
$tags[] = $tagLanguage;
}
// Attacher Categorie Arabe or Coran
$category = $order->getCategory();
if ($category != null) {
// Remonter tag category lors de l'abonnement
$tags[] = $category->getName();
}
$subject = $order->getSubject();
if ($subject != null) {
$subjects[] = $subject->getId();
// Remonter tag subject lors de l'abonnement
$tags[] = $subject->getTagName();
}
$addToListPrivate = true;
}
if ($order instanceof SessionOrder) {
// Attacher Tag language
$user = $order->getStudents();
if ($user != null) {
$tagLanguage = $user->getLanguage();
// Verifier si Abonnement
if (!$isUnsubscribe)
$tags[] = $tagLanguage;
}
// Attacher session Exemple : juillet2021
$session = $order->getSession();
if ($session != null) {
// Remonter Period subject lors de l'abonnement
$tags[] = $session->getPeriod();
$periods[] = $session->getPeriod();
// Attacher session Exemple : Niveau 1
$level = $session->getLevel();
if ($level != null) {
// Remonter level subject lors de l'abonnement
$tags[] = $level->getName();
$subject = $level->getSubject();
if ($subject != null) {
$subjects[] = $subject->getId();
// Remonter tag subject lors de l'abonnement
$tags[] = $subject->getTagName();
}
}
}
$addToListGroup = true;
}
if ($addToListPrivate) {
$lists[] = self::ID_LIST_SUBSCRIBE_PRIVATE;
} elseif ($addToListGroup) {
$lists[] = self::ID_LIST_SUBSCRIBE_GROUP;
}
// Recuperer tous les Tags avec une requette SQL si desabonnement
if ($isUnsubscribe) {
$tags = $this->getTagsFromAllOrdersFromDB($order, $isUnsubscribe);
}
$lists = array_unique($lists);
$tags = array_unique($tags);
$res = [
"lists" => $lists,
"tags" => $tags
];
return (object) $res;
}
public function getTagsFromAllOrdersFromDB($order, $isUnsubscribe = false)
{
$tags = [];
if ($order instanceof SubscriptionOrder) {
$user = $order->getUser();
if ($user != null) {
// recuperer les tags
// Category
$field = 'category';
$tagsToAdd = $this->subscriptionOrderRepository->getTagsFromSubscriptionForUser($user, $isUnsubscribe, $field);
$tags = array_merge($tags, $tagsToAdd);
// Subject
$field = 'subject';
$tagsToAdd = $this->subscriptionOrderRepository->getTagsFromSubscriptionForUser($user, $isUnsubscribe, $field);
$tags = array_merge($tags, $tagsToAdd);
}
}
if ($order instanceof SessionOrder) {
// Attacher Tag language
$user = $order->getStudents();
if ($user != null) {
// recuperer les Tags
// Period
$field = 'period';
$tagsToAdd = $this->sessionOrderRepository->getTagsFromSessionForUser($user, $isUnsubscribe, $field);
$tags = array_merge($tags, $tagsToAdd);
// Level
$field = 'level';
$tagsToAdd = $this->sessionOrderRepository->getTagsFromSessionForUser($user, $isUnsubscribe, $field);
$tags = array_merge($tags, $tagsToAdd);
// Subject
$field = 'subject';
$tagsToAdd = $this->sessionOrderRepository->getTagsFromSessionForUser($user, $isUnsubscribe, $field);
$tags = array_merge($tags, $tagsToAdd);
}
}
return $tags;
}
public function getListsUnsubscribe($order, $unsubscribeAll = false)
{
$addToListPrivate = false;
$addToListGroup = false;
$lists = [];
// Attacher les listes par defaut
if ($order instanceof SubscriptionOrder) {
$addToListPrivate = true;
}
if ($order instanceof SessionOrder) {
$addToListGroup = true;
}
if ($unsubscribeAll) {
$lists[] = self::ID_LIST_UNSUBSCRIBE_PRIVATE;
$lists[] = self::ID_LIST_UNSUBSCRIBE_GROUP;
} else {
if ($addToListPrivate) {
$lists[] = self::ID_LIST_UNSUBSCRIBE_PRIVATE;
} elseif ($addToListGroup) {
$lists[] = self::ID_LIST_UNSUBSCRIBE_GROUP;
}
}
return $lists;
}
// Get Lists ID to subscribe
public function getListIds($listAndTags)
{
$res = $listAndTags->lists;
return $res;
}
// Get TAGS to subscribe
public function getTags($listAndTags)
{
$res = [];
$tags = $listAndTags->tags;
foreach ($tags as $t) {
if ($t != null) {
$tag = $this->activeCampaign->findTagList($t);
if ($tag != null) {
$res[] = $tag;
}
}
}
return $res;
}
/*
* Subscribe a contact to a list or unsubscribe a contact from a list.
*
* @param int $list ID of list to remove contact from
* @param int $contact ID of contact to remove from list
* @param bool $subscribe TRUE to subscribe, FALSE otherwise
*/
public function updateContactLists($listsID = [], $contactID = "", $subscribe = true)
{
foreach ($listsID as $listID) {
$this->activeCampaign->updateListStatus($listID, $contactID, $subscribe);
}
}
/*
Add Tags to contact
*/
public function addTagsToContact($tags, $contact)
{
foreach ($tags as $tag) {
//$tag = $this->activeCampaign->findTag($nameTag);
$this->activeCampaign->addTagToContact($contact, $tag);
}
return $tags;
}
/*
* Create Contact in ActiveCampain API
*/
public function addOrder($order)
{
if ($this->checkApiDown($order))
return false;
// Get Participant from SubscriptionOrder
if ($order != null) {
$this->subscribeContactToLists($order);
}
return true;
}
/*
* Subscribe contact to lists
*/
public function subscribeContactToLists($order)
{
// Cree Contact dans ActiveCampaign
$contact = $this->getOrCreateContact($order);
if ($contact != null) {
$contactID = $contact->id;
$listAndTags = $this->getListsAndTags($order);
$listsID = $this->getListIds($listAndTags);
$tags = $this->getTags($listAndTags);
$subscribe = true;
$this->updateContactLists($listsID, $contactID, $subscribe);
$this->addTagsToContact($tags, $contact);
// Unsubscribe contact in lists Archive
$listsID = $this->getListsUnsubscribe($order);
$subscribe = false;
$this->updateContactLists($listsID, $contactID, $subscribe);
}
}
/*
* Unsubscribe contact from Old Lists
*/
public function unsubscribeOrder($order)
{
// Get Participant from SubscriptionOrder
if ($order != null) {
$this->unsubscribeContactToLists($order);
}
}
public function removeTagsContact($contact, $tags)
{
foreach ($tags as $tag) {
$this->activeCampaign->removeTagFromContact($contact, $tag);
}
}
public function unsubscribeContactToLists($order)
{
// Cree Contact dans ActiveCampaign
$contact = $this->getOrCreateContact($order);
if ($contact != null) {
$contactID = $contact->id;
$isUnsubscribe = true;
$listAndTags = $this->getListsAndTags($order, $isUnsubscribe);
$listsID = $this->getListIds($listAndTags);
$tags = $this->getTags($listAndTags);
// Check if active SessionOrder or SubscriptionOrder exist
$ordersActiveExist = $this->checkOrderSActiveExist($order);
if ($ordersActiveExist) {
// Unsubscribe from Lists ( Anciens élèves , Anciens étudiants collectifs )
$listsID = $this->getListsUnsubscribe($order);
$subscribe = false;
$this->updateContactLists($listsID, $contactID, $subscribe);
} else {
// Unsubscribe from All Lists
$subscribe = false;
$this->updateContactLists($listsID, $contactID, $subscribe);
// Subscribe contact in lists Archive
$listsID = $this->getListsUnsubscribe($order);
$subscribe = true;
$this->updateContactLists($listsID, $contactID, $subscribe);
}
// Remove tags contact
$this->removeTagsContact($contact, $tags);
// add log
$this->addLogUnsubscribeLog($order);
}
}
public function checkOrderSActiveExist($order)
{
// verifier si order actif existe
$exist = false;
$nbOrders = 0;
if ($order instanceof SubscriptionOrder) {
$user = $order->getUser();
$nbOrders = $this->subscriptionOrderRepository->getNumberActiveSubscriptionForUser($user);
}
if ($order instanceof SessionOrder) {
$user = $order->getStudents();
$nbOrders = $this->sessionOrderRepository->getNumberActiveSessionsForUser($user);
}
//echo " nbOrders : $nbOrders <br> ";
if ($nbOrders > 0) {
$exist = true;
}
return $exist;
}
public function addLogUnsubscribeLog($order)
{
//Ajouter log lors de désabonemement
$ActiveCampainUnsubscribeLog = new ActiveCampainUnsubscribeLog();
if ($order instanceof SubscriptionOrder) {
$ActiveCampainUnsubscribeLog->setSubscription($order);
}
if ($order instanceof SessionOrder) {
$ActiveCampainUnsubscribeLog->setGroupSession($order);
}
$this->em->persist($ActiveCampainUnsubscribeLog);
//$this->em->flush();
}
function checkApiDown($order)
{
if (!$this->checkOnline()) {
$this->addLogSubscribeLostLog($order);
return true;
}
return false;
}
function checkOnline()
{
$domain = $this->Activecampaign_url;
$curlInit = curl_init($domain);
curl_setopt($curlInit, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curlInit, CURLOPT_HEADER, true);
curl_setopt($curlInit, CURLOPT_NOBODY, true);
curl_setopt($curlInit, CURLOPT_RETURNTRANSFER, true);
//get answer
$response = curl_exec($curlInit);
curl_close($curlInit);
if ($response) return true;
return false;
}
public function addLogSubscribeLostLog($order)
{
//Ajouter log lors de désabonemement
$activeCampainSubscribeLostLog = new ActiveCampainSubscribeLostLog();
if ($order instanceof SubscriptionOrder) {
$activeCampainSubscribeLostLog->setSubscription($order);
}
if ($order instanceof SessionOrder) {
$activeCampainSubscribeLostLog->setGroupSession($order);
}
$this->em->persist($activeCampainSubscribeLostLog);
$this->em->flush();
}
//fait par moi
public function sendTagToActiveCampaing($tag,$user,$participant)
{
if ($user != null) {
$lastName = $user->getLastName();
$firstName = $user->getFirstName();
$email = $user->getEmail();
$gender = $user->getGender()->getName();
$language = $user->getLanguage();
if ($participant != null) {
$lastName = $participant->getLastName();
$firstName = $participant->getFirstName();
$gender = $participant->getGender()->getName();
}
$phone = "";
$contact = $this->activeCampaign->updateOrCreateContact($email, $firstName, $lastName, $phone);
$tags = [$tag, $gender, $language];
$this->activeCampaign->addTagsToContact($contact, $tags);
return true;
}
return false;
}
/**
* @param SessionOrder $order
*/
function removeOrder($order){
$contact = $this->getOrCreateContact($order);
if ($contact != null) {
$contactID = $contact->id;
$listAndTags = $this->getListsAndTags($order);
$listsID = $this->getListIds($listAndTags);
$tags = $this->getTags($listAndTags);
$period = $order->getSession()->getPeriod();
$level = $order->getSession()->getLevel();
$subject = $level->getSubject();
// Get other sessions info
$otherSessionsInfo = ['period' => 0, 'level' => 0, 'subject' => 0];
foreach ($order->getStudents()->getSessionOrder() as $sessionOrder){
if($sessionOrder->getIsActif()){
if($sessionOrder->getSession()->getPeriod() == $period){
$otherSessionsInfo['period']++;
}
if($sessionOrder->getSession()->getLevel() == $level){
$otherSessionsInfo['level']++;
}
if($sessionOrder->getSession()->getLevel()->getSubject() == $subject){
$otherSessionsInfo['subject']++;
}
}
}
foreach ($tags as $key => $tag) {
if ($order->getSession()->getPeriod() == $tag->tag && $otherSessionsInfo['period'] == 0) {
$this->activeCampaign->removeTagFromContact($contact, $tag);
}
if ($order->getSession()->getLevel()->getName() == $tag->tag && $otherSessionsInfo['level'] == 0) {
$this->activeCampaign->removeTagFromContact($contact, $tag);
}
if ($order->getSession()->getLevel()->getSubject() == $tag->tag && $otherSessionsInfo['subject'] == 0) {
$this->activeCampaign->removeTagFromContact($contact, $tag);
}
}
$this->updateContactLists($listsID, $contactID, false);
}
}
public function updateCustomFieldLastLevelTestForContact($contactEmail, Session $session) {
$fieldID = null;
$fieldDateID = null;
switch ($session->getLevel()->getSubject()->getId()) {
case 1:
$fieldID = "Last Level AL KAAMIL"; //8;
$fieldDateID = "Last Level AL KAAMIL DATE"; //13;
break;
case 33:
$fieldID = "Last Level TAKALLAM"; //6;
$fieldDateID = "Last Level TAKALLAM DATE"; //14;
break;
}
$value = $session->getLevel()->getLevel();
if($fieldID !== null) {
$contact = $this->activeCampaign->findContact($contactEmail);
if ($contact instanceof Contact) {
$customField = $this->activeCampaign->findCustomField($fieldID);
if ($customField instanceof CustomField) {
$this->activeCampaign->addCustomFieldToContact($contact, $customField, $value);
}
$customFieldDate = $this->activeCampaign->findCustomField($fieldDateID);
if ($customFieldDate instanceof CustomField) {
$this->activeCampaign->addCustomFieldToContact($contact, $customFieldDate, date('d/m/Y'));
}
}
}
}
public function updateCustomFieldLastTestResultForContact($contactEmail, UserPlacementTest $userPlacementTest) {
$fieldID = null;
$fieldDateID = null;
switch ($userPlacementTest->getSubject()->getId()) {
case 1:
$fieldID = "Level Test Result AL KAAMIL";// 7;
$fieldDateID = "Last Level Test Result AL KAAMIL DATE"; //11;
break;
case 33:
$fieldID = "Level Test Result TAKALLAM"; // 9;
$fieldDateID = "Last Level Test Result TAKALLAM DATE"; //12;
break;
}
if($fieldID !== null) {
$contact = $this->activeCampaign->findContact($contactEmail);
if ($contact instanceof Contact) {
$customField = $this->activeCampaign->findCustomField($fieldID);
if ($customField instanceof CustomField) {
$this->activeCampaign->addCustomFieldToContact($contact, $customField, $userPlacementTest->getTestResult()->getLevel());
}
$customFieldDate = $this->activeCampaign->findCustomField($fieldDateID);
if ($customFieldDate instanceof CustomField) {
$this->activeCampaign->addCustomFieldToContact($contact, $customFieldDate, date('d/m/Y'));
}
}
}
}
}