src/Services/Common.php line 171

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