src/Services/Common.php line 79

Open in your IDE?
  1. <?php
  2. namespace App\Services;
  3. use App\Config;
  4. use App\Entity\AdjustAppDetails;
  5. use App\Entity\AdvertiserAccountManager;
  6. use App\Entity\AdvertiserInfo;
  7. use App\Entity\AdvertiserTagRelationship;
  8. use App\Entity\AffiliateAccountManager;
  9. use App\Entity\AffiliateInfo;
  10. use App\Entity\AffiliateOfferApproval;
  11. use App\Entity\AffiliateOfferBlockLogs;
  12. use App\Entity\AffiliateTagRelationship;
  13. use App\Entity\MafoAffiliates;
  14. use App\Entity\AlertMeta;
  15. use App\Entity\AppInfo;
  16. use App\Entity\CommandLogger;
  17. use App\Entity\DeductionControl;
  18. use App\Entity\Employees;
  19. use App\Entity\MafoUserNotifications;
  20. use App\Entity\MmpAdvertisers;
  21. use App\Entity\MmpMobileApps;
  22. use App\Entity\ObjectMappingWithTuneWebAccount;
  23. use App\Entity\OfferCategories;
  24. use App\Entity\OfferCategoryRelationship;
  25. use App\Entity\OfferCreativeFile;
  26. use App\Entity\OfferGeoRelationship;
  27. use App\Entity\OfferGoalsInfo;
  28. use App\Entity\OfferInfo;
  29. use App\Entity\OfferTagRelationship;
  30. use App\Entity\OfferWhitelist;
  31. use App\Entity\SkadNetworkApiLogs;
  32. use App\Entity\SkadNetworkManualPostbackMapping;
  33. use App\Entity\SkadNetworkPostbackLogs;
  34. use App\Entity\Tag;
  35. use App\Entity\UserApiKey;
  36. use App\Entity\Users;
  37. use App\Entity\MafoAdvertisers;
  38. use App\Entity\MafoOffers;
  39. use App\Repository\AdvertiserAccountManagerRepository;
  40. use Aws\Credentials\Credentials;
  41. use Aws\S3\Exception\S3Exception;
  42. use Aws\Exception\MultipartUploadException;
  43. use Aws\S3\MultipartUploader;
  44. use Aws\S3\ObjectUploader;
  45. use Aws\S3\S3Client;
  46. use Doctrine\ORM\EntityManagerInterface;
  47. use PhpOffice\PhpSpreadsheet\IOFactory;
  48. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  49. use Psr\Log\LoggerInterface;
  50. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  51. use Symfony\Component\Mercure\HubInterface;
  52. use Symfony\Component\Mercure\Update;
  53. use Twig\Environment;
  54. /**
  55.  *
  56.  * Common functions which are used throughout the project
  57.  *
  58.  * Class Common
  59.  * @package App\Services
  60.  */
  61. class Common
  62. {
  63.     private $em;
  64.     private $brandApi;
  65.     private $doctrine;
  66.     private $scraper;
  67.     private $elasticCache;
  68.     private $rootPath;
  69.     private $usersComponents;
  70.     private $mafoObjectsComponents;
  71.     private $hyperApis;
  72.     private LoggerInterface $logger;
  73.     private HubInterface $hub;
  74.     public function __construct(
  75.         MysqlQueries $em,
  76.         BrandHasofferAPI $brandApi,
  77.         EntityManagerInterface $doctrine,
  78.         Scraper $scraper,
  79.         Environment $templating,
  80.         Aws\ElasticCache $elasticCache,
  81.         ParameterBagInterface $params,
  82.         UsersComponents $usersComponents,
  83.         MafoObjectsComponents $mafoObjectsComponents,
  84.         HyperApis $hyperApis,
  85.         LoggerInterface $logger,
  86.         HubInterface $hub
  87.     ) {
  88.         $this->em $em;
  89.         $this->brandApi $brandApi;
  90.         $this->doctrine $doctrine;
  91.         $this->scraper $scraper;
  92.         $this->template $templating;
  93.         $this->elasticCache $elasticCache;
  94.         $this->rootPath $params->get('kernel.project_dir');
  95.         $this->usersComponents $usersComponents;
  96.         $this->mafoObjectsComponents $mafoObjectsComponents;
  97.         $this->hyperApis $hyperApis;
  98.         $this->logger $logger;
  99.         $this->hub $hub;
  100.     }
  101.     public function getAdvertisersListByStatusWithKeys($arr = [])
  102.     {
  103.         $statuses = isset($arr['statuses']) && sizeof($arr['statuses']) > $arr['statuses'] : [Config::ACTIVE_STATUS];
  104.         $tuneAccount = isset($arr['tuneAccount']) ? $arr['tuneAccount'] : Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  105.         $cachedList $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_ADVERTISER_LIST_FOR_MULTISELECT '_' $tuneAccount);
  106.         if (!$cachedList || (count($statuses) == && !in_array(Config::ACTIVE_STATUS$statuses))) {
  107.             $advertiserList $this->getWarmedUpHoAdvertiserList($statuses$tuneAccount);
  108.         } else {
  109.             $advertiserList json_decode($cachedListtrue);
  110.         }
  111.         ksort($advertiserList);
  112.         return $advertiserList;
  113.     }
  114.     public function getWarmedUpHoAdvertiserList($statuses$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  115.     {
  116.         $advertiserList = [];
  117.         $advertiserData $this->doctrine->getRepository(AdvertiserInfo::class)->getAdvertiserListByStatus($statuses$tuneAccount  );
  118.         $employeesInfo $this->getEmployeesByEmployeeId();
  119.         foreach ($advertiserData as $key => $value) {
  120.             $temp = [
  121.                 'status' => $value['status'],
  122.                 'name' => $value['company'],
  123.                 'accountManagerId' => $value['accountManagerId'],
  124.                 'accountManagerEmail' => null,
  125.                 'accountManagerName' => null,
  126.                 'id' => (int)$value['advertiserId']
  127.             ];
  128.             if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
  129.                 $temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
  130.                 $temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
  131.             }
  132.             $advertiserList[$value['advertiserId']] = $temp;
  133.         }
  134.         return $advertiserList;
  135.     }
  136.     public function getAffiliateListByStatusWithKeys($tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  137.     {
  138.         $statuses = [Config::ACTIVE_STATUS];
  139.         $tuneAccountCacheKey Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT '_' $tuneAccount;  
  140.         $cachedList $this->elasticCache->redisGet($tuneAccountCacheKey);
  141.         if (!$cachedList || (count($statuses) == && !in_array(Config::ACTIVE_STATUS$statuses))) {
  142.             $affiliateList $this->getWarmedUpHoAffiliateList($statuses$tuneAccount);
  143.         } else {
  144.             $affiliateList json_decode($cachedListtrue);
  145.         }
  146.         ksort($affiliateList);
  147.         return $affiliateList;
  148.     }
  149.     public function getPublisherAffiliateListByStatusWithKeys($statuses = [Config::ACTIVE_STATUS], $affiliateIds)
  150.     {
  151.         //        $cachedList = $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT);
  152.         //
  153.         //        if (!$cachedList || (count($statuses) == 1 && !in_array(Config::ACTIVE_STATUS, $statuses))) {
  154.         //            $affiliateList = $this->getWarmedUpHoPublisherAffiliateList($statuses);
  155.         //        } else {
  156.         //            $affiliateList = json_decode($cachedList, true);
  157.         //        }
  158.         $affiliateList $this->getWarmedUpHoPublisherAffiliateList($statuses$affiliateIds);
  159.         ksort($affiliateList);
  160.         return $affiliateList;
  161.     }
  162.     public function getWarmedUpHoAffiliateList($statuses$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  163.     {
  164.         $affiliateList = [];
  165.         $affiliateData $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByStatusArr($statuses$tuneAccount);
  166.         $employeesInfo $this->getEmployeesByEmployeeId();
  167.         foreach ($affiliateData as $key => $value) {
  168.             $temp = [
  169.                 'status' => $value['status'],
  170.                 'name' => $value['company'],
  171.                 'accountManagerId' => $value['accountManagerId'],
  172.                 'accountManagerEmail' => null,
  173.                 'accountManagerName' => null,
  174.                 'id' => (int)$value['affiliateId']
  175.             ];
  176.             if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
  177.                 $temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
  178.                 $temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
  179.             }
  180.             $affiliateList[$value['affiliateId']] = $temp;
  181.         }
  182.         return $affiliateList;
  183.     }
  184.   
  185.     public function getWarmedUpHoPublisherAffiliateList(array $statuses, array $affiliateIds = [])
  186.     {
  187.         $affiliateList = [];
  188.         // Fetch affiliate data based on status
  189.         $affiliateData $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByStatusArr($statuses);
  190.         // Get employee information
  191.         $employeesInfo $this->getEmployeesByEmployeeId();
  192.         foreach ($affiliateData as $value) {
  193.             // Only process if the affiliateId is in the provided $affiliateIds array, or if $affiliateIds is empty
  194.             if (empty($affiliateIds) || in_array($value['affiliateId'], $affiliateIds)) {
  195.                 $temp = [
  196.                     'status' => $value['status'],
  197.                     'name' => $value['company'],
  198.                     'accountManagerId' => $value['accountManagerId'],
  199.                     'accountManagerEmail' => null,
  200.                     'accountManagerName' => null,
  201.                     'id' => (int)$value['affiliateId']
  202.                 ];
  203.                 // Check if account manager info is available
  204.                 if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
  205.                     $temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
  206.                     $temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
  207.                 }
  208.                 // Add to affiliate list
  209.                 $affiliateList[$value['affiliateId']] = $temp;
  210.             }
  211.         }
  212.         return $affiliateList;
  213.     }
  214.     public function getWarmedUpHoPublisherMafoAffiliateList(array $statuses, array $affiliateIds = [])
  215.     {
  216.         $affiliateList = [];
  217.         // Fetch affiliate data based on status
  218.         $affiliateData $this->doctrine->getRepository(MafoAffiliates::class)->getAffiliateListByStatusArr($statuses);
  219.         // Get employee information
  220.         $employeesInfo $this->getEmployeesByEmployeeId();
  221.         foreach ($affiliateData as $value) {
  222.             // Only process if the affiliateId is in the provided $affiliateIds array, or if $affiliateIds is empty
  223.             if (empty($affiliateIds) || in_array($value['affiliateId'], $affiliateIds)) {
  224.                 $temp = [
  225.                     'status' => $value['status'],
  226.                     'name' => $value['name'],
  227.                     'accountManagerId' => $value['accountManagerId'],
  228.                     'accountManagerEmail' => null,
  229.                     'accountManagerName' => null,
  230.                     'id' => (int)$value['id']
  231.                 ];
  232.                 // Check if account manager info is available
  233.                 if (array_key_exists($value['accountManagerId'], $employeesInfo)) {
  234.                     $temp['accountManagerEmail'] = $employeesInfo[$value['accountManagerId']]['email'];
  235.                     $temp['accountManagerName'] = $employeesInfo[$value['accountManagerId']]['fullName'];
  236.                 }
  237.                 // Add to affiliate list
  238.                 $affiliateList[$value['id']] = $temp;
  239.             }
  240.         }
  241.         return $affiliateList;
  242.     }
  243.     public function getHyperClientCachedListByKeys()
  244.     {
  245.         $cachedList $this->elasticCache->redisGet(Config::CACHE_REDIS_HYPER_CLIENT_LIST);
  246.         if (!$cachedList) {
  247.             $clientList $this->getHyperClientListByKeys();
  248.         } else {
  249.             $clientList json_decode($cachedListtrue);
  250.         }
  251.         return $clientList;
  252.     }
  253.     public function getHyperClientListByKeys()
  254.     {
  255.         $hyperData $this->hyperApis->getHyperClientList();
  256.         $clientList = [];
  257.         if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
  258.             foreach ($hyperData['ResultData']['Data'] as $key => $value) {
  259.                 $countryCode null;
  260.                 foreach (Config::COUNTRIES as $k => $v) {
  261.                     if ($this->checkForString($value['Country'], $v['name'])) {
  262.                         $countryCode $k;
  263.                         break;
  264.                     }
  265.                 }
  266.                 $value['countryCode'] = $countryCode;
  267.                 $clientList[$value['ClientNumber']] = $value;
  268.             }
  269.         }
  270.         $this->elasticCache->redisSet(Config::CACHE_REDIS_HYPER_CLIENT_LISTjson_encode($clientList));
  271.         return $clientList;
  272.     }
  273.     public function getHyperPublisherCachedListByKeys()
  274.     {
  275.         $cachedList $this->elasticCache->redisGet(Config::CACHE_REDIS_HYPER_PUBLISHER_LIST);
  276.         if (!$cachedList) {
  277.             $clientList $this->getHyperPublisherListByKeys();
  278.         } else {
  279.             $clientList json_decode($cachedListtrue);
  280.         }
  281.         return $clientList;
  282.     }
  283.     public function getHyperPublisherListByKeys()
  284.     {
  285.         $hyperData $this->hyperApis->getHyperPublisherInfo();
  286.         $clientList = [];
  287.         if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
  288.             foreach ($hyperData['ResultData']['Data'] as $key => $value) {
  289.                 $countryCode null;
  290.                 foreach (Config::COUNTRIES as $k => $v) {
  291.                     if ($this->checkForString($value['Country'], $v['name'])) {
  292.                         $countryCode $k;
  293.                         break;
  294.                     }
  295.                 }
  296.                 $value['countryCode'] = $countryCode;
  297.                 $clientList[$value['SupplierNumber']] = $value;
  298.             }
  299.         }
  300.         
  301.         return $clientList;
  302.     }
  303.     public function getHyperAffiliateListByKeys()
  304.     {
  305.         $hyperData $this->hyperApis->getHyperClientList();
  306.         $clientList = [];
  307.         if ($hyperData && isset($hyperData['Result']) && $hyperData['Result'] == 'Ok') {
  308.             foreach ($hyperData['ResultData']['Data'] as $key => $value) {
  309.                 $countryCode null;
  310.                 foreach (Config::COUNTRIES as $k => $v) {
  311.                     if ($this->checkForString($value['Country'], $v['name'])) {
  312.                         $countryCode $k;
  313.                         break;
  314.                     }
  315.                 }
  316.                 $value['countryCode'] = $countryCode;
  317.                 $clientList[$value['ClientNumber']] = $value;
  318.             }
  319.         }
  320.         $this->elasticCache->redisSet(Config::CACHE_REDIS_HYPER_CLIENT_LISTjson_encode($clientList));
  321.         return $clientList;
  322.     }
  323.     public function getMmpAdvertisersListWithKeys()
  324.     {
  325.         $advertisers $this->doctrine->getRepository(MmpAdvertisers::class)->getMmpAdvertisers();
  326.         $data = [];
  327.         foreach ($advertisers as $key => $value) {
  328.             $data[$value['id']] = [
  329.                 'value' => $value['id'],
  330.                 'label' => $value['name']
  331.             ];
  332.         }
  333.         ksort($data);
  334.         return $data;
  335.     }
  336.     public function getAffiliateTagListByStatusWithKeys($tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  337.     {
  338.         $tagsInDb $this->doctrine->getRepository(Tag::class)->getTags(1nullnull1$tuneAccount);
  339.         $tagList = [];
  340.         foreach ($tagsInDb as $key => $value) {
  341.             $tagList[$value['tagId']] = [
  342.                 'value' => $value['tagId'],
  343.                 'name' => $value['name']
  344.             ];
  345.         }
  346.         ksort($tagList);
  347.         return $tagList;
  348.     }
  349.     public function getOfferCategoriesListByStatusWithKeys($tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  350.     {
  351.         $status Config::ACTIVE_STATUS;
  352.         $offerCategoriesData $this->doctrine->getRepository(OfferCategories::class)->getOfferCategoriesByStatus($status$tuneAccount);
  353.         $offerCategoryList = [];
  354.         foreach ($offerCategoriesData as $key => $value) {
  355.             $offerCategoryList[$value['categoryId']] = [
  356.                 'name' => $value['name'],
  357.                 'id' => (int)$value['categoryId']
  358.             ];
  359.         }
  360.         ksort($offerCategoryList);
  361.         return $offerCategoryList;
  362.     }
  363.     public function getAdvertiserListByAdvertiserIdArr($advertiserIdArr$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  364.     {
  365.         $advertiserDataByAdvertiserId = [];
  366.         if ($advertiserIdArr) {
  367.             $advertiserInfo $this->doctrine->getRepository(AdvertiserInfo::class)->getAdvertiserInfoByAdvertiserIdArr($advertiserIdArr$tuneAccount);
  368.             foreach ($advertiserInfo as $key => $value) {
  369.                 $advertiserDataByAdvertiserId[$value['advertiserId']] = [
  370.                     'id' => (int)$value['advertiserId'],
  371.                     'name' => $value['company']
  372.                 ];
  373.             }
  374.         }
  375.         return $advertiserDataByAdvertiserId;
  376.     }
  377.     public function getGoalDisableLinkData($offerId)
  378.     {
  379.         $data $this->em->getGoalDisableLinkData($offerId);
  380.         $distinctOfferIds = [];
  381.         foreach ($data as $key => $value) {
  382.             if (!in_array($value['offerId'], $distinctOfferIds)) {
  383.                 $distinctOfferIds[] = $value['offerId'];
  384.             }
  385.         }
  386.         $offerGoalsByOfferId = [];
  387.         if ($distinctOfferIds) {
  388.             $offerGoalData $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalsDataByOfferIdArr($distinctOfferIds);
  389.             if ($offerGoalData) {
  390.                 foreach ($offerGoalData as $key => $value) {
  391.                     $offerGoalsByOfferId[$value['offerId']][] = $value['goalId'];
  392.                 }
  393.             }
  394.         }
  395.         $bifurcatedData = [];
  396.         foreach ($data as $key => $value) {
  397.             if (array_key_exists($value['offerId'], $offerGoalsByOfferId) && in_array($value['goalId'], $offerGoalsByOfferId[$value['offerId']])) {
  398.                 $bifurcatedData[$value['addedFrom']][] = $value;
  399.             }
  400.         }
  401.         return $bifurcatedData;
  402.     }
  403.     public function disableLink($offerId$affiliateId$source$affsub2$affSub3$affSub5$addedFrom$advertiserId$jsonMetaDataStr$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  404.     {
  405.         $disableLinkMd5 $this->getDisableLinkMd5($offerId$affiliateId$source$affsub2$affSub3$affSub5$tuneAccount);
  406.         $md5Exist $this->em->getDisableLinkByMd5($disableLinkMd5);
  407.         if (!$md5Exist) {
  408.             $data $this->brandApi->saveOfferDisabledLink($offerId$affiliateId$source$affsub2$affSub3$affSub5$tuneAccount);
  409.             if ($data['response']['status'] === 1) {
  410.                 $this->em->insertToDisableLink($disableLinkMd5$offerId$affiliateId$source$affsub2$affSub3$affSub5$addedFrom$advertiserId$jsonMetaDataStr);
  411.             }
  412.         }
  413.     }
  414.     public function getDisableLinkMd5($offerId$affiliateId$source$affsub2$affSub3$affSub5$trackingAccount Config::TUNE_ACCOUNT_DEFAULT$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  415.     {
  416.         $trackingAccountStr $trackingAccount == Config::TUNE_ACCOUNT_DEFAULT '' Config::TUNE_ACCOUNT_WEB;
  417.         return md5($offerId $affiliateId $source $affsub2 $affSub3 $affSub5 $trackingAccountStr $tuneAccount);
  418.     }
  419.     public function automaticDisableLinkData($tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  420.     {
  421.         $automaticDisableLinkData $this->em->getAutomaticDisableLinkData($tuneAccount);
  422.         $finalArr['byAdvertiser'] = [];
  423.         $finalArr['byAffiliate'] = [];
  424.         $finalArr['byOffer'] = [];
  425.         foreach ($automaticDisableLinkData as $key => $value) {
  426.             $value['tuneAccountPretty'] = Config::MAFO_SYSTEM_IDENTIFIER_PRETTY[$value['tuneAccount']];
  427.             $value['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  428.             if ($value['advertiserId']) {
  429.                 $finalArr['byAdvertiser'][] = $value;
  430.             }
  431.             if ($value['affiliateId']) {
  432.                 $finalArr['byAffiliate'][] = $value;
  433.             }
  434.             if ($value['offerId']) {
  435.                 $finalArr['byOffer'][] = $value;
  436.             }
  437.         }
  438.         return $finalArr;
  439.     }
  440.     public function deleteDisableLinkByMd5($md5$id$trackingAccount Config::TUNE_ACCOUNT_DEFAULT)
  441.     {
  442.         $disableLink $this->em->getDisableLinkByMd5($md5);
  443.         if ($disableLink) {
  444.             $offerId $disableLink->getOfferId();
  445.             $affiliateId $disableLink->getAffiliateId();
  446.             $source $disableLink->getSource();
  447.             $affSub2 $disableLink->getAffsub2();
  448.             $affSub3 $disableLink->getAffsub3();
  449.             $affSub5 $disableLink->getAffsub5();
  450.             $advertiserId $disableLink->getAdvertiserId();
  451.             $addedFrom $disableLink->getAddedFrom();
  452.             $meta $disableLink->getMeta();
  453.             $wasInsertedOn $disableLink->getDateInserted();
  454.             $trackingAccount $disableLink->getTrackingAccount();
  455.             $strict 0;
  456.             $disableLinkData $this->brandApi->findDisableLink($offerId$affiliateId$source$strict$affSub2$affSub3$affSub5$trackingAccount)['response']['data'];
  457.             foreach ($disableLinkData as $k => $v) {
  458.                 $this->brandApi->deleteDisableLink($k$trackingAccount);
  459.             }
  460.             $this->em->deleteDisableLinkByMd5($md5);
  461.             //            Removing dump from mysql and added dump of DisableLinks to mongo
  462.             //            $this->em->insertToDisableLinkDump($md5, $offerId, $affiliateId, $source, $affSub2, $addedFrom, $advertiserId, $meta, $wasInsertedOn, $affSub3, $affSub5, $trackingAccount);
  463.         } else {
  464.             $this->brandApi->deleteDisableLink($id);
  465.         }
  466.     }
  467.     public function checkForNonIncentInString($string)
  468.     {
  469.         if ($this->checkForString($string'Non Incent') || $this->checkForString($string'NO Incent') || $this->checkForString($string'No-Incent') || $this->checkForString($string'Non-Incent') || $this->checkForString($string'NonIncent') || $this->checkForString($string'NoIncent') || $this->checkForString($string'No_Incent') || $this->checkForString($string'Non_Incent')) {
  470.             return true;
  471.         }
  472.         return false;
  473.     }
  474.     public function checkForString($superString$checkString)
  475.     {
  476.         if (strpos(strtolower($superString), strtolower($checkString)) !== false) {
  477.             return true;
  478.         } else {
  479.             return false;
  480.         }
  481.     }
  482.     public function filterSource($source)
  483.     {
  484.         if ($this->checkForString($source"_")) {
  485.             $source explode("_"$source);
  486.             if (($source[0] == "" && $source[1] != "") || ($source[0] != "" && $source[1] == "") || ($source[0] == "" && $source[1] == "")) {
  487.                 $source implode("_"$source);
  488.             } else {
  489.                 $source $source[0];
  490.             }
  491.         }
  492.         return $source;
  493.     }
  494.     public function filterSourceByAffiliate($source$affiliateId)
  495.     {
  496.         if ($affiliateId == 3467) {
  497.             $actualSource $source;
  498.             if (substr($source04) === "114_") {
  499.                 $actualSource substr($source4);
  500.             }
  501.             return $actualSource;
  502.         }
  503.         return $source;
  504.     }
  505.     public function filterSourceByAffiliateAndLtr($source$affiliateId$clicks$conversions)
  506.     {
  507.         if ($affiliateId == 3467) {
  508.             $actualSource $source;
  509.             if (substr($source04) === "114_") {
  510.                 $actualSource substr($source4);
  511.             }
  512.             if ($conversions 15 && (($conversions $clicks) * 100 30)) {
  513.                 return $actualSource;
  514.             } else {
  515.                 return false;
  516.             }
  517.         }
  518.         return $source;
  519.     }
  520.     public function getBulkCapData()
  521.     {
  522.         $bulkData $this->em->getBulkCapData();
  523.         foreach ($bulkData as $key => $value) {
  524.             $bulkData[$key]['affiliateOfferCapType'] = str_replace("_"" "ucfirst($value['affiliateOfferCapType']));
  525.             $bulkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:s:i');
  526.         }
  527.         return $bulkData;
  528.     }
  529.     public function getBulkCapByAffiliateData()
  530.     {
  531.         $bulkData $this->em->getBulkCapByAffiliateData();
  532.         foreach ($bulkData as $key => $value) {
  533.             $bulkData[$key]['affiliateOfferCapType'] = str_replace("_"" "ucfirst($value['affiliateOfferCapType']));
  534.             $bulkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:s:i');
  535.         }
  536.         return $bulkData;
  537.     }
  538.     public function getAccountManagerInfoByTuneAdvertiserId($advertiserId$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  539.     {
  540.         $accountManagerInfo $this->doctrine->getRepository(AdvertiserAccountManager::class)->getAdvertiserAccountManagerByAdvertiserId($advertiserId$tuneAccount);
  541.         $email Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
  542.         $firstName '';
  543.         $lastName '';
  544.         if ($accountManagerInfo) {
  545.             $email $accountManagerInfo->getEmail();
  546.             $firstName $accountManagerInfo->getFirstName();
  547.             $lastName $accountManagerInfo->getLastName();
  548.         }
  549.         return [
  550.             'emailId' => $email,
  551.             'firstName' => $firstName,
  552.             'lastName' => $lastName
  553.         ];
  554.     }
  555.     public function getAccountManagerInfoByMafoAdvertiserId($advertiserId)
  556.     {
  557.         $mafoAdvertiserInfo $this->doctrine->getRepository(MafoAdvertisers::class)->findOneBy(['id' => $advertiserId]);
  558.         $email Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
  559.         $firstName '';
  560.         $lastName '';
  561.         if ($mafoAdvertiserInfo) {
  562.             $accountManagerInfo $this->doctrine->getRepository(Users::class)->findOneBy(['email' => $mafoAdvertiserInfo->getAccountManagerEmail()]);
  563.             $email $mafoAdvertiserInfo->getAccountManagerEmail();
  564.             $name $accountManagerInfo->getName();
  565.             $nameArr explode(" "$name);
  566.             $firstName $nameArr[0];
  567.             $lastName $nameArr[1];
  568.         }
  569.         return [
  570.             'emailId' => $email,
  571.             'firstName' => $firstName,
  572.             'lastName' => $lastName
  573.         ];
  574.     }
  575.     public function getAccountManagerInfoByTuneAffiliateId($affiliateId$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  576.     {
  577.         $accountManagerInfo $this->doctrine->getRepository(AffiliateAccountManager::class)->getAffiliateAccountManagerByAffiliateId($affiliateId$tuneAccount);
  578.         $email Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
  579.         $firstName '';
  580.         $lastName '';
  581.         if ($accountManagerInfo) {
  582.             $email $accountManagerInfo->getEmail();
  583.             $firstName $accountManagerInfo->getFirstName();
  584.             $lastName $accountManagerInfo->getLastName();
  585.         }
  586.         return [
  587.             'emailId' => $email,
  588.             'firstName' => $firstName,
  589.             'lastName' => $lastName
  590.         ];
  591.     }
  592.     public function getAccountManagerInfoByMafoAffiliateId($affiliateId)
  593.     {
  594.         $mafoAffiliateInfo $this->doctrine->getRepository(MafoAffiliates::class)->findOneBy(['id' => $affiliateId]);
  595.         $email Config::ALERT_RECIPIENT_DEFAULT_EMAIL;
  596.         $firstName '';
  597.         $lastName '';
  598.         if ($mafoAffiliateInfo) {
  599.             $accountManagerInfo $this->doctrine->getRepository(Users::class)->findOneBy(['email' => $mafoAffiliateInfo->getAccountManagerEmail()]);
  600.             $email $mafoAffiliateInfo->getAccountManagerEmail();
  601.             $name $accountManagerInfo->getName();
  602.             $nameArr explode(" "$name);
  603.             $firstName $nameArr[0];
  604.             $lastName $nameArr[1];
  605.         }
  606.         return [
  607.             'emailId' => $email,
  608.             'firstName' => $firstName,
  609.             'lastName' => $lastName
  610.         ];
  611.     }
  612.     public function getAccountManagerInfoByAffiliateIdArrWithKeys($affiliateIdArr$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  613.     {
  614.         $accountManagerInfoDB $this->doctrine->getRepository(AffiliateAccountManager::class)->getDataByAffiliateIds($affiliateIdArr$tuneAccount );
  615.         $accountManagerInfo = [];
  616.         foreach ($accountManagerInfoDB as $key => $value) {
  617.             $accountManagerInfo[$value['affiliateId']] = $value;
  618.             $accountManagerInfo[$value['affiliateId']]['id'] = $value['employeeId'];
  619.             $accountManagerInfo[$value['affiliateId']]['name'] = $value['firstName'] . ' ' $value['lastName'];
  620.         }
  621.         return $accountManagerInfo;
  622.     }
  623.     public function getAccountManagerInfoByOfferId($offerId)
  624.     {
  625.         $offerInfo $this->doctrine->getRepository(OfferInfo::class)->checkOfferIdExist($offerId);
  626.         return $this->getAccountManagerInfoByTuneAdvertiserId($offerInfo $offerInfo->getAdvertiserId() : null);
  627.     }
  628.     public function getDisableLinkLogs($affiliateIdArray$offerIdArray$sourceIdArray$advertiserArray$addedFromArr$dateStart$dateEnd$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  629.     {
  630.         $disableLinksMyMd5 = [];
  631.         $disableLinkData = [];
  632.         if (empty($addedFromArr) || in_array(Config::DISABLE_LINKS_FROM_HO_PANEL$addedFromArr)) {
  633.             $disableLinkDataFromHO $this->brandApi->findDisableLinksDyDateRange($offerIdArray$affiliateIdArray$sourceIdArray, [], $dateStart$dateEnd$tuneAccount)['response']['data']['data'];
  634.             $disableLinkData = [];
  635.             $md5Arr = [];
  636.             foreach ($disableLinkDataFromHO as $key => $value) {
  637.                 $md5 $this->getDisableLinkMd5($value['OfferDisabledLink']['offer_id'], $value['OfferDisabledLink']['affiliate_id'], $value['OfferDisabledLink']['source'], Config::DEFAULT_AFF_SUB2Config::DEFAULT_AFF_SUB3Config::DEFAULT_AFF_SUB5$tuneAccount);
  638.                 $disableLinkData[] = [
  639.                     'affiliateId' => $value['OfferDisabledLink']['affiliate_id'],
  640.                     'offerId' => $value['OfferDisabledLink']['offer_id'],
  641.                     'source' => $value['OfferDisabledLink']['source'],
  642.                     'advertiserId' => null,
  643.                     'dateInserted' => $value['OfferDisabledLink']['datetime'],
  644.                     'addedFrom' => null,
  645.                     'md5' => $md5,
  646.                     'tuneAccount' => $tuneAccount,
  647.                     'id' => $value['OfferDisabledLink']['id']
  648.                 ];
  649.                 $md5Arr[] = $md5;
  650.             }
  651.             if (!empty($md5Arr)) {
  652.                 $savedDisableLinkData $this->em->getDisableLinksByMd5Arr($md5Arr);
  653.                 foreach ($savedDisableLinkData as $key => $value) {
  654.                     $disableLinksMyMd5[$value['md5']] = $value;
  655.                 }
  656.             }
  657.         } else {
  658.             $disableLinkData $this->em->getDisableLinkLogs($affiliateIdArray$offerIdArray$advertiserArray$sourceIdArray$addedFromArr$dateStart$dateEnd);
  659.             foreach ($disableLinkData as $key => $value) {
  660.                 $disableLinksMyMd5[$value['md5']] = $value;
  661.                 $disableLinkData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  662.             }
  663.         }
  664.         $distinctOfferIdArr = [];
  665.         $distinctAffiliateIdArr = [];
  666.         foreach ($disableLinkData as $key => $value) {
  667.             if (!in_array($value['offerId'], $distinctOfferIdArr)) {
  668.                 array_push($distinctOfferIdArr$value['offerId']);
  669.             }
  670.             if (!in_array($value['affiliateId'], $distinctAffiliateIdArr)) {
  671.                 array_push($distinctAffiliateIdArr$value['affiliateId']);
  672.             }
  673.             $disableLinkData[$key]['date_inserted'] = $value['dateInserted'];
  674.         }
  675.         $offerInfo = [];
  676.         if (!empty($distinctOfferIdArr)) {
  677.             $offerInfo $this->getOfferInfoByKey($distinctOfferIdArr$tuneAccount);
  678.         }
  679.         $advertiserList $this->getAdvertisersListByStatusWithKeys([
  680.             'tuneAccount' => $tuneAccount
  681.         ]);
  682.         $affiliateList $this->getAffiliateListByStatusWithKeys($tuneAccount);
  683.         foreach ($disableLinkData as $key => $value) {
  684.             if (!array_key_exists($value['offerId'], $offerInfo)) {
  685.                 unset($disableLinkData[$key]);
  686.                 continue;
  687.             }
  688.             $offerName $offerInfo[$value['offerId']]['name'] ?? '';
  689.             $advertiserName array_key_exists($offerInfo[$value['offerId']]['advertiserId'], $advertiserList) ? $advertiserList[$offerInfo[$value['offerId']]['advertiserId']]['name'] : '';
  690.             $advertiserId $offerInfo[$value['offerId']]['advertiserId'] ?? '';
  691.             $affiliateName array_key_exists($value['affiliateId'], $affiliateList) ? $affiliateList[$value['affiliateId']]['name'] : '';
  692.             $meta = [];
  693.             $addedFrom Config::DISABLE_LINKS_FROM_HO_PANEL;
  694.             if (array_key_exists($value['md5'], $disableLinksMyMd5)) {
  695.                 $meta json_decode($disableLinksMyMd5[$value['md5']]['meta'], true) != null json_decode($disableLinksMyMd5[$value['md5']]['meta'], true) : [];
  696.                 $addedFrom $disableLinksMyMd5[$value['md5']]['addedFrom'];
  697.             }
  698.             if (
  699.                 (!empty($addedFromArr) && !in_array($addedFrom$addedFromArr)) ||
  700.                 (sizeof($advertiserArray) && !in_array($advertiserId$advertiserArray))
  701.             ) {
  702.                 unset($disableLinkData[$key]);
  703.                 continue;
  704.             }
  705.             $disableLinkData[$key]['affiliateName'] = $affiliateName;
  706.             $disableLinkData[$key]['advertiserName'] = $advertiserName;
  707.             $disableLinkData[$key]['advertiserId'] = $advertiserId;
  708.             $disableLinkData[$key]['offerName'] = $offerName;
  709.             $disableLinkData[$key]['addedFrom'] = $addedFrom;
  710.             $disableLinkData[$key]['meta'] = $meta;
  711.         }
  712.         return $disableLinkData;
  713.     }
  714.     public function createUpdateRetentionOptimisation($offerId$goalId$retentionRate$minimumBudget$sendAlert$autoBlock$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  715.     {
  716.         $retentionOptimisationExist $this->em->getRetentionOptimisationByParams($offerId$goalId$tuneAccount);
  717.         if ($retentionOptimisationExist) {
  718.             if ($sendAlert === null) {
  719.                 $sendAlert $retentionOptimisationExist->getSendAlert();
  720.             }
  721.             if ($autoBlock === null) {
  722.                 $autoBlock $retentionOptimisationExist->getAutoBlock();
  723.             }
  724.             $this->em->updateRetentionOptimisation($offerId$goalId$retentionRate$minimumBudget$sendAlert$autoBlock$tuneAccount);
  725.         } else {
  726.             $this->em->insertRetentionOptimisation($offerId$goalId$retentionRate$minimumBudget$sendAlert$autoBlock$tuneAccount);
  727.         }
  728.     }
  729.     public function getRetentionOptimisationData($offerId$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  730.     {
  731.         $retentionOptimisationData $this->em->getRetentionOptimisation($offerId$tuneAccount);
  732.         $distinctOfferIds = [];
  733.         foreach ($retentionOptimisationData as $key => $value) {
  734.             if (!in_array($value['offerId'], $distinctOfferIds)) {
  735.                 array_push($distinctOfferIds$value['offerId']);
  736.             }
  737.         }
  738.         foreach ($retentionOptimisationData as $key => $value) {
  739.             // $retentionOptimisationData[$key]['offerName'] = $offerInfo[$value['offerId']]['name'] ?? "";
  740.             // $retentionOptimisationData[$key]['advertiserId'] = $offerInfo[$value['offerId']]['advertiserId'] ?? "";
  741.             // $retentionOptimisationData[$key]['advertiserName'] = $offerInfo[$value['offerId']]['Advertiser']['company'] ?? "";
  742.             // $retentionOptimisationData[$key]['advertiserName'] = array_key_exists($offerInfo[$value['offerId']]['advertiserId'], $advertiserList) ? $advertiserList[$offerInfo[$value['offerId']]['advertiserId']]['name'] : '';
  743.             // $retentionOptimisationData[$key]['goalName'] = $offerInfo[$value['offerId']]['Goal'][$value['goalId']]['name'] ?? "";
  744.             $retentionOptimisationData[$key]['dateInserted'] = $value['dateUpdated']->format("Y-m-d H:s:i");
  745.         }
  746.         return array_values($retentionOptimisationData);
  747.     }
  748.     public function changeCamelCaseToWords($camelCaseString)
  749.     {
  750.         return ucfirst(implode(" "preg_split('/(?=[A-Z])/'$camelCaseString)));
  751.     }
  752.     public function setOfferAffiliateCap($affiliateId$offerId$affiliateOfferCapType$capValue$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  753.     {
  754.         $capExist $this->em->getCombinationFromAffiliateOfferCapping($affiliateId$offerId$affiliateOfferCapType$tuneAccount);
  755.         if (!$capExist || ($capExist->getCapValue() != $capValue)) {
  756.             if ($capExist) {
  757.                 $this->em->deleteAffiliateOfferCapById($capExist->getId());
  758.             }
  759.             $hoResponse $this->brandApi->setAffiliateOfferCap($affiliateId$offerId$affiliateOfferCapType$capValue$tuneAccount);
  760.             if ($hoResponse['response']['status'] == 1) {
  761.                 $this->em->insertToAffiliateOfferCap($affiliateId$offerId$affiliateOfferCapType$capValue$tuneAccount);
  762.             }
  763.         }
  764.     }
  765.     public function getImpressionOptimisationData()
  766.     {
  767.         $impressionOptimisations $this->em->getActiveImpressionOptimisation();
  768.         foreach ($impressionOptimisations as $key => $value) {
  769.             $impressionOptimisations[$key]['dateUpdated'] = $value['dateUpdated']->format("Y-m-d H:s:i");
  770.             $impressionOptimisations[$key]['dateInserted'] = $value['dateInserted']->format("Y-m-d H:s:i");
  771.         }
  772.         return $impressionOptimisations;
  773.     }
  774.     public function createUpdateImpressionOptimisation($offerId$affiliate_id$ctr$addedBy)
  775.     {
  776.         return $this->em->createUpdateImpression($offerId$affiliate_id$ctr$addedBy);
  777.     }
  778.     public function getFraudFlagLogs($affiliateIdArray$offerIdArray$advertiserArray$dateStart$dateEnd)
  779.     {
  780.         $fraudFlagData = [];
  781.         $fraudFlagData $this->em->getFraudFlagLogs($affiliateIdArray$offerIdArray$advertiserArray$dateStart$dateEnd);
  782.         //                foreach ($fraudFlagData as $key => $value) {
  783.         //                    $fraudFlagData[$key]['dateInserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  784.         //                }
  785.         $distinctOfferIdArr = [];
  786.         $distinctAffiliateIdArr = [];
  787.         foreach ($fraudFlagData as $key => $value) {
  788.             if (!in_array($value['offerId'], $distinctOfferIdArr)) {
  789.                 array_push($distinctOfferIdArr$value['offerId']);
  790.             }
  791.             if (!in_array($value['affiliateId'], $distinctAffiliateIdArr)) {
  792.                 array_push($distinctAffiliateIdArr$value['affiliateId']);
  793.             }
  794.             $fraudFlagData[$key]['date_inserted'] = $value['dateInserted']->format('Y-m-d H:i:s');
  795.         }
  796.         if (!empty($distinctOfferIdArr)) {
  797.             $offerInfo $this->brandApi->getOffersByOfferIdsArr($distinctOfferIdArr)['response']['data'];
  798.         }
  799.         if (!empty($distinctAffiliateIdArr)) {
  800.             $affiliateInfo $this->brandApi->getAffiliatesByAffiliateIdArr($distinctAffiliateIdArr)['response']['data'];
  801.         }
  802.         foreach ($fraudFlagData as $key => $value) {
  803.             $offerName $offerInfo[$value['offerId']]['Offer']['name'] ?? '';
  804.             $advertiserName $offerInfo[$value['offerId']]['Advertiser']['company'] ?? '';
  805.             $advertiserId $offerInfo[$value['offerId']]['Advertiser']['id'] ?? '';
  806.             $affiliateName $affiliateInfo[$value['affiliateId']]['Affiliate']['company'] ?? '';
  807.             $fraudFlagData[$key]['affiliateName'] = $affiliateName;
  808.             $fraudFlagData[$key]['advertiserName'] = $advertiserName;
  809.             $fraudFlagData[$key]['advertiserId'] = $advertiserId;
  810.             $fraudFlagData[$key]['offerName'] = $offerName;
  811.         }
  812.         return $fraudFlagData;
  813.     }
  814.     public function deleteFraudFlagLogs($id)
  815.     {
  816.         $this->em->deleteFraudFlagLogs($id);
  817.     }
  818.     public function blockOfferForAffiliate($offerId$affiliateId$blockType$blockedFrom$conversions$clicks$ltr$trackingAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  819.     {
  820.         $combinationExist $this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->findOneBy([
  821.             'offerId' => $offerId,
  822.             'affiliateId' => $affiliateId,
  823.             'trackingAccount' => $trackingAccount
  824.         ]);
  825.         $affiliateOfferBlockedInHO $this->brandApi->getAffiliateOfferBlock($offerId$affiliateId$trackingAccount)['response']['data']['data'];
  826.         if (array_key_exists($offerId$affiliateOfferBlockedInHO) && $affiliateOfferBlockedInHO[$offerId]['OfferAffiliateBlock']['affiliate_id'] == $affiliateId && !$combinationExist) {
  827.             return false;
  828.         }
  829.         if (!$combinationExist) {
  830.             if ($blockType === Config::AFFILIATE_OFFER_BLOCK_MACRO) {
  831.                 $hoResponse $this->brandApi->blockOfferAffiliate($offerId$affiliateId$trackingAccount);
  832.             } elseif ($blockType === Config::AFFILIATE_OFFER_UNBLOCK_MACRO) {
  833.                 $hoResponse $this->brandApi->unblockOfferAffiliate($offerId$affiliateId$trackingAccount);
  834.             }
  835.             if (isset($hoResponse['response']['status']) && $hoResponse['response']['status'] == 1) {
  836.                 $this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->insertToOfferAffiliateBlock($offerId$affiliateId$blockType$blockedFrom$conversions$clicks$ltr$trackingAccount);
  837.                 //            Removing dump from mysql and added dump of AffiliateOfferBlock to mongo
  838.                 //                $this->doctrine->getRepository('App\Entity\AffiliateOfferBlockLogs')->insertToOfferAffiliateBlockLogs($offerId, $affiliateId, $blockType, $blockedFrom, $conversions, $clicks, $ltr, $trackingAccount);
  839.                 return true;
  840.             }
  841.         }
  842.         return false;
  843.     }
  844.     public function deleteOfferAffiliateBlock($offerId$affiliateId$trackingAccount)
  845.     {
  846.         $hoResponse $this->brandApi->unblockOfferAffiliate($offerId$affiliateId$trackingAccount);
  847.         if ($hoResponse['response']['status'] == 1) {
  848.             $this->doctrine->getRepository('App\Entity\AffiliateOfferBlock')->deleteOfferAffiliateBlock($offerId$affiliateId$trackingAccount);
  849.         }
  850.     }
  851.     public function populateDbByOfferId($offerId$metaData = [])
  852.     {
  853.         $calledFromCronJob $metaData['calledFromCronJob'] ?? true;
  854.         $tuneAccount $metaData['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  855.         $offerExistInDB $this->doctrine->getRepository('App\Entity\OfferInfo')->findOneBy([
  856.             'offerId' => $offerId,
  857.             'tuneAccount' => $tuneAccount
  858.         ]);
  859.         $offerInfo[$offerId] = $this->brandApi->getOfferByOfferId($offerId$tuneAccount)['response']['data'];
  860.         $offerIpWhitelistHoData $this->brandApi->getIpWhitelistByOfferId($offerId$tuneAccount)['response']['data'];
  861.         $offerFileCreativesHoData $this->brandApi->getOfferFilesByOfferId($offerId$tuneAccount);
  862.         $offerIpWhitelistArray = [];
  863.         foreach ($offerIpWhitelistHoData as $key => $value) {
  864.             if ($value['OfferWhitelist']['type'] == Config::OFFER_IP_WHITELIST_TYPE_POSTBACK) {
  865.                 array_push($offerIpWhitelistArray$value['OfferWhitelist']['content']);
  866.             }
  867.         }
  868.         $offerCountryIdArray = isset($offerInfo[$offerId]['Country']) ? array_keys($offerInfo[$offerId]['Country']) : [];
  869.         $offerCategoryIdArray = isset($offerInfo[$offerId]['OfferCategory']) ? array_keys($offerInfo[$offerId]['OfferCategory']) : [];
  870.         $offerTagIdArray = isset($offerInfo[$offerId]['OfferTag']) ? array_keys($offerInfo[$offerId]['OfferTag']) : [];
  871.         $offerGoalArray = isset($offerInfo[$offerId]['Goal']) ? array_values($offerInfo[$offerId]['Goal']) : [];
  872.         foreach ($offerGoalArray as $key => $value) {
  873.             foreach ($value as $k => $v) {
  874.                 $offerGoalArray[$key][lcfirst(implode(''array_map('ucfirst'explode('_'$k))))] = $v;
  875.                 if ($this->checkForString($k'_')) {
  876.                     unset($offerGoalArray[$key][$k]);
  877.                 }
  878.             }
  879.         }
  880.         if ($offerExistInDB) {
  881.             $offerDataToUpdate = [];
  882.             foreach ($offerInfo[$offerId]['Offer'] as $key => $value) {
  883.                 $appId $this->scraper->getAppId($offerInfo[$offerId]['Offer']['preview_url']);
  884.                 if (!$appId) {
  885.                     $appId 'Not Found';
  886.                 }
  887.                 $offerDataToUpdate['appId'] = $appId;
  888.                 $offerDataToUpdate[lcfirst(implode(''array_map('ucfirst'explode('_'$key))))] = $value;
  889.             }
  890.             $offerDataToUpdate['geoIdsJson'] = json_encode($offerCountryIdArray);
  891.             $offerDataToUpdate['categoryIdsJson'] = json_encode($offerCategoryIdArray);
  892.             $offerDataToUpdate['tagIdsJson'] = json_encode($offerTagIdArray);
  893.             // $offerDataToUpdate['whitelistIpsJson'] = json_encode($offerIpWhitelistArray);
  894.             if ($offerInfo[$offerId]['Thumbnail'] && isset($offerInfo[$offerId]['Thumbnail']['preview_uri'])) {
  895.                 $offerDataToUpdate['thumbnail'] = $offerInfo[$offerId]['Thumbnail']['preview_uri'];
  896.             }
  897.             $this->doctrine->getRepository(OfferInfo::class)->updateOfferByOfferId($offerId$offerDataToUpdate$tuneAccount);
  898.         } else {
  899.             $offerValue $offerInfo[$offerId];
  900.             $domain $offerInfo[$offerId]['Hostname']['domain'] ?? '';
  901.             $appId $this->scraper->getAppId($offerValue['Offer']['preview_url']);
  902.             if (!$appId) {
  903.                 $appId 'Not Found';
  904.             }
  905.             $offerValue['Offer']['app_id'] = $appId;
  906.             if (!$offerValue['Offer']['advertiser_id']) {
  907.                 $offerValue['Offer']['advertiser_id'] = 0;
  908.             }
  909.             $this->doctrine->getRepository(OfferInfo::class)->insertToOfferInfo($offerValue['Offer']['id'], $offerValue['Offer']['advertiser_id'], $offerValue['Offer']['name'], $offerValue['Offer']['description'], $offerValue['Offer']['require_approval'], $offerValue['Offer']['preview_url'], $offerValue['Thumbnail']['preview_uri'] ?? null$offerValue['Offer']['offer_url'], $offerValue['Offer']['currency'], $offerValue['Offer']['default_payout'], $offerValue['Offer']['payout_type'], $offerValue['Offer']['max_payout'], $offerValue['Offer']['revenue_type'], $offerValue['Offer']['status'], $offerValue['Offer']['redirect_offer_id'], $offerValue['Offer']['ref_id'], $offerValue['Offer']['conversion_cap'], $offerValue['Offer']['monthly_conversion_cap'], $offerValue['Offer']['payout_cap'], $offerValue['Offer']['monthly_payout_cap'], $offerValue['Offer']['revenue_cap'], $offerValue['Offer']['monthly_revenue_cap'], json_encode($offerCountryIdArray), json_encode($offerCategoryIdArray), $offerValue['Offer']['is_private'], $offerValue['Offer']['default_goal_name'], $offerValue['Offer']['note'], $offerValue['Offer']['has_goals_enabled'], $offerValue['Offer']['enforce_secure_tracking_link'], $offerValue['Offer']['enable_offer_whitelist'], $offerValue['Offer']['lifetime_conversion_cap'], $offerValue['Offer']['lifetime_payout_cap'], $offerValue['Offer']['lifetime_revenue_cap'], json_encode($offerTagIdArray), json_encode([]), $offerValue['Offer']['protocol'], $offerValue['Offer']['app_id'], $offerValue['Offer']['approve_conversions'], $domain$tuneAccount);
  910.         }
  911.         $this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount$offerId);
  912.         foreach ($offerGoalArray as $key => $value) {
  913.             $goalExistInDB $this->doctrine->getRepository(OfferGoalsInfo::class)->findOneBy(['goalId' => $value['id'], 'tuneAccount' => $tuneAccount]);
  914.             if ($goalExistInDB) {
  915.                 $this->doctrine->getRepository(OfferGoalsInfo::class)->updateGoalByGoalId($value['id'], $value$tuneAccount);
  916.             } else {
  917.                 $this->doctrine->getRepository(OfferGoalsInfo::class)->insertToOfferGoalsInfo($value['id'], $offerId$value['name'], $value['description'], $value['status'], $value['isPrivate'], $value['payoutType'], $value['defaultPayout'], $value['revenueType'], $value['maxPayout'], $value['tieredPayout'], $value['tieredRevenue'], $value['usePayoutGroups'], $value['useRevenueGroups'], $value['advertiserId'], $value['protocol'], $value['allowMultipleConversions'], $value['approveConversions'], $value['enforceEncryptTrackingPixels'], $value['isEndPoint'], $value['refId'], $tuneAccount);
  918.             }
  919.         }
  920.         if ($calledFromCronJob) {
  921.             $this->scraper->getAppDetailsByPreviewUrl($offerInfo[$offerId]['Offer']['preview_url']);
  922.             if (is_array($offerTagIdArray)) {
  923.                 $this->doctrine->getRepository(OfferTagRelationship::class)->deleteOfferTagRelationByOfferId($offerId$tuneAccount);
  924.                 foreach ($offerTagIdArray as $tagId) {
  925.                     $this->doctrine->getRepository(OfferTagRelationship::class)->insertToOfferTagRelationship($offerId$tagId$tuneAccount);
  926.                 }
  927.             }
  928.             if (is_array($offerCategoryIdArray)) {
  929.                 $this->doctrine->getRepository(OfferCategoryRelationship::class)->deleteOfferCategoryRelationByOfferId($offerId$tuneAccount);
  930.                 foreach ($offerCategoryIdArray as $categoryId) {
  931.                     $this->doctrine->getRepository(OfferCategoryRelationship::class)->insertToOfferCategoryRelationship($offerId$categoryId$tuneAccount);
  932.                 }
  933.             }
  934.             if (is_array($offerCountryIdArray)) {
  935.                 $this->doctrine->getRepository(OfferGeoRelationship::class)->deleteOfferGeoRelationByOfferId($offerId$tuneAccount);
  936.                 foreach ($offerCountryIdArray as $geo) {
  937.                     $this->doctrine->getRepository(OfferGeoRelationship::class)->insertToOfferGeoRelationship($offerId$geo$tuneAccount);
  938.                 }
  939.             }
  940.         }
  941.         if (!$calledFromCronJob) {
  942.             $offerWhitelistIdArrFromHO = [];
  943.             foreach ($offerIpWhitelistHoData as $key => $value) {
  944.                 $value $value['OfferWhitelist'];
  945.                 $value['tuneAccount'] = $tuneAccount;
  946.                 $offerWhitelistExist $this->doctrine->getRepository(OfferWhitelist::class)->findOneBy(['whitelistId' => $value['id'], 'tuneAccount' => $tuneAccount]);
  947.                 if (!$offerWhitelistExist) {
  948.                     $this->doctrine->getRepository(OfferWhitelist::class)->insertToOfferWhitelist($value['id'], $value['offer_id'], $value['type'], $value['content_type'], $value['content'], $tuneAccount);
  949.                 } else {
  950.                     $this->doctrine->getRepository(OfferWhitelist::class)->updateOfferWhitelistByWhitelistId($value['id'], $value$tuneAccount);
  951.                 }
  952.                 array_push($offerWhitelistIdArrFromHO$value['id']);
  953.             }
  954.             if (sizeof($offerWhitelistIdArrFromHO)) {
  955.                 $offerWhitelistToBeDeleted $this->doctrine->getRepository(OfferWhitelist::class)->getDeletedOfferWhitelistIds($offerId$offerWhitelistIdArrFromHO$tuneAccount);
  956.                 foreach ($offerWhitelistToBeDeleted as $key => $value) {
  957.                     $this->doctrine->getRepository(OfferWhitelist::class)->deleteByWhitelistId($value['whitelistId'], $tuneAccount);
  958.                 }
  959.             }
  960.             foreach ($offerFileCreativesHoData as $key => $value) {
  961.                 $fileExist $this->doctrine->getRepository(OfferCreativeFile::class)->findOneBy(['fileId' => $key'tuneAccount' => $tuneAccount]);
  962.                 if (isset($value['OfferFile'])) {
  963.                     if (!$fileExist) {
  964.                         $response $value['OfferFile'];
  965.                         if ($response['status'] == Config::DELETED_STATUS || $response['status'] == Config::PENDING_STATUS) {
  966.                             continue;
  967.                         }
  968.                         $this->doctrine->getRepository(OfferCreativeFile::class)->insertToOfferCreativeFile($response['id'], $response['offer_id'], $response['display'], $response['filename'], $response['size'], $response['status'], $response['type'], $response['width'], $response['height'], $response['code'], $response['flash_vars'], $response['interface'], $response['account_id'], $response['is_private'], $response['url'], $response['preview_uri'], $response['thumbnail'], $tuneAccount);
  969.                     } elseif ($fileExist->getStatus() != $value['OfferFile']['status']) {
  970.                         $this->doctrine->getRepository(OfferCreativeFile::class)->updateStatusByFileId($value['OfferFile']['id'], $value['OfferFile']['status'], $tuneAccount);
  971.                     }
  972.                 }
  973.             }
  974.         }
  975.     }
  976.     public function updateOffer($offerId$offerDetails$offerCountries$offerCategories$offerTags$offerWhitelistIps$tuneAccount)
  977.     {
  978.         $offerCreateHoResponse $this->brandApi->createOrUpdateOffer($offerId$offerDetails$tuneAccount);
  979.         if ($offerCreateHoResponse['response']['status'] === 1) {
  980.             $offerInfo $offerCreateHoResponse['response']['data']['Offer'];
  981.             $offerId $offerInfo['id'];
  982.             $this->doctrine->getRepository(OfferInfo::class)->updateOfferByOfferId($offerId$offerDetails$tuneAccount);
  983.             $this->updateOfferCountries($offerId$offerCountries$tuneAccount);
  984.             $this->updateOfferCategories($offerId$offerCategories$tuneAccount);
  985.             $this->updateOfferTags($offerId$offerTags$tuneAccount);
  986.             $this->updateOfferWhitelist($offerId$offerWhitelistIps$tuneAccount);
  987.             $this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount$offerId);
  988.         }
  989.         return $offerCreateHoResponse;
  990.     }
  991.     public function createNewOffer($offerDetails$offerCountries$offerCategories$offerTags$offerWhitelistIps$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  992.     {
  993.         $offerCreateHoResponse $this->brandApi->createOrUpdateOffer(null$offerDetails$tuneAccount);
  994.         if ($offerCreateHoResponse['response']['status'] === 1) {
  995.             $offerInfo $offerCreateHoResponse['response']['data']['Offer'];
  996.             $offerId $offerInfo['id'];
  997.             $appId $this->scraper->getAppId($offerInfo['preview_url']);
  998.             if (!$appId) {
  999.                 $appId 'Not Found';
  1000.             }
  1001.             $offerInfo['app_id'] = $appId;
  1002.             $this->doctrine->getRepository('App\Entity\OfferInfo')->insertToOfferInfo($offerId$offerInfo['advertiser_id'], $offerInfo['name'], $offerInfo['description'], $offerInfo['require_approval'], $offerInfo['preview_url'], null$offerInfo['offer_url'], $offerInfo['currency'], $offerInfo['default_payout'], $offerInfo['payout_type'], $offerInfo['max_payout'], $offerInfo['revenue_type'], $offerInfo['status'], $offerInfo['redirect_offer_id'], $offerInfo['ref_id'], $offerInfo['conversion_cap'], $offerInfo['monthly_conversion_cap'], $offerInfo['payout_cap'], $offerInfo['monthly_payout_cap'], $offerInfo['revenue_cap'], $offerInfo['monthly_revenue_cap'], '[]''[]'$offerInfo['is_private'], $offerInfo['default_goal_name'], $offerInfo['note'], $offerInfo['has_goals_enabled'], $offerInfo['enforce_secure_tracking_link'], $offerInfo['enable_offer_whitelist'], $offerInfo['lifetime_conversion_cap'], $offerInfo['lifetime_payout_cap'], $offerInfo['lifetime_revenue_cap'], '[]''[]'$offerInfo['protocol'], $offerInfo['app_id'], null$offerDetails['trackingDomain'] ?? null$tuneAccount);
  1003.             $this->updateOfferCountries($offerId$offerCountries$tuneAccount);
  1004.             $this->updateOfferCategories($offerId$offerCategories$tuneAccount);
  1005.             $this->updateOfferTags($offerId$offerTags$tuneAccount);
  1006.             $this->updateOfferWhitelist($offerId$offerWhitelistIps$tuneAccount);
  1007.             $this->mafoObjectsComponents->createOrUpdateOffer($tuneAccount$offerId);
  1008.             $appDetails $this->scraper->getAppDetailsByPreviewUrl($offerInfo['preview_url']);
  1009.             if ($appDetails) {
  1010.                 $fileResponse $this->uploadFile($offerId$appDetails['icon'], Config::FILE_TYPE_THUMBNAIL0);
  1011.                 if ($fileResponse['response']['status'] == 1) {
  1012.                     $this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['thumbnail' => $fileResponse['response']['data']['OfferFile']['url']], $tuneAccount);
  1013.                 }
  1014.             }
  1015.         }
  1016.         return $offerCreateHoResponse;
  1017.     }
  1018.     public function updateOfferCountries($offerId$offerCountries$tuneAccount)
  1019.     {
  1020.         $savedOfferInfo $this->doctrine->getRepository('App\Entity\OfferInfo')->findOneBy(['offerId' => $offerId'tuneAccount' => $tuneAccount]);
  1021.         $savedGeos json_decode($savedOfferInfo->getGeoIdsJson(), true);
  1022.         foreach ($savedGeos as $geo) {
  1023.             if (!in_array($geo$offerCountries)) {
  1024.                 $this->brandApi->removeGeoFromOffer($offerId$geo$tuneAccount);
  1025.             }
  1026.         }
  1027.         foreach ($offerCountries as $geo) {
  1028.             $this->brandApi->addGeoToOffer($offerId$geo$tuneAccount);
  1029.         }
  1030.         $this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['geoIdsJson' => json_encode($offerCountries)], $tuneAccount);
  1031.     }
  1032.     public function updateOfferCategories($offerId$offerCategories$tuneAccount)
  1033.     {
  1034.         if (is_array($offerCategories) && count($offerCategories) > 0) {
  1035.             $this->brandApi->setCategoryToOffer($offerId$offerCategories$tuneAccount);
  1036.             $this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['categoryIdsJson' => json_encode($offerCategories)], $tuneAccount);
  1037.         }
  1038.     }
  1039.     public function updateOfferTags($offerId$offerTags$tuneAccount)
  1040.     {
  1041.         if (is_array($offerTags) && count($offerTags) > 0) {
  1042.             foreach ($offerTags as $tagId) {
  1043.                 $this->brandApi->addTagToOffer($offerId$tagId$tuneAccount);
  1044.             }
  1045.             $this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['tagIdsJson' => json_encode($offerTags)], $tuneAccount);
  1046.         }
  1047.     }
  1048.     public function updateOfferWhitelist($offerId$offerWhitelistIps$tuneAccount)
  1049.     {
  1050.         if (is_array($offerWhitelistIps) && count($offerWhitelistIps) > 0) {
  1051.             foreach ($offerWhitelistIps as $whitelistIp) {
  1052.                 $this->brandApi->addIpWhitelistToOffer($offerId$whitelistIpConfig::OFFER_IP_WHITELIST_CONTENT_TYPE_IP_ADDRESSConfig::OFFER_IP_WHITELIST_TYPE_POSTBACK$tuneAccount);
  1053.             }
  1054.             // echo json_encode($offerWhitelistIps);
  1055.             // $this->doctrine->getRepository('App\Entity\OfferInfo')->updateOfferByOfferId($offerId, ['whitelistIpsJson' => json_encode($offerWhitelistIps)], $tuneAccount);
  1056.         }
  1057.     }
  1058.     public function updateOfferGoal($goalId$offerGoalDetails$tuneAccount)
  1059.     {
  1060.         if (isset($offerGoalDetails['goal_id'])) {
  1061.             unset($offerGoalDetails['goal_id']);
  1062.         }
  1063.         $offerGoalCreateHoResponse $this->brandApi->createOrUpdateOfferGoal($goalId$offerGoalDetails$tuneAccount);
  1064.         if ($offerGoalCreateHoResponse['response']['status'] === 1) {
  1065.             $dataToUpdate = [];
  1066.             foreach ($offerGoalCreateHoResponse['response']['data']['Goal'] as $key => $value) {
  1067.                 if ($key === 'id') {
  1068.                     continue;
  1069.                 }
  1070.                 $dataToUpdate[$this->convertStringFromSnakeCaseToCamelCase($key)] = $value;
  1071.             }
  1072.             $this->doctrine->getRepository(OfferGoalsInfo::class)->updateGoalByGoalId($goalId$dataToUpdate$tuneAccount);
  1073.         }
  1074.         return $offerGoalCreateHoResponse;
  1075.     }
  1076.     public function createNewOfferGoal($offerGoalDetails$tuneAccount)
  1077.     {
  1078.         $offerGoalCreateHoResponse $this->brandApi->createOrUpdateOfferGoal(null$offerGoalDetails$tuneAccount);
  1079.         if ($offerGoalCreateHoResponse['response']['status'] === 1) {
  1080.             $offerGoalCreateHoResponseData $offerGoalCreateHoResponse['response']['data']['Goal'];
  1081.             $this->doctrine->getRepository(OfferGoalsInfo::class)->insertToOfferGoalsInfo(
  1082.                 $offerGoalCreateHoResponseData['id'],
  1083.                 $offerGoalCreateHoResponseData['offer_id'],
  1084.                 $offerGoalCreateHoResponseData['name'],
  1085.                 $offerGoalCreateHoResponseData['description'],
  1086.                 $offerGoalCreateHoResponseData['status'],
  1087.                 $offerGoalCreateHoResponseData['is_private'],
  1088.                 $offerGoalCreateHoResponseData['payout_type'],
  1089.                 $offerGoalCreateHoResponseData['default_payout'],
  1090.                 $offerGoalCreateHoResponseData['revenue_type'],
  1091.                 $offerGoalCreateHoResponseData['max_payout'],
  1092.                 $offerGoalCreateHoResponseData['tiered_payout'],
  1093.                 $offerGoalCreateHoResponseData['tiered_revenue'],
  1094.                 $offerGoalCreateHoResponseData['use_payout_groups'],
  1095.                 $offerGoalCreateHoResponseData['use_revenue_groups'],
  1096.                 $offerGoalCreateHoResponseData['advertiser_id'],
  1097.                 $offerGoalCreateHoResponseData['protocol'],
  1098.                 $offerGoalCreateHoResponseData['allow_multiple_conversions'],
  1099.                 $offerGoalCreateHoResponseData['approve_conversions'],
  1100.                 $offerGoalCreateHoResponseData['enforce_encrypt_tracking_pixels'],
  1101.                 $offerGoalCreateHoResponseData['is_end_point'],
  1102.                 $offerGoalCreateHoResponseData['ref_id'],
  1103.                 $tuneAccount
  1104.             );
  1105.         }
  1106.         return $offerGoalCreateHoResponse;
  1107.     }
  1108.     public function uploadFile($offerId$fileUrlToUpload$creativeType$isPrivate)
  1109.     {
  1110.         $fileData = @file_get_contents($fileUrlToUpload);
  1111.         $fileExtension pathinfo($fileUrlToUploadPATHINFO_EXTENSION);
  1112.         $fileName $fileExtension === '' $offerId "_" basename($fileUrlToUpload) . '.png' $offerId "_" basename($fileUrlToUpload);
  1113.         file_put_contents($fileName$fileData);
  1114.         $fileResponse $this->brandApi->offerFileAPI($offerId$creativeType$fileName$fileName$isPrivate);
  1115.         unlink($fileName);
  1116.         return $fileResponse;
  1117.     }
  1118.     public function convertStringFromCamelCaseToSnakeCase($input)
  1119.     {
  1120.         preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!'$input$matches);
  1121.         $ret $matches[0];
  1122.         foreach ($ret as &$match) {
  1123.             $match $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
  1124.         }
  1125.         return implode('_'$ret);
  1126.     }
  1127.     public function convertStringFromSnakeCaseToCamelCase($input)
  1128.     {
  1129.         return lcfirst(implode(''array_map('ucfirst'explode('_'$input))));
  1130.     }
  1131.     public function getScraper()
  1132.     {
  1133.         return $this->scraper;
  1134.     }
  1135.     public function getOfferListByOfferIdArr($offerIdArr)
  1136.     {
  1137.         $response = [];
  1138.         if ($offerIdArr) {
  1139.             $offerInfo $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr);
  1140.             foreach ($offerInfo as $key => $value) {
  1141.                 $response[$value['offerId']] = [
  1142.                     'id' => (int)$value['offerId'],
  1143.                     'name' => $value['name']
  1144.                 ];
  1145.             }
  1146.         }
  1147.         return $response;
  1148.     }
  1149.     public function checkOfferAffiliateCapping($offerId$affiliateId$goalId)
  1150.     {
  1151.         $offerInfo $this->doctrine->getRepository(OfferInfo::class)->getOfferDataByOfferId($offerId);
  1152.         if (!$offerInfo) {
  1153.             return false;
  1154.         }
  1155.         $conversionCapByOfferIdHOData $this->brandApi->getCappingByOfferId($offerId)['response']['data'];
  1156.         $conversionCap $offerInfo->getConversionCap();
  1157.         $payoutCap $offerInfo->getPayoutCap();
  1158.         $revenueCap $offerInfo->getRevenueCap();
  1159.         $monthlyConversionCap $offerInfo->getMonthlyConversionCap();
  1160.         $monthlyPayoutCap $offerInfo->getMonthlyPayoutCap();
  1161.         $monthlyRevenueCap $offerInfo->getMonthlyRevenueCap();
  1162.         foreach ($conversionCapByOfferIdHOData as $key => $value) {
  1163.             if ($value['OfferConversionCap']['offer_id'] == $offerId && $value['OfferConversionCap']['affiliate_id'] == $affiliateId) {
  1164.                 $conversionCap $value['OfferConversionCap']['conversion_cap'];
  1165.                 $payoutCap $value['OfferConversionCap']['payout_cap'];
  1166.                 $revenueCap $value['OfferConversionCap']['revenue_cap'];
  1167.                 $monthlyConversionCap $value['OfferConversionCap']['monthly_conversion_cap'];
  1168.                 $monthlyPayoutCap $value['OfferConversionCap']['monthly_payout_cap'];
  1169.                 $monthlyRevenueCap $value['OfferConversionCap']['monthly_revenue_cap'];
  1170.                 break;
  1171.             }
  1172.         }
  1173.         $dailyConversionGenerated 0;
  1174.         $dailyPayoutGenerated 0;
  1175.         $dailyRevenueGenerated 0;
  1176.         $monthlyConversionGenerated 0;
  1177.         $monthlyPayoutGenerated 0;
  1178.         $monthlyRevenueGenerated 0;
  1179.         $statByDay $this->brandApi->getStatsForCappingCheck($offerId$affiliateId$goalIdtruefalse)['response']['data']['data'];
  1180.         if (!empty($statByDay)) {
  1181.             $dailyConversionGenerated $statByDay[0]['Stat']['conversions'];
  1182.             $dailyPayoutGenerated $statByDay[0]['Stat']['payout'];
  1183.             $dailyRevenueGenerated $statByDay[0]['Stat']['revenue'];
  1184.         }
  1185.         $statByMonth $this->brandApi->getStatsForCappingCheck($offerId$affiliateId$goalIdfalsetrue)['response']['data']['data'];
  1186.         if (!empty($statByMonth) && isset($statByDay[0])) {
  1187.             $monthlyConversionGenerated $statByDay[0]['Stat']['conversions'];
  1188.             $monthlyPayoutGenerated $statByDay[0]['Stat']['payout'];
  1189.             $monthlyRevenueGenerated $statByDay[0]['Stat']['revenue'];
  1190.         }
  1191.         $conversionCapReached $dailyConversionGenerated >= $conversionCap && $conversionCap != 0;
  1192.         $payoutCapReached $dailyPayoutGenerated >= $payoutCap && $payoutCap != 0;
  1193.         $revenueCapReached $dailyRevenueGenerated >= $revenueCap && $revenueCap != 0;
  1194.         $monthlyConversionCapReached $monthlyConversionGenerated >= $monthlyConversionCap && $monthlyConversionCap != 0;
  1195.         $monthlyPayoutCapReached $monthlyPayoutGenerated >= $monthlyPayoutCap && $monthlyPayoutCap != 0;
  1196.         $monthlyRevenueCapReached $monthlyRevenueGenerated >= $monthlyRevenueCap && $monthlyRevenueCap != 0;
  1197.         $cappingReached false;
  1198.         if ($conversionCapReached || $payoutCapReached || $revenueCapReached || $monthlyConversionCapReached || $monthlyPayoutCapReached || $monthlyRevenueCapReached) {
  1199.             $cappingReached true;
  1200.         }
  1201.         return [
  1202.             'conversionCap' => $conversionCap,
  1203.             'payoutCap' => $payoutCap,
  1204.             'revenueCap' => $revenueCap,
  1205.             'monthlyConversionCap' => $monthlyConversionCap,
  1206.             'monthlyPayoutCap' => $monthlyPayoutCap,
  1207.             'monthlyRevenueCap' => $monthlyRevenueCap,
  1208.             'dailyConversionGenerated' => $dailyConversionGenerated,
  1209.             'dailyPayoutGenerated' => $dailyPayoutGenerated,
  1210.             'dailyRevenueGenerated' => $dailyRevenueGenerated,
  1211.             'monthlyConversionGenerated' => $monthlyConversionGenerated,
  1212.             'monthlyPayoutGenerated' => $monthlyPayoutGenerated,
  1213.             'monthlyRevenueGenerated' => $monthlyRevenueGenerated,
  1214.             'conversionCapReached' => $conversionCapReached,
  1215.             'payoutCapReached' => $payoutCapReached,
  1216.             'revenueCapReached' => $revenueCapReached,
  1217.             'monthlyConversionCapReached' => $monthlyConversionCapReached,
  1218.             'monthlyPayoutCapReached' => $monthlyPayoutCapReached,
  1219.             'monthlyRevenueCapReached' => $monthlyRevenueCapReached,
  1220.             'cappingReached' => $cappingReached
  1221.         ];
  1222.     }
  1223.     public function appsBlackAndWhiteList($data)
  1224.     {
  1225.         $dateRange 30;
  1226.         $minClicks 100;
  1227.         $dataToProcess = [];
  1228.         foreach ($data as $key => $value) {
  1229.             $value['offerId'] ? $dataToProcess['offer'][$value['offerId']][$value['param']][$value['listType']][] = $value['appId'] : false;
  1230.             $value['advertiserId'] ? $dataToProcess['advertiser'][$value['advertiserId']][$value['param']][$value['listType']][] = $value['appId'] : false;
  1231.             $value['affiliateId'] ? $dataToProcess['affiliate'][$value['affiliateId']][$value['param']][$value['listType']][] = $value['appId'] : false;
  1232.         }
  1233.         $dataToBlock = [];
  1234.         foreach ($dataToProcess as $entityType => $entity) {
  1235.             foreach ($entity as $entityId => $entityData) {
  1236.                 foreach ($entityData as $param => $paramData) {
  1237.                     $advertiserId $entityType == 'advertiser' $entityId null;
  1238.                     $affiliateId $entityType == 'affiliate' $entityId null;
  1239.                     $offerId $entityType == 'offer' $entityId null;
  1240.                     if ($advertiserId) {
  1241.                         $addedFrom Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_ADVERTISER;
  1242.                     } elseif ($affiliateId) {
  1243.                         $addedFrom Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_AFFILIATE;
  1244.                     } else {
  1245.                         $addedFrom Config::DISABLE_LINK_FROM_APPS_BLACK_AND_WHITE_LIST_BY_OFFER;
  1246.                     }
  1247.                     if ($advertiserId == null && $affiliateId == null && $offerId == null) {
  1248.                         continue;
  1249.                     }
  1250.                     $statData $this->brandApi->getStatsForAppBlackAndWhiteList($offerId$affiliateId$advertiserId$dateRange$minClicks$param)['response']['data']['data'];
  1251.                     foreach ($paramData as $listType => $appIds) {
  1252.                         foreach ($statData as $key => $value) {
  1253.                             $offerInfo $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $value['Stat']['offer_id']]);
  1254.                             if (
  1255.                                 !$offerInfo ||
  1256.                                 !in_array($offerInfo->getAppId(), $appIds)
  1257.                             ) {
  1258.                                 continue;
  1259.                             }
  1260.                             $temp = [
  1261.                                 'offerId' => $value['Stat']['offer_id'],
  1262.                                 'affiliateId' => $value['Stat']['affiliate_id'],
  1263.                                 'advertiserId' => $value['Stat']['advertiser_id'],
  1264.                                 'param' => $param,
  1265.                                 'paramValue' => $value['Stat'][$param],
  1266.                                 'clicks' => $value['Stat']['clicks'],
  1267.                                 'conversions' => $value['Stat']['conversions'],
  1268.                                 'addedFrom' => $addedFrom,
  1269.                                 'listType' => $listType
  1270.                             ];
  1271.                             if (array_key_exists('blacklist'$paramData) && in_array($value['Stat'][$param], $paramData['blacklist'])) {
  1272.                                 $dataToBlock[] = $temp;
  1273.                             }
  1274.                             if (array_key_exists('whitelist'$paramData) && !in_array($value['Stat'][$param], $paramData['whitelist'])) {
  1275.                                 $dataToBlock[] = $temp;
  1276.                             }
  1277.                         }
  1278.                     }
  1279.                 }
  1280.             }
  1281.         }
  1282.         return $dataToBlock;
  1283.     }
  1284.     public function setAffiliateOfferApproval($offerId$affiliateId$status$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  1285.     {
  1286.         $combinationExist $this->doctrine->getRepository(AffiliateOfferApproval::class)->checkIfOfferApproved($offerId$affiliateId$tuneAccount);
  1287.         if ($combinationExist && $combinationExist->getApprovalStatus() != $status) {
  1288.             $hoResponse $this->brandApi->setOfferApprovalForAffiliate($offerId$affiliateId$status$tuneAccount);
  1289.             if ($hoResponse['response']['status'] == 1) {
  1290.                 $this->doctrine->getRepository(AffiliateOfferApproval::class)->updateAffiliateOfferApprovalById($combinationExist->getId(), [
  1291.                     'approvalStatus' => $status
  1292.                 ]);
  1293.             }
  1294.         } elseif (!$combinationExist) {
  1295.             $hoResponse $this->brandApi->setOfferApprovalForAffiliate($offerId$affiliateId$status$tuneAccount);
  1296.             if ($hoResponse['response']['status'] == 1) {
  1297.                 $this->doctrine->getRepository(AffiliateOfferApproval::class)->insertToAffiliateOfferApproval(null$affiliateIdnull$offerIdnullnullnull$statusnullnull$tuneAccount);
  1298.             }
  1299.         }
  1300.     }
  1301.     public function disableLinkByExternalUrl($offerId$advertiserId$affiliateId$source$affSub2$affSub3$affSub5)
  1302.     {
  1303.         $stat = [
  1304.             'offerId' => $offerId,
  1305.             'advertiserId' => $advertiserId,
  1306.             'affiliateId' => $affiliateId,
  1307.             'source' => $source,
  1308.             'affSub2' => $affSub2,
  1309.             'affSub3' => $affSub3,
  1310.             'affSub5' => $affSub5
  1311.         ];
  1312.         $link Config::DISABLE_LINK_EXTERNAL_ENDPOINT '?token=' base64_encode(json_encode($stat));
  1313.         return $link;
  1314.     }
  1315.     public function getOfferInfoByKey($offerIdArr$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  1316.     {
  1317.         if (!is_array($offerIdArr) || !sizeof($offerIdArr)) {
  1318.             return [];
  1319.         }
  1320.         $offerData $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIdArr$tuneAccount);
  1321.         $offerInfo = [];
  1322.         foreach ($offerData as $key => $value) {
  1323.             $offerInfo[$value['offerId']] = $value;
  1324.         }
  1325.         return $offerInfo;
  1326.     }
  1327.     public function getMafoOfferInfoByKey($offerIdArr)
  1328.     {
  1329.         if (!is_array($offerIdArr) || !sizeof($offerIdArr)) {
  1330.             return [];
  1331.         }
  1332.         $offerData $this->doctrine->getRepository(MafoOffers::class)->getMafoOffersByOfferIdsArr($offerIdArr);
  1333.         $offerInfo = [];
  1334.         foreach ($offerData as $key => $value) {
  1335.             $offerInfo[$value['id']] = $value;
  1336.         }
  1337.         return $offerInfo;
  1338.     }
  1339.     public function getEmployeesByEmployeeId()
  1340.     {
  1341.         $cachedList $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_EMPLOYEES_LIST);
  1342.         if (!$cachedList) {
  1343.             $employeeList $this->getWarmedUpEmployeesByEmployeeId();
  1344.         } else {
  1345.             $employeeList json_decode($cachedListtrue);
  1346.         }
  1347.         ksort($employeeList);
  1348.         return $employeeList;
  1349.     }
  1350.     public function getWarmedUpEmployeesByEmployeeId()
  1351.     {
  1352.         $employeesData $this->doctrine->getRepository(Employees::class)->getEmployees();
  1353.         $data = [];
  1354.         foreach ($employeesData as $key => $value) {
  1355.             $data[$value['employeeId']] = [
  1356.                 'firstName' => $value['firstName'],
  1357.                 'lastName' => $value['lastName'],
  1358.                 'email' => $value['email'],
  1359.                 'fullName' => $value['fullName']
  1360.             ];
  1361.         }
  1362.         return $data;
  1363.     }
  1364.     public function getMd5ForMmpReport($advertiser$offerCountry$offerRegion$offerCity$appId$event$revenueModel$payoutModel)
  1365.     {
  1366.         return md5(strtolower($advertiser) . '#' strtolower($offerCountry) . '#' strtolower($offerRegion) . '#' strtolower($offerCity) . '#' strtolower($appId) . '#' strtolower($event) . '#' strtolower($revenueModel) . '#' strtolower($payoutModel));
  1367.     }
  1368.     public function updateAffiliateDBByIds($affiliateIds$metaData)
  1369.     {
  1370.         $createApiKeyIfNotExist $metaData['createApiKeyIfNotExist'] ?? false;
  1371.         $tuneAccount $metaData['tuneAccount'] ?? Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE;
  1372.         $affiliateInfoArr $this->brandApi->getAffiliateInfoByAffiliateIdsArr($affiliateIds$tuneAccount)['response']['data'];
  1373.         foreach ($affiliateInfoArr as $key => $value) {
  1374.             $affiliateDBInfo $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
  1375.             if ($affiliateDBInfo) {
  1376.                 $this->doctrine->getRepository(AffiliateInfo::class)->updateAffiliateInfoByAffiliateId($value['Affiliate']['id'], [
  1377.                     'status' => $value['Affiliate']['status'],
  1378.                     'accountManagerId' => $value['AccountManager'] !== null $value['AccountManager']['id'] : null,
  1379.                     'company' => $value['Affiliate']['company']
  1380.                 ], $tuneAccount);
  1381.             } else {
  1382.                 $this->doctrine->getRepository(AffiliateInfo::class)->insertToAffiliateInfo($value['Affiliate']['id'], $value['Affiliate']['company'], $value['AccountManager'] !== null $value['AccountManager']['id'] : null$value['Affiliate']['status'], $tuneAccount);
  1383.             }
  1384.             //            $this->mafoObjectsComponents->createOrUpdateAffiliate(Config::MAFO_SYSTEM_IDENTIFIER_TUNE, $value['Affiliate']['id']);
  1385.             //            $execCommand = "php " . $this->rootPath . "/bin/console app:updateCache " . Config::CACHE_REDIS_HO_AFFILIATE_LIST_FOR_MULTISELECT . " --env=prod > /dev/null &";
  1386.             //            exec($execCommand);
  1387.             if ($value['AffiliateUser'] !== null) {
  1388.                 foreach ($value['AffiliateUser'] as $k => $v) {
  1389.                     if ($v['status'] == Config::ACTIVE_STATUS) {
  1390.                         if ($createApiKeyIfNotExist) {
  1391.                             $apiKeyData $this->doctrine->getRepository(UserApiKey::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
  1392.                             if (!$apiKeyData) {
  1393.                                 $this->brandApi->generateApiKeyByUserId($k$tuneAccount);
  1394.                             }
  1395.                         }
  1396.                         $userApiData $this->brandApi->getUserApiKey($k)['response']['data'];
  1397.                         if ($userApiData) {
  1398.                             $userApiKey $this->doctrine->getRepository(UserApiKey::class)->findOneBy(['userId' => $k'tuneAccount' => $tuneAccount]);
  1399.                             if ($userApiKey) {
  1400.                                 $this->doctrine->getRepository(UserApiKey::class)->updateUserApiKeyByUserId($k, [
  1401.                                     'affiliateId' => $value['Affiliate']['id'],
  1402.                                     'userType' => $userApiData['user_type'],
  1403.                                     'apiKey' => $userApiData['api_key'],
  1404.                                     'apiKeyStatus' => $userApiData['status'],
  1405.                                     'userStatus' => $v['status']
  1406.                                 ], $tuneAccount);
  1407.                             } else {
  1408.                                 $this->doctrine->getRepository(UserApiKey::class)->insertToUserApiKey($value['Affiliate']['id'], $k$userApiData['user_type'], $userApiData['api_key'], $userApiData['status'], $v['status'], $tuneAccount);
  1409.                             }
  1410.                         }
  1411.                     }
  1412.                 }
  1413.             }
  1414.             if ($value['AccountManager'] !== null) {
  1415.                 $affiliateAccountManagerDBInfo $this->doctrine->getRepository(AffiliateAccountManager::class)->findOneBy(['affiliateId' => $value['Affiliate']['id'], 'tuneAccount' => $tuneAccount]);
  1416.                 if ($affiliateAccountManagerDBInfo) {
  1417.                     $this->doctrine->getRepository(AffiliateAccountManager::class)->updateDataByAffiliateId($value['Affiliate']['id'], [
  1418.                         'employeeId' => $value['AccountManager']['id'],
  1419.                         'email' => $value['AccountManager']['email'],
  1420.                         'firstName' => $value['AccountManager']['first_name'],
  1421.                         'lastName' => $value['AccountManager']['last_name'],
  1422.                         'status' => $value['AccountManager']['status'],
  1423.                     ], $tuneAccount);
  1424.                 } else {
  1425.                     $this->doctrine->getRepository(AffiliateAccountManager::class)->insertToAffiliateAccountManager($value['Affiliate']['id'], $value['AccountManager']['id'], $value['AccountManager']['email'], $value['AccountManager']['first_name'], $value['AccountManager']['last_name'], $value['AccountManager']['status'], $tuneAccount);
  1426.                 }
  1427.             }
  1428.             $affiliateTagRelationship $this->brandApi->getAffiliateTagRelationByAffiliateId($value['Affiliate']['id'], $tuneAccount);
  1429.             if ($affiliateTagRelationship['response']['status'] == 1) {
  1430.                 $affiliateTags = [];
  1431.                 foreach ($affiliateTagRelationship['response']['data']['data'] as $k => $v) {
  1432.                     !in_array($v['AffiliatesTags']['tag_id'], $affiliateTags) ? array_push($affiliateTags$v['AffiliatesTags']['tag_id']) : false;
  1433.                 }
  1434.                 $affiliateDBTagsData $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByAffiliateId($value['Affiliate']['id'], $tuneAccount);
  1435.                 $affiliateDBTags = [];
  1436.                 foreach ($affiliateDBTagsData as $k => $v) {
  1437.                     !in_array($v['tagId'], $affiliateDBTags) ? array_push($affiliateDBTags$v['tagId']) : false;
  1438.                 }
  1439.                 if ($affiliateDBTags != $affiliateTags) {
  1440.                     $this->doctrine->getRepository(AffiliateTagRelationship::class)->deleteAffiliateTagRelationshipByAffiliateId($value['Affiliate']['id'], $tuneAccount);
  1441.                     foreach ($affiliateTags as $affiliateTag) {
  1442.                         $this->doctrine->getRepository(AffiliateTagRelationship::class)->insertToAffiliateTagRelationship($affiliateTag$value['Affiliate']['id'], $tuneAccount);
  1443.                     }
  1444.                 }
  1445.             }
  1446.         }
  1447.     }
  1448.     public function updateAdvertiserDBById($advertiserId$metaData$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  1449.     {
  1450.         $this->updateAdvertiserDBByIds([$advertiserId], $tuneAccount);
  1451.         if ($this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $advertiserId'tuneAccount' => $tuneAccount])) {
  1452.             $advertiserDiscountType $metaData['advertiserDiscountType'] ?? Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT;
  1453.             $advertiserDiscountValue $metaData['advertiserDiscountValue'] ?? null;
  1454.             if ($advertiserDiscountValue || $advertiserDiscountValue 100) {
  1455.                 $advertiserDiscountType Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT;
  1456.                 $advertiserDiscountValue null;
  1457.             }
  1458.             $this->doctrine->getRepository(AdvertiserInfo::class)->updateAdvertiserInfoByAdvertiserId($advertiserId, [
  1459.                 'discountValue' => $advertiserDiscountType !== Config::ADVERTISER_DISCOUNT_TYPE_NO_DISCOUNT $advertiserDiscountValue 0,
  1460.                 'discountType' => $advertiserDiscountType,
  1461.             ], $tuneAccount);
  1462.         }
  1463.     }
  1464.     public function updateAdvertiserDBByIds($advertiserIds$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  1465.     {
  1466.         $advertiserInfoArr $this->brandApi->getAdvertiserInfoByAdvertiserIdsArr($advertiserIds$tuneAccount)['response']['data'];
  1467.         foreach ($advertiserInfoArr as $key => $value) {
  1468.             $advertiserDBInfo $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy([
  1469.                 'advertiserId' => $value['Advertiser']['id'],
  1470.                 'tuneAccount' => $tuneAccount
  1471.             ]);
  1472.             if ($advertiserDBInfo) {
  1473.                 $this->doctrine->getRepository(AdvertiserInfo::class)->updateAdvertiserInfoByAdvertiserId($value['Advertiser']['id'], [
  1474.                     'status' => $value['Advertiser']['status'],
  1475.                     'accountManagerId' => $value['AccountManager'] !== null $value['AccountManager']['id'] : null,
  1476.                     'company' => $value['Advertiser']['company']
  1477.                 ], $tuneAccount);
  1478.             } else {
  1479.                 $this->doctrine->getRepository(AdvertiserInfo::class)->insertToAdvertiserInfo($value['Advertiser']['id'], $value['Advertiser']['company'], $value['AccountManager'] !== null $value['AccountManager']['id'] : null$value['Advertiser']['status'], $tuneAccount);
  1480.             }
  1481.             // $this->mafoObjectsComponents->createOrUpdateAdvertiser(Config::MAFO_SYSTEM_IDENTIFIER_TUNE, $value['Advertiser']['id']);
  1482. //            $execCommand = "php " . $this->rootPath . "/bin/console app:updateCache " . Config::CACHE_REDIS_HO_ADVERTISER_LIST_FOR_MULTISELECT . " --env=prod > /dev/null &";
  1483. //            exec($execCommand);
  1484.             if ($value['AccountManager'] !== null) {
  1485.                 $affiliateAccountManagerDBInfo $this->doctrine->getRepository(AdvertiserAccountManager::class)->findOneBy(['advertiserId' => $value['Advertiser']['id']]);
  1486.                 if ($affiliateAccountManagerDBInfo) {
  1487.                     $this->doctrine->getRepository(AdvertiserAccountManager::class)->updateDataByAdvertiserId($value['Advertiser']['id'], [
  1488.                         'employeeId' => $value['AccountManager']['id'],
  1489.                         'email' => $value['AccountManager']['email'],
  1490.                         'firstName' => $value['AccountManager']['first_name'],
  1491.                         'lastName' => $value['AccountManager']['last_name'],
  1492.                         'status' => $value['AccountManager']['status'],
  1493.                     ], $tuneAccount);
  1494.                 } else {
  1495.                     $this->doctrine->getRepository(AdvertiserAccountManager::class)->insertToAdvertiserAccountManager($value['Advertiser']['id'], $value['AccountManager']['id'], $value['AccountManager']['email'], $value['AccountManager']['first_name'], $value['AccountManager']['last_name'], $value['AccountManager']['status'], $tuneAccount);
  1496.                 }
  1497.             }
  1498.             $advertiserTagRelationship $this->brandApi->getAdvertiserTagRelationByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
  1499.             if ($advertiserTagRelationship['response']['status'] == 1) {
  1500.                 $advertiserTags = [];
  1501.                 foreach ($advertiserTagRelationship['response']['data']['data'] as $k => $v) {
  1502.                     !in_array($v['AdvertisersTags']['tag_id'], $advertiserTags) ? array_push($advertiserTags$v['AdvertisersTags']['tag_id']) : false;
  1503.                 }
  1504.                 $advertiserDBTagsData $this->doctrine->getRepository(AdvertiserTagRelationship::class)->getAdvertiserTagRelationshipByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
  1505.                 $advertiserDBTags = [];
  1506.                 foreach ($advertiserDBTagsData as $k => $v) {
  1507.                     !in_array($v['tagId'], $advertiserDBTags) ? array_push($advertiserDBTags$v['tagId']) : false;
  1508.                 }
  1509.                 if ($advertiserDBTags != $advertiserTags) {
  1510.                     $this->doctrine->getRepository(AdvertiserTagRelationship::class)->deleteAdvertiserTagRelationshipByAdvertiserId($value['Advertiser']['id'], $tuneAccount);
  1511.                     foreach ($advertiserTags as $advertiserTag) {
  1512.                         $this->doctrine->getRepository(AdvertiserTagRelationship::class)->insertToAdvertiserTagRelationship($advertiserTag$value['Advertiser']['id'], $tuneAccount);
  1513.                     }
  1514.                 }
  1515.             }
  1516.         }
  1517.     }
  1518.     public function getEmployeesWithEmailAsKey()
  1519.     {
  1520.         $employeesData $this->doctrine->getRepository(Employees::class)->getEmployees();
  1521.         $employees = [];
  1522.         foreach ($employeesData as $key => $value) {
  1523.             $employees[strtolower($value['email'])] = $value;
  1524.         }
  1525.         return $employees;
  1526.     }
  1527.     public function getNewsletterBuilderTemplate($offerIds$introduction$unsubscribeEmailId '')
  1528.     {
  1529.         $offerInfoFromApi = [];
  1530.         if ($offerIds) {
  1531.             $offerInfoFromApi $this->doctrine->getRepository(OfferInfo::class)->getOffersByOfferIdsArr($offerIds);
  1532.         }
  1533.         $offerInfoByOfferId = [];
  1534.         foreach ($offerIds as $offerId) {
  1535.             foreach ($offerInfoFromApi as $key => $value) {
  1536.                 if ($offerId == $value['offerId']) {
  1537.                     $value['geos'] = json_decode($value['geoIdsJson'], true);
  1538.                     $offerInfoByOfferId[] = $value;
  1539.                 }
  1540.             }
  1541.         }
  1542.         return $this->template->render('components/newsletterBuilder.html.twig', [
  1543.             'offerDetails' => $offerInfoByOfferId,
  1544.             'introduction' => $introduction,
  1545.             'unsubscribeLink' => "http://firehose.mobupps.com/api/unsubscribe/" $unsubscribeEmailId
  1546.         ]);
  1547.     }
  1548.     public function getOfferGoalInfoByOfferGoalIdArrWithKeys($offerGoalIdArr)
  1549.     {
  1550.         $offerGoalData $this->doctrine->getRepository(OfferGoalsInfo::class)->getGoalInfoByGoalIdArr($offerGoalIdArr);
  1551.         $data = [];
  1552.         foreach ($offerGoalData as $key => $value) {
  1553.             $data[$value['goalId']] = $value;
  1554.         }
  1555.         return $data;
  1556.     }
  1557.     public function getSkadNetworkMessageSeparator()
  1558.     {
  1559.         return mb_chr(Config::SKADNETWORK_MESSAGE_SEPARATOR_CODE);
  1560.     }
  1561.     public function setCommandLoggerData($identifier$commandName$meta)
  1562.     {
  1563.         $identifierExists $this->doctrine->getRepository(CommandLogger::class)->findOneBy([
  1564.             'identifier' => $identifier
  1565.         ]);
  1566.         if (is_array($meta)) {
  1567.             $meta json_encode($meta);
  1568.         }
  1569.         $currentTimestamp strtotime('now');
  1570.         if (!$identifierExists) {
  1571.             $this->doctrine->getRepository(CommandLogger::class)->insertToCommandLogger($identifier$commandName$currentTimestampnullnullnull);
  1572.         } else {
  1573.             $this->doctrine->getRepository(CommandLogger::class)->updateCommandLoggerById($identifierExists->getId(), [
  1574.                 'endTimestamp' => $currentTimestamp,
  1575.                 'timestampDiff' => $currentTimestamp $identifierExists->getStartTimestamp(),
  1576.                 'meta' => $meta
  1577.             ]);
  1578.         }
  1579.     }
  1580.     public function getMafoUsersWithEmailIdAsKey()
  1581.     {
  1582.         $users $this->doctrine->getRepository('App\Entity\Users')->getUsers();
  1583.         $arr = [];
  1584.         foreach ($users as $key => $value) {
  1585.             $name explode(' '$value['name']);
  1586.             $value['firstName'] = $name[0];
  1587.             $arr[$value['email']] = $value;
  1588.         }
  1589.         return $arr;
  1590.     }
  1591.     
  1592.     public function checkAlertMetaExists($identifier$type)
  1593.     {
  1594.         $identifierExists $this->doctrine->getRepository(AlertMeta::class)->findOneBy(['identifier' => $identifier]);
  1595.         if (!$identifierExists) {
  1596.             $this->doctrine->getRepository(AlertMeta::class)->insertToAlertMeta($identifier$type);
  1597.             return false;
  1598.         } else {
  1599.             return true;
  1600.         }
  1601.     }
  1602.     public function getHourOffsetFromTimezoneString($timezone)
  1603.     {
  1604.         $hourOffset '+0:00';
  1605.         if (array_key_exists($timezoneConfig::TIMEZONES)) {
  1606.             $timezone Config::TIMEZONES[$timezone];
  1607.             $timezone explode(" "$timezone)[0];
  1608.             $timezone str_replace("(GMT"""$timezone);
  1609.             $hourOffset str_replace(")"""$timezone);
  1610.         }
  1611.         return $hourOffset;
  1612.     }
  1613.     public function processPendingPostback($postbackLogId)
  1614.     {
  1615.         $postbackLogData $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->findOneBy(['id' => $postbackLogId]);
  1616.         $endpoint $postbackLogData->getEndpoint();
  1617.         $appId $postbackLogData->getAppId();
  1618.         $campaignId $postbackLogData->getCampaignId();
  1619.         $payload json_decode($postbackLogData->getRequest(), true);
  1620.         $isAttributionSignatureValid $postbackLogData->getIsAttributionSignatureValid();
  1621.         $postbackTimestamp $postbackLogData->getDateInserted()->getTimestamp();
  1622.         $offerId null;
  1623.         $affiliateId null;
  1624.         $skadNetworkPostbackMappingExists null;
  1625.         if ($endpoint == Config::SKADNETWORK_POSTBACK_ENDPOINT_WMADV) {
  1626.             $skadNetworkPostbackMappingExists $this->doctrine->getRepository(SkadNetworkManualPostbackMapping::class)->findOneBy([
  1627.                 'appId' => $appId,
  1628.                 'campaignId' => $campaignId,
  1629.                 'isDeleted' => 0
  1630.             ]);
  1631.             if ($skadNetworkPostbackMappingExists) {
  1632.                 $offerId $skadNetworkPostbackMappingExists->getOfferId();
  1633.                 $affiliateId $skadNetworkPostbackMappingExists->getAffiliateId();
  1634.             }
  1635.         } else {
  1636.             $apiLogsData $this->doctrine->getRepository(SkadNetworkApiLogs::class)->findOneBy(['appId' => $appId'campaignId' => $campaignId]);
  1637.             if ($apiLogsData) {
  1638.                 $offerId $apiLogsData->getOfferId();
  1639.                 $affiliateId $apiLogsData->getAffiliateId();
  1640.             }
  1641.         }
  1642.         $postbacksToMake = [];
  1643.         if ($isAttributionSignatureValid && $postbackLogData->getDidWin()) {
  1644.             if ($offerId) {
  1645.                 $offerInfo $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $offerId]);
  1646.                 if ($offerInfo && $offerInfo->getSkadNetworkMmp() && in_array($offerInfo->getSkadNetworkMmp(), Config::SKADNETOWRK_MMP)) {
  1647.                     if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_ADJUST && $offerInfo->getSkadNetworkAdjustTracker()) {
  1648.                         $offerGeoRelationship $this->doctrine->getRepository(OfferGeoRelationship::class)->findOneBy(['offerId' => $offerInfo->getOfferId()]);
  1649.                         $postbackParams = [
  1650.                             'tracker' => $offerInfo->getSkadNetworkAdjustTracker(),
  1651.                             'sk_payload' => urlencode($payload),
  1652.                             'sk_ts' => strtotime('now')
  1653.                         ];
  1654.                         if ($offerGeoRelationship && $offerGeoRelationship->getGeo()) {
  1655.                             $postbackParams['country'] = strtolower($offerGeoRelationship->getGeo());
  1656.                         }
  1657.                         $postbacksToMake[] = [
  1658.                             'requestType' => Config::HTTP_METHOD_POST,
  1659.                             'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()] . '?' http_build_query($postbackParams),
  1660.                             'postbackForMmp' => true,
  1661.                             'skadNetworkMmp' => Config::SKADNETWORK_MMP_ADJUST
  1662.                         ];
  1663.                     } else if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_BRANCH) {
  1664.                         $postbacksToMake[] = [
  1665.                             'requestType' => Config::HTTP_METHOD_POST,
  1666.                             'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[Config::SKADNETWORK_MMP_BRANCH],
  1667.                             'postbackForMmp' => true,
  1668.                             'skadNetworkMmp' => Config::SKADNETWORK_MMP_BRANCH
  1669.                         ];
  1670.                         if ($skadNetworkPostbackMappingExists) {
  1671.                             if ($skadNetworkPostbackMappingExists->getBranchPartnerCampaignId()) {
  1672.                                 $payload['partner-campaign-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerCampaignId();
  1673.                             }
  1674.                             if ($skadNetworkPostbackMappingExists->getBranchPartnerCampaignName()) {
  1675.                                 $payload['partner-campaign-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerCampaignName();
  1676.                             }
  1677.                             if ($skadNetworkPostbackMappingExists->getBranchPartnerAdSetId()) {
  1678.                                 $payload['partner-ad-set-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdSetId();
  1679.                             }
  1680.                             if ($skadNetworkPostbackMappingExists->getBranchPartnerAdSetName()) {
  1681.                                 $payload['partner-ad-set-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdSetName();
  1682.                             }
  1683.                             if ($skadNetworkPostbackMappingExists->getBranchPartnerAdId()) {
  1684.                                 $payload['partner-ad-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdId();
  1685.                             }
  1686.                             if ($skadNetworkPostbackMappingExists->getBranchPartnerAdName()) {
  1687.                                 $payload['partner-ad-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerAdName();
  1688.                             }
  1689.                             if ($skadNetworkPostbackMappingExists->getBranchPartnerCreativeId()) {
  1690.                                 $payload['partner-creative-id'] = $skadNetworkPostbackMappingExists->getBranchPartnerCreativeId();
  1691.                             }
  1692.                             if ($skadNetworkPostbackMappingExists->getBranchPartnerCreativeName()) {
  1693.                                 $payload['partner-creative-name'] = $skadNetworkPostbackMappingExists->getBranchPartnerCreativeName();
  1694.                             }
  1695.                         }
  1696.                     } else if ($offerInfo->getSkadNetworkMmp() == Config::SKADNETWORK_MMP_APPSFLYER) {
  1697.                         //                        $payload['ad-network-campaign-id'] = $campaignId . "";
  1698.                         //                        $payload['ad-network-campaign-name'] = $offerId . "";
  1699.                         //                        $payload['ad-network-country-code'] = implode(",", json_decode($offerInfo->getGeoIdsJson(), true));
  1700.                         //                        $payload['timestamp'] = $postbackTimestamp;
  1701.                         //                        if($affiliateId) {
  1702.                         //                            $payload['source-app-id'] = $affiliateId."";
  1703.                         //                            $payload['ad-network-source-app-id'] = $affiliateId."";
  1704.                         //                        }
  1705.                         $postbacksToMake[] = [
  1706.                             'requestType' => Config::HTTP_METHOD_POST,
  1707.                             'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()],
  1708.                             'postbackForMmp' => true,
  1709.                             'skadNetworkMmp' => $offerInfo->getSkadNetworkMmp()
  1710.                         ];
  1711.                     } else {
  1712.                         $postbacksToMake[] = [
  1713.                             'requestType' => Config::HTTP_METHOD_POST,
  1714.                             'requestUrl' => Config::SKADNETOWRK_MMP_POSTBACK_URL[$offerInfo->getSkadNetworkMmp()],
  1715.                             'postbackForMmp' => true,
  1716.                             'skadNetworkMmp' => $offerInfo->getSkadNetworkMmp()
  1717.                         ];
  1718.                     }
  1719.                 }
  1720.             }
  1721.             if ($affiliateId) {
  1722.                 $affiliateInfo $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $affiliateId]);
  1723.                 if ($affiliateInfo && $affiliateInfo->getSkadNetworkPostbackUrl()) {
  1724.                     $postbacksToMake[] = [
  1725.                         'requestType' => Config::HTTP_METHOD_POST,
  1726.                         'requestUrl' => $affiliateInfo->getSkadNetworkPostbackUrl(),
  1727.                         'postbackForMmp' => false
  1728.                     ];
  1729.                 }
  1730.             }
  1731.             foreach ($postbacksToMake as $key => $value) {
  1732.                 $result false;
  1733.                 if ($value['requestType'] == Config::HTTP_METHOD_POST) {
  1734.                     $postdata json_encode($payload);
  1735.                     $ch curl_init($value['requestUrl']);
  1736.                     curl_setopt($chCURLOPT_SSL_VERIFYHOST0);
  1737.                     curl_setopt($chCURLOPT_SSL_VERIFYPEER0);
  1738.                     curl_setopt($chCURLOPT_POST1);
  1739.                     curl_setopt($chCURLOPT_POSTFIELDS$postdata);
  1740.                     curl_setopt($chCURLOPT_RETURNTRANSFER1);
  1741.                     curl_setopt($chCURLOPT_FOLLOWLOCATION1);
  1742.                     curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  1743.                     $result curl_exec($ch);
  1744.                     curl_close($ch);
  1745.                 } elseif ($value['requestType'] == Config::HTTP_METHOD_GET) {
  1746.                     $ch curl_init($value['requestUrl']);
  1747.                     curl_setopt($chCURLOPT_RETURNTRANSFER1);
  1748.                     curl_setopt($chCURLOPT_FOLLOWLOCATION1);
  1749.                     curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  1750.                     $result curl_exec($ch);
  1751.                     curl_close($ch);
  1752.                 }
  1753.                 if ($result) {
  1754.                     if (array_key_exists('postbackForMmp'$value) && $value['postbackForMmp']) {
  1755.                         if (
  1756.                             array_key_exists('skadNetworkMmp'$value) &&
  1757.                             $value['skadNetworkMmp'] == Config::SKADNETWORK_MMP_BRANCH
  1758.                         ) {
  1759.                             $result json_decode($resulttrue);
  1760.                             if (array_key_exists('id'$result)) {
  1761.                                 $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
  1762.                                     'isPostbackScheduledForMmp' => false,
  1763.                                     'branchPostbackId' => $result['id']
  1764.                                 ]);
  1765.                             }
  1766.                         } else if ($value['skadNetworkMmp'] == Config::SKADNETWORK_MMP_APPSFLYER) {
  1767.                             $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
  1768.                                 'isPostbackScheduledForMmp' => false
  1769.                             ]);
  1770.                         }
  1771.                     } else {
  1772.                         $this->doctrine->getRepository(SkadNetworkPostbackLogs::class)->updateSkadNetworkPostbackLogs($postbackLogId, [
  1773.                             'isPostbackScheduledForAffiliate' => false
  1774.                         ]);
  1775.                     }
  1776.                 }
  1777.             }
  1778.         }
  1779.     }
  1780.     public function getAppInfoByAppIdArrWithKeys($appIdArr)
  1781.     {
  1782.         $appData = [];
  1783.         if ($appIdArr) {
  1784.             $appData $this->doctrine->getRepository(AppInfo::class)->getDataByAppIds($appIdArr);
  1785.         }
  1786.         $arr = [];
  1787.         foreach ($appData as $key => $value) {
  1788.             $arr[$value['appId']] = $value;
  1789.         }
  1790.         return $arr;
  1791.     }
  1792.     public function getAppInfoWithKeys($fromCache true)
  1793.     {
  1794.         $arr = [];
  1795.         if ($fromCache) {
  1796.             $arr $this->elasticCache->redisGet(Config::CACHE_REDIS_APP_INFO_KEY);
  1797.         }
  1798.         if (!$arr) {
  1799.             $appData $this->doctrine->getRepository(AppInfo::class)->getAppIds();
  1800.             $arr = [];
  1801.             foreach ($appData as $key => $value) {
  1802.                 $arr[$value['appId']] = $value;
  1803.             }
  1804.         } else {
  1805.             $arr json_decode($arrtrue);
  1806.         }
  1807.         return $arr;
  1808.     }
  1809.     public function getDataFromJsonFile($jsonFileName)
  1810.     {
  1811.         $json file_get_contents($this->rootPath "/src/Resources/json/" $jsonFileName ".json");
  1812.         if (in_array($jsonFileName, [Config::JSON_FILE_FINANCIAL_TOOLS_GAP_CONTROLConfig::JSON_FILE_FINANCIAL_TOOLS_MAFO_GAP_CONTROL])) {
  1813.             $teamsByTeamId $this->usersComponents->getTeamsByTeamId();
  1814.             $usersByTeamId $this->usersComponents->getMafoUsersByTeamIds();
  1815.             $columnsData json_decode($jsontrue);
  1816.             foreach ($usersByTeamId as $teamId => $users) {
  1817.                 if (sizeof($users)) {
  1818.                     $columnsData[$teamsByTeamId[$teamId]['label'] . 'Cost'] = [
  1819.                         'header' => $teamsByTeamId[$teamId]['label'] . ' Media Cost',
  1820.                         'accessor' => $teamsByTeamId[$teamId]['label'] . 'Cost',
  1821.                         'percentageWidth' => 5,
  1822.                         'show' => true,
  1823.                         'disabled' => false,
  1824.                         'customClass' => 'text-right',
  1825.                         'category' => 'statistics',
  1826.                         'footerEnabled' => true,
  1827.                         'aggregate' => 'sum',
  1828.                         //                        'alwaysEnabled' => true
  1829.                     ];
  1830.                 }
  1831.             }
  1832.             $itemsToBePushedToEnd = ['totalAffiliateCost''gap'];
  1833.             $arrToBePushedToEnd = [];
  1834.             foreach ($itemsToBePushedToEnd as $key => $value) {
  1835.                 $arrToBePushedToEnd[$value] = $columnsData[$value];
  1836.                 unset($columnsData[$value]);
  1837.             }
  1838.             $columnsData array_merge($columnsData$arrToBePushedToEnd);
  1839.             $json json_encode($columnsData);
  1840.         }
  1841.         return json_decode($jsontrue);
  1842.     }
  1843.     public function changeColumnVisibilityForTable($tableColumns$selectedColumns$groupedColumns)
  1844.     {
  1845.         foreach ($tableColumns as $key => $value) {
  1846.             $tableColumns[$key]['show'] = false;
  1847.             foreach ($selectedColumns as $k => $v) {
  1848.                 if ($value['accessor'] === $k && $v !== 'undefined') {
  1849.                     $tableColumns[$key]['show'] = $v == '0' false true;
  1850.                     break;
  1851.                 }
  1852.             }
  1853.             foreach ($groupedColumns as $k => $v) {
  1854.                 if ($value['accessor'] === $k && $v !== 'undefined') {
  1855.                     $tableColumns[$key]['groupBy'] = !($v == '0');
  1856.                     !($v == '0') ? $tableColumns[$key]['show'] = true null;
  1857.                     break;
  1858.                 }
  1859.             }
  1860.         }
  1861.         return $tableColumns;
  1862.     }
  1863.     public function downloadCSV($tableColumns$data$reportNamePretty)
  1864.     {
  1865.         $reportName str_replace(" ""-"strtolower($reportNamePretty));
  1866.         $header = [];
  1867.         foreach ($tableColumns as $key => $value) {
  1868.             if ($value['show'] == 1) {
  1869.                 $headerValue = isset($value['Header']) ? $value['Header'] : (isset($value['header']) ? $value['header'] : null);
  1870.                 array_push($header$headerValue);
  1871.             }
  1872.         }
  1873.         $rows = [$header];
  1874.         foreach ($data as $key => $value) {
  1875.             $row = [];
  1876.             foreach ($tableColumns as $k => $v) {
  1877.                 if ($v['show'] == 1) {
  1878.                     if ($v['accessor'] == 'comments' && is_array($value[$v['accessor']])) {
  1879.                         $comments '';
  1880.                         foreach ($value[$v['accessor']] as $commentKey => $commentValue) {
  1881.                             $commentValue['comment'] = $commentValue['isDeleted'] ? "**This comment was deleted.**" $commentValue['comment'];
  1882.                             $comments .= "{$commentValue['addedByName']} [{$commentValue['dateInserted']}]: {$commentValue['comment']}\n";
  1883.                         }
  1884.                         $value[$v['accessor']] = $comments;
  1885.                     } elseif ($v['accessor'] == 'attachedFiles') {
  1886.                         $value[$v['accessor']] = $value['linkToFile'];
  1887.                     } elseif (is_array($value[$v['accessor']])) {
  1888.                         $items '';
  1889.                         if (array_key_exists('label'$value[$v['accessor']])) {
  1890.                             $items .= $value[$v['accessor']]['label'];
  1891.                         } else {
  1892.                             foreach ($value[$v['accessor']] as $kk => $vv) {
  1893.                                 if (array_key_Exists('label'$vv)) {
  1894.                                     $items .= $vv['label'] . "\n";
  1895.                                 }
  1896.                             }
  1897.                         }
  1898.                         $value[$v['accessor']] = $items;
  1899.                     }
  1900.                     array_push($row$value[$v['accessor']]);
  1901.                 }
  1902.             }
  1903.             $rows[] = $row;
  1904.         }
  1905.         $spreadsheet = new Spreadsheet();
  1906.         $spreadsheet->getProperties()->setCreator('MAFO')->setLastModifiedBy('MAFO')->setTitle($reportNamePretty ' Report')->setSubject($reportNamePretty)->setDescription($reportNamePretty);
  1907.         //        echo json_encode($rows);die;
  1908.         $spreadsheet->getActiveSheet()->fromArray($rowsnull'A1');
  1909.         header('Content-Type: application/vnd.ms-excel');
  1910.         header('Content-Disposition: attachment;filename="' $reportName '.xls"');
  1911.         header('Cache-Control: max-age=0');
  1912.         $writer IOFactory::createWriter($spreadsheet'Xls');
  1913.         $writer->save('php://output');
  1914.         exit;
  1915.     }
  1916.     public function getReportResponse($finalArr$tableColumns$limit$page$sortBy$sortType)
  1917.     {
  1918.         foreach ($finalArr as $key => $value) {
  1919.             foreach ($tableColumns as $k => $v) {
  1920.                 if (isset($v['footerEnabled'])) {
  1921.                     if (!array_key_exists('Footer'$v)) {
  1922.                         $tableColumns[$k]['Footer'] = 0;
  1923.                     }
  1924.                     if (array_key_exists($v['accessor'], $value)) {
  1925.                         $tableColumns[$k]['Footer'] += $value[$v['accessor']];
  1926.                     }
  1927.                 }
  1928.             }
  1929.         }
  1930.         foreach ($tableColumns as $key => $value) {
  1931.             if (isset($value['footerEnabled']) && isset($value['Footer'])) {
  1932.                 $tableColumns[$key]['Footer'] = round($value['Footer'], 2);
  1933.             }
  1934.         }
  1935.         if (sizeof($finalArr)) {
  1936.             $entity $finalArr[0];
  1937.             if (array_key_exists($sortBy$entity)) {
  1938.                 $sortFlag 3;
  1939.                 if ($sortType == Config::SORT_TYPE_ASC) {
  1940.                     $sortFlag 4;
  1941.                 }
  1942.                 array_multisort(array_column($finalArr$sortBy), $sortFlag$finalArr);
  1943.             }
  1944.         }
  1945.         $offset $limit * ($page 1);
  1946.         $totalRecordCount sizeof($finalArr);
  1947.         $noOfPages ceil($totalRecordCount $limit);
  1948.         $finalArr array_slice($finalArr$offset$limit);
  1949.         return [
  1950.             'response' => [
  1951.                 'success' => true,
  1952.                 'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  1953.                 'data' => [
  1954.                     'tableColumns' => $tableColumns,
  1955.                     'data' => $finalArr,
  1956.                     'metaData' => [
  1957.                         "total" => $totalRecordCount,
  1958.                         "limit" => $limit,
  1959.                         "page" => $page,
  1960.                         "pages" => $noOfPages
  1961.                     ]
  1962.                 ],
  1963.                 'error' => null
  1964.             ]
  1965.         ];
  1966.     }
  1967.     public function getDeductionForAdvertiserAndAffiliateForPeriod($offerId$advertiserId$affiliateId$startDate$endDate)
  1968.     {
  1969.         $totalDeduction 0;
  1970.         $approvedDeduction 0;
  1971.         if (
  1972.             $this->doctrine->getRepository(AdvertiserInfo::class)->findOneBy(['advertiserId' => $advertiserId]) &&
  1973.             $this->doctrine->getRepository(AffiliateInfo::class)->findOneBy(['affiliateId' => $affiliateId])
  1974.         ) {
  1975.             $deductionControlData $this->doctrine->getRepository(DeductionControl::class)->getDeductionControlData($offerId ? [$offerId] : [], $advertiserId ? [$advertiserId] : [], $affiliateId ? [$affiliateId] : [], [], [], $startDate$endDate0, []);
  1976.             foreach ($deductionControlData as $key => $value) {
  1977.                 $totalDeduction += $value['deductionValue'];
  1978.                 if ($value['status'] === Config::REVENUE_CONTROL_STATUS_APPROVED) {
  1979.                     $approvedDeduction += $value['deductionValue'];
  1980.                 }
  1981.             }
  1982.         }
  1983.         return [
  1984.             'advertiserId' => $advertiserId,
  1985.             'affiliateId' => $affiliateId,
  1986.             'totalDeduction' => round($totalDeduction2),
  1987.             'approvedDeduction' => round($approvedDeduction2),
  1988.         ];
  1989.     }
  1990.     public function getIndexedDeductionFromDeductionControlByAdvertiserAndAffiliate($startDate$endDate)
  1991.     {
  1992.         $indexedDeduction = [];
  1993.         $deductionControlData $this->doctrine->getRepository(DeductionControl::class)->getDeductionControlData([], [], [], [], [], $startDate$endDate0, []);
  1994.         foreach ($deductionControlData as $key => $value) {
  1995.             $deductionPeriod $value['deductionPeriod']->format('Y-m');
  1996.             if (!isset($indexedDeduction[$deductionPeriod])) {
  1997.                 $indexedDeduction[$deductionPeriod] = [];
  1998.             }
  1999.             if (!isset($indexedDeduction[$deductionPeriod][$value['advertiserId']])) {
  2000.                 $indexedDeduction[$deductionPeriod][$value['advertiserId']] = [];
  2001.             }
  2002.             if (!isset($indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']])) {
  2003.                 $indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']] = [
  2004.                     'advertiserId' => $value['advertiserId'],
  2005.                     'affiliateId' => $value['affiliateId'],
  2006.                     'totalDeduction' => 0,
  2007.                     'approvedDeduction' => 0
  2008.                 ];
  2009.             }
  2010.             $indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']]['totalDeduction'] += $value['deductionValue'];
  2011.             if ($value['status'] === Config::REVENUE_CONTROL_STATUS_APPROVED) {
  2012.                 $indexedDeduction[$deductionPeriod][$value['advertiserId']][$value['affiliateId']]['approvedDeduction'] += $value['deductionValue'];
  2013.             }
  2014.         }
  2015.         return $indexedDeduction;
  2016.     }
  2017.     public function detectCSVDelimiter($csvFile)
  2018.     {
  2019.         $delimiters = [";" => 0"," => 0"\t" => 0"|" => 0];
  2020.         $handle fopen($csvFile"r");
  2021.         $firstLine fgets($handle);
  2022.         fclose($handle);
  2023.         foreach ($delimiters as $delimiter => &$count) {
  2024.             $count count(str_getcsv($firstLine$delimiter));
  2025.         }
  2026.         return array_search(max($delimiters), $delimiters);
  2027.     }
  2028.     public function assignTagsToOffers()
  2029.     {
  2030.         $activeOffers $this->doctrine->getRepository(OfferInfo::class)->getOfferInfoByStatus(Config::ACTIVE_STATUS);
  2031.         foreach ($activeOffers as $key => $value) {
  2032.             if ($value['offerUrl']) {
  2033.                 foreach (Config::HASOFFER_TRACKING_LINK_KEYWORDS_BY_TAG_ID as $k => $v) {
  2034.                     if ($k == Config::HASOFFER_ADJUST_OFFER_TAG_ID) {
  2035.                         $adjustAppDetails $this->doctrine->getRepository(AdjustAppDetails::class)->getAdjustAppDetails();
  2036.                         foreach ($adjustAppDetails as $kk => $vv) {
  2037.                             if (
  2038.                                 $this->checkForString($value['offerUrl'], $vv['appToken']) &&
  2039.                                 array_key_exists($vv['account'], Config::MMP_ADJUST_ACCOUNT_TUNE_TAG_MAPPING)
  2040.                             ) {
  2041.                                 $this->brandApi->addTagToOffer($value['offerId'], Config::MMP_ADJUST_ACCOUNT_TUNE_TAG_MAPPING[$vv['account']]);
  2042.                                 $this->populateDbByOfferId($value['offerId']);
  2043.                                 break 2;
  2044.                             }
  2045.                         }
  2046.                     } else {
  2047.                         foreach ($v as $subLink) {
  2048.                             if (
  2049.                                 isset($value['offerUrl']) &&
  2050.                                 $this->checkForString($value['offerUrl'], $subLink) &&
  2051.                                 !$this->doctrine->getRepository(OfferTagRelationship::class)->findOneBy(['tagId' => $k'offerId' => $value['offerId']])
  2052.                             ) {
  2053.                                 $this->brandApi->addTagToOffer($value['offerId'], $k);
  2054.                                 $this->populateDbByOfferId($value['offerId']);
  2055.                                 break 2;
  2056.                             }
  2057.                         }
  2058.                     }
  2059.                 }
  2060.             }
  2061.         }
  2062.     }
  2063.     public function getReportsRowWiseDataByAggregation($tableColumns$selectedColumns$rowWiseData)
  2064.     {
  2065.         $finalArr = [];
  2066.         foreach ($rowWiseData as $rowWiseIndex => $rowWiseValue) {
  2067.             $indexArr = [];
  2068.             foreach ($selectedColumns as $key => $value) {
  2069.                 if (
  2070.                     array_key_exists($key$tableColumns) &&
  2071.                     $value &&
  2072.                     in_array($tableColumns[$key]['category'], ['data_fields''item_interval'])
  2073.                 ) {
  2074.                     $indexArr[] = $rowWiseValue[$key];
  2075.                 }
  2076.             }
  2077.             $index md5(implode("#"$indexArr));
  2078.             if (!array_key_exists($index$finalArr)) {
  2079.                 foreach ($selectedColumns as $key => $value) {
  2080.                     if (array_key_exists($key$tableColumns) && $value && array_key_exists($key$rowWiseValue)) {
  2081.                         if (in_array($tableColumns[$key]['category'], ['data_fields''item_interval'])) {
  2082.                             $finalArr[$index][$key] = $rowWiseValue[$key];
  2083.                         }
  2084.                     }
  2085.                 }
  2086.                 foreach ($tableColumns as $key => $value) {
  2087.                     if ($value['category'] == 'statistics') {
  2088.                         $finalArr[$index][$key] = 0;
  2089.                     }
  2090.                 }
  2091.             }
  2092.             foreach ($tableColumns as $key => $value) {
  2093.                 if (
  2094.                     (
  2095.                         $value['category'] == 'statistics' && !isset($value['calculationType'])
  2096.                     ) ||
  2097.                     (
  2098.                         isset($value['calculationType']) && $value['category'] == 'statistics' && $value['calculationType'] != 'percentage'
  2099.                     )
  2100.                 ) {
  2101.                     $finalArr[$index][$key] += $rowWiseValue[$key];
  2102.                     $finalArr[$index][$key] = round($finalArr[$index][$key], 2);
  2103.                 }
  2104.             }
  2105.         }
  2106.         return $finalArr;
  2107.     }
  2108.     public function getPaginatedResponseForReports($reportData$tableColumns$selectedColumns$sortBy$sortType$limit$page)
  2109.     {
  2110.         $reportData array_values($reportData);
  2111.         if (sizeof($reportData)) {
  2112.             $entity $reportData[0];
  2113.             if (array_key_exists($sortBy$entity)) {
  2114.                 $sortFlag 3;
  2115.                 if ($sortType == Config::SORT_TYPE_ASC) {
  2116.                     $sortFlag 4;
  2117.                 }
  2118.                 array_multisort(array_column($reportData$sortBy), $sortFlag$reportData);
  2119.             }
  2120.         }
  2121.         $offset $limit * ($page 1);
  2122.         $totalRecordCount sizeof($reportData);
  2123.         $noOfPages ceil($totalRecordCount $limit);
  2124.         foreach ($tableColumns as $key => $value) {
  2125.             if (isset($value['aggregate'])) {
  2126.                 if ($value['aggregate'] == 'sum') {
  2127.                     $tableColumns[$key]['Footer'] = number_format(round(array_sum(array_column($reportData$value['accessor'])), 2));
  2128.                 }
  2129.                 if ($value['aggregate'] == 'average' && count($reportData) > 0) {
  2130.                     $tableColumns[$key]['Footer'] = number_format(round(array_sum(array_column($reportData$value['accessor'])) / count($reportData), 2));
  2131.                 }
  2132.             }
  2133.         }
  2134.         $tableColumns $this->changeColumnVisibilityForTable(array_values($tableColumns), $selectedColumns, []);
  2135.         return [
  2136.             'response' => [
  2137.                 'success' => true,
  2138.                 'httpStatus' => Config::HTTP_STATUS_CODE_OK,
  2139.                 'data' => [
  2140.                     'tableColumns' => array_values($tableColumns),
  2141.                     'data' => array_slice($reportData$offset$limit),
  2142.                     'metaData' => [
  2143.                         'total' => $totalRecordCount,
  2144.                         'limit' => (int)$limit,
  2145.                         'page' => (int)$page,
  2146.                         'pages' => (int)$noOfPages,
  2147.                     ]
  2148.                 ],
  2149.                 'error' => null
  2150.             ]
  2151.         ];
  2152.     }
  2153.     public function getAffiliateCategoryByAffiliateId($tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  2154.     {
  2155.         $affiliateTagRelationshipData $this->doctrine->getRepository(AffiliateTagRelationship::class)->getAffiliateTagRelationshipByTagIdArr([Config::HASOFFER_AFFILIATE_CATEGORY_A_TAG_IDConfig::HASOFFER_AFFILIATE_CATEGORY_B_TAG_ID], $tuneAccount);
  2156.         $data = [];
  2157.         foreach ($affiliateTagRelationshipData as $key => $value) {
  2158.             $data[$key] = [
  2159.                 'category' => Config::HASOFFER_AFFILIATE_CATEGORY_ARRAY[$value['tagId']],
  2160.                 'affiliateId' => $value['affiliateId']
  2161.             ];
  2162.         }
  2163.         $affiliateData $this->doctrine->getRepository(AffiliateInfo::class)->getAffiliateListByArrToSearch([], $tuneAccount);
  2164.         foreach ($affiliateData as $key => $value) {
  2165.             if (!array_key_exists($value['affiliateId'], $data)) {
  2166.                 $data[$value['affiliateId']] = [
  2167.                     'category' => Config::HASOFFER_AFFILIATE_CATEGORY_UNCATEGORISED_TAG_NAME,
  2168.                     'affiliateId' => $value['affiliateId']
  2169.                 ];
  2170.             }
  2171.         }
  2172.         return $data;
  2173.     }
  2174.     public function getPidByOfferId($offerId$tuneAccount Config::MAFO_SYSTEM_IDENTIFIER_TUNE_MOBILE)
  2175.     {
  2176.         $tunePid null;
  2177.         $offerInfo $this->doctrine->getRepository(OfferInfo::class)->findOneBy(['offerId' => $offerId'tuneAccount' => $tuneAccount]);
  2178.         if ($offerInfo) {
  2179.             $parsedUrl parse_url($offerInfo->getOfferUrl());
  2180.             if (isset($parsedUrl['query'])) {
  2181.                 parse_str($parsedUrl['query'], $query);
  2182.                 if (isset($query['pid']) && in_array($query['pid'], Config::TUNE_APPSFLYER_PIDS)) {
  2183.                     $tunePid $query['pid'];
  2184.                 }
  2185.             }
  2186.         }
  2187.         return $tunePid;
  2188.     }
  2189.     public function getWhitelistIPsAppsflyerOrAdjust($offerUrl)
  2190.     {
  2191.         $whitelistIps = [];
  2192.         if (stripos($offerUrlConfig::APPSFLYER_DOMAIN) !== false) {
  2193.             $whitelistIps Config::WIZARD_APPSFLYER_WHITE_LIST;
  2194.         }
  2195.         if (
  2196.             stripos($offerUrlConfig::ADJUST_IO_DOMAIN) !== false
  2197.             || stripos($offerUrlConfig::ADJUST_COM_DOMAIN) !== false
  2198.         ) {
  2199.             $whitelistIps Config::WIZARD_ADJUST_WHITE_LIST;
  2200.         }
  2201.         return $whitelistIps;
  2202.     }
  2203.     public function updateNotificationUnreadCountByUser($userEmail$unreadNotificationCount)
  2204.     {
  2205.         $cacheKey Config::CACHE_REDIS_UNREAD_NOTIFICATION_COUNT_BY_USER $userEmail;
  2206.         if (is_null($this->elasticCache->redisGet($cacheKey))) {
  2207.             $userData $this->doctrine->getRepository(MafoUserNotifications::class)->findBy([
  2208.                 'sentToUserId' => $userEmail,
  2209.                 'isRead' => 0
  2210.             ]);
  2211.             $notificationCount count($userData);
  2212.         } else {
  2213.             $notificationCount $this->elasticCache->redisGet($cacheKey);
  2214.         }
  2215.         $unreadNotificationCount += $notificationCount;
  2216.         $this->elasticCache->redisSet($cacheKey$unreadNotificationCount);
  2217.     }
  2218.     public function getUnreadNotificationCountByUser($userEmail)
  2219.     {
  2220.         $cacheKey Config::CACHE_REDIS_UNREAD_NOTIFICATION_COUNT_BY_USER $userEmail;
  2221.         if (is_null($this->elasticCache->redisGet($cacheKey))) {
  2222.             $userData $this->doctrine->getRepository(MafoUserNotifications::class)->findBy([
  2223.                 'sentToUserId' => $userEmail,
  2224.                 'isRead' => 0
  2225.             ]);
  2226.             $notificationCount count($userData);
  2227.         } else {
  2228.             $notificationCount $this->elasticCache->redisGet($cacheKey);
  2229.         }
  2230.         return $notificationCount;
  2231.     }
  2232.     public function sendPushNotification($topic$topicData)
  2233.     {
  2234.         try {
  2235.             $update = new Update(
  2236.                 $topic,
  2237.                 $topicData
  2238.                 //               ,true
  2239.             );
  2240.             $this->hub->publish($update);
  2241.         } catch (\Exception $e) {
  2242.             $this->logger->error('Error occurred: ' $e);
  2243.         }
  2244.     }
  2245.     public function getEmployeesByUserId()
  2246.     {
  2247.         $cachedList $this->elasticCache->redisGet(Config::CACHE_REDIS_HO_EMPLOYEES_LIST);
  2248.         if (!$cachedList) {
  2249.             $employeeList $this->getWarmedUpUsersByUserId();
  2250.         } else {
  2251.             $employeeList json_decode($cachedListtrue);
  2252.         }
  2253.         ksort($employeeList);
  2254.         return $employeeList;
  2255.     }
  2256.     public function getWarmedUpUsersByUserId()
  2257.     {
  2258.         $employeesData $this->doctrine->getRepository(Users::class)->getEmployees();
  2259.         $data = [];
  2260.         foreach ($employeesData as $key => $value) {
  2261.             $data[$value['email']] = [
  2262.                 'firstName' => $value['name'],
  2263.                 'email' => $value['email']
  2264.             ];
  2265.         }
  2266.         return $data;
  2267.     }
  2268. }