src/Services/Common.php line 97

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