src/Service/CustomNotificationService.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use Pimcore\Db;
  4. use Pimcore\Model\DataObject;
  5. use Pimcore\Model\DataObject\Customer;
  6. use Pimcore\Model\DataObject\Location;
  7. use Pimcore\Model\DataObject\AlertType;
  8. use Pimcore\Model\DataObject\AlertMaster;
  9. use App\Model\CustomNotificationLog\Listing;
  10. use Pimcore\Model\DataObject\AbstractObject;
  11. use Pimcore\Model\DataObject\CustomNotification;
  12. use Pimcore\Model\DataObject\AdvanceCustomNotification;
  13. use Pimcore\Model\DataObject\Data\ObjectMetadata;
  14. use Symfony\Component\Templating\EngineInterface;
  15. use Pimcore\Model\DataObject\MannedAlertSubscription;
  16. use Symfony\Component\Process\Process;
  17. use Symfony\Component\Process\Exception\ProcessFailedException;
  18. use Pimcore\Model\DataObject\UserGroup;
  19. class CustomNotificationService
  20. {
  21.     private $templating;
  22.     public function __construct(EngineInterface $templating)
  23.     {
  24.         $this->templating $templating;
  25.     }
  26.     public function subscribeAlerts($customer$locationIds$alertType$title$color$units$minValue$maxValue$weatherModel$alertOnEmail$alertOnSMS$calculate$duration,$frequency=1$logger$translator)
  27.     {
  28.         // try {
  29.         // retrieve customer by userId
  30.         if (!$customer instanceof Customer) {
  31.             throw new \Exception('Customer not found for userId:');
  32.         }
  33.         // retrieve location by locationId
  34.         // $location = DataObject::getById($locationId);
  35.         // if (!$location) {
  36.         //     throw new \Exception('Location not found for locationId: ' . $locationId);
  37.         // }
  38.         // retrieve alertType by alertType
  39.         $alertTypes = new  AlertMaster\Listing();
  40.         $alertTypes->addConditionParam("alertKey = ? AND units = ?", [$alertType$units]);
  41.         $alertType $alertTypes->current();
  42.         // $alertType = AlertMaster::getByAlertKey($alertType, true);
  43.         if (!$alertType) {
  44.             throw new \Exception('Alert type not found: ' $alertType);
  45.         }
  46.         if (count($locationIds)) {
  47.             $notificationIds = [];
  48.             foreach ($locationIds as $locationId) {
  49.                 $location DataObject::getById($locationId);
  50.                 if (!$location) {
  51.                     throw new \Exception('Location not found for locationId: ' $locationId);
  52.                 }
  53.                 $key \Pimcore\Model\Element\Service::getValidKey($alertType->getAlertKey(), 'object');
  54.                 // $customNotification = \Pimcore\Model\DataObject::getByPath('/CustomNotification/'.$customer->getEmail().'/'.$key.time());
  55.                 // if(!$customNotification){
  56.                 // }   
  57.                 $customNotification = new CustomNotification();
  58.                 $customNotification->setKey($key time() . rand(0100));
  59.                 $customNotification->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/Notification/CustomNotification/'));
  60.                 $customNotification->setTitle($title);
  61.                 $customNotification->setColor($color);
  62.                 $customNotification->setUnits($units);
  63.                 $customNotification->setMinValue($minValue);
  64.                 $customNotification->setMaxValue($maxValue);
  65.                 $customNotification->setWeatherModel($weatherModel);
  66.                 $customNotification->setAlertOnEmail($alertOnEmail);
  67.                 $customNotification->setAlertOnSMS($alertOnSMS);
  68.                 $customNotification->setLocation($location);
  69.                 // set metadata for user
  70.                 $objectArray = [];
  71.                 $objectMetadata = new DataObject\Data\ObjectMetadata('user', ['alert_on_email''alert_on_sms'],  $customer);
  72.                 $objectMetadata->setAlert_on_email($alertOnEmail);
  73.                 $objectMetadata->setAlert_on_sms($alertOnSMS);
  74.                 array_push($objectArray$objectMetadata);
  75.                 $customNotification->setUser($objectArray);
  76.                 $customNotification->setAlert($alertType);
  77.                 $customNotification->setStatus(true);
  78.                 $customNotification->setPublished(true);
  79.                 $customNotification->setCalculate($calculate);
  80.                 $customNotification->setDuration($duration);
  81.                 $customNotification->setFrequency($frequency);
  82.                 $customNotification->save();
  83.                 $notificationIds[] = $customNotification->getId();
  84.                 // Execute notification command if alertOnEmail is true
  85.                 // $hitCommand = $alertOnEmail == true || $alertOnEmail == '1' ? true : false;
  86.                 // if ($hitCommand) {
  87.                 //     $commandArguments = ['php', 'bin/console', 'app:get-custom-notification'];
  88.                 //     if ($customNotification->getId()) {
  89.                 //         $commandArguments[] = (string) $customNotification->getId(); // Cast ID to string if needed
  90.                 //     }
  91.                 //     $process = new Process($commandArguments);
  92.                 //     $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
  93.                 //     $process->setTimeout(300); // Set timeout to 300 seconds (5 minutes)
  94.                 //     try {
  95.                 //         $process->mustRun();
  96.                 //         $logger->info("Custom Notification command executed successfully: " . $process->getOutput());
  97.                 //         $result['success'] = true;
  98.                 //         $result['message'] = $process->getOutput();
  99.                 //     } catch (ProcessFailedException $exception) {
  100.                 //         $logger->error("Custom Notification command failed: " . $exception->getMessage());
  101.                 //         $result['success'] = false;
  102.                 //         $result['message'] = "Failed to execute Custom notification command.";
  103.                 //     }
  104.                 // }
  105.             }
  106.             \App\Lib\Utility::storeActivityLog($customNotification$customer$action 'create-user-custom-notification'$translator);
  107.             return ["success" => true"data" => $notificationIds"message" => $translator->trans("alert_created_successfully")];
  108.         }
  109.         return ["success" => false"data" => "Location is mandatory"];
  110.         // return ["success" => true, "data" => $customNotification->getId()];
  111.         // } catch (\Exception $ex) {
  112.         //     throw new \Exception($ex->getMessage());
  113.         // }
  114.     }
  115.     public function subscribeAlertsByTag($customer$tagIds$alertType$title$color$units$minValue$maxValue$weatherModel$alertOnEmail$alertOnSMS$calculate$duration$frequency=1$logger$translator)
  116.     {
  117.         if (!$customer instanceof Customer) {
  118.             throw new \Exception('Customer not found for userId:');
  119.         }
  120.         // retrieve alertType by alertType
  121.         $alertTypes = new  AlertMaster\Listing();
  122.         $alertTypes->addConditionParam("alertKey = ? AND units = ?", [$alertType$units]);
  123.         $alertType $alertTypes->current();
  124.         if (!$alertType) {
  125.             throw new \Exception('Alert type not found: ' $alertType);
  126.         }
  127.         $notificationIds = [];
  128.         if (count($tagIds)) {
  129.             foreach ($tagIds as $tagId) {
  130.                 $tag DataObject::getById($tagId);
  131.                 if (!$tag) {
  132.                     throw new \Exception('Tag not found for tagId: ' $tagId);
  133.                 }
  134.                 // Assuming Location::getByTag($tag) retrieves multiple locations associated with the tag
  135.                 $locations Location::getByTag($tag);
  136.                 foreach ($locations as $location) {
  137.                     $key \Pimcore\Model\Element\Service::getValidKey($alertType->getAlertKey(), 'object');
  138.                     $customNotification = new CustomNotification();
  139.                     $customNotification->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/Notification/CustomNotification/'));
  140.                     $customNotification->setKey($key time() . rand(0100));
  141.                     $customNotification->setTitle($title);
  142.                     $customNotification->setColor($color);
  143.                     $customNotification->setUnits($units);
  144.                     $customNotification->setMinValue($minValue);
  145.                     $customNotification->setMaxValue($maxValue);
  146.                     $customNotification->setWeatherModel($weatherModel);
  147.                     $customNotification->setAlertOnEmail($alertOnEmail);
  148.                     $customNotification->setAlertOnSMS($alertOnSMS);
  149.                     $customNotification->setTag($tag);
  150.                     $customNotification->setLocation($location);
  151.                     // set metadata for user
  152.                     $objectArray = [];
  153.                     $objectMetadata = new DataObject\Data\ObjectMetadata('user', ['alert_on_email''alert_on_sms'],  $customer);
  154.                     $objectMetadata->setAlert_on_email($alertOnEmail);
  155.                     $objectMetadata->setAlert_on_sms($alertOnSMS);
  156.                     array_push($objectArray$objectMetadata);
  157.                     $customNotification->setUser($objectArray);
  158.                     $customNotification->setAlert($alertType);
  159.                     $customNotification->setStatus(true);
  160.                     $customNotification->setPublished(true);
  161.                     $customNotification->setCalculate($calculate);
  162.                     $customNotification->setDuration($duration);
  163.                     $customNotification->setFrequency($frequency);
  164.                     $customNotification->save();
  165.                     $notificationIds[] = $customNotification->getId();
  166.                     // Execute notification command if alertOnEmail is true
  167.                     // $hitCommand = $alertOnEmail == true || $alertOnEmail == '1' ? true : false;
  168.                     // if ($hitCommand) {
  169.                     //     $commandArguments = ['php', 'bin/console', 'app:get-custom-notification'];
  170.                     //     if ($customNotification->getId()) {
  171.                     //         $commandArguments[] = (string) $customNotification->getId(); // Cast ID to string if needed
  172.                     //     }
  173.                     //     $process = new Process($commandArguments);
  174.                     //     $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
  175.                     //     $process->setTimeout(300); // Set timeout to 300 seconds (5 minutes)
  176.                     //     try {
  177.                     //         $process->mustRun();
  178.                     //         $logger->info("Custom Notification command executed successfully: " . $process->getOutput());
  179.                     //         $result['success'] = true;
  180.                     //         $result['message'] = $process->getOutput();
  181.                     //     } catch (ProcessFailedException $exception) {
  182.                     //         $logger->error("Custom Notification command failed: " . $exception->getMessage());
  183.                     //         $result['success'] = false;
  184.                     //         $result['message'] = "Failed to execute Custom notification command.";
  185.                     //     }
  186.                     // }
  187.                 }
  188.                 return ["success" => true"data" => $notificationIds"message" => $translator->trans("alert_created_successfully")];
  189.             }
  190.             return ["success" => false"data" => "Tag id is mandatory"];
  191.         }
  192.     }
  193.     public function unSubscribeAlerts($customer$locationId$alertType$translator)
  194.     {
  195.         try {
  196.             // retrieve customer by userId            
  197.             if (!$customer instanceof \Pimcore\Model\DataObject) {
  198.                 throw new \Exception('Customer not found');
  199.             }
  200.             // retrieve location by locationId
  201.             $location DataObject::getById($locationId);
  202.             if (!$location) {
  203.                 throw new \Exception('Location not found for locationId: ' $locationId);
  204.             }
  205.             // retrieve alertType by alertType
  206.             $alertType AlertMaster::getByAlertKey($alertTypetrue);
  207.             if (!$alertType) {
  208.                 throw new \Exception('Alert type not found: ' $alertType);
  209.             }
  210.             $customNotification = new CustomNotification\Listing();
  211.             // $customNotification->filterByUser($customer);
  212.             $customNotification->addConditionParam("user like '%," $customer->getId() . ",%'");
  213.             $customNotification->filterByLocation($location);
  214.             $customNotification->filterByAlert($alertType);
  215.             $customNotifications $customNotification->load();
  216.             if ($customNotifications) {
  217.                 foreach ($customNotifications as $customNotification) {
  218.                     $objectArray = ($customNotification) ? $customNotification->getUser() : [];
  219.                     if ($objectArray) {
  220.                         foreach ($objectArray as $key => $objUser) {
  221.                             // added below new line to remove the user from the array
  222.                             $currentUser $objUser->getObject();
  223.                             if ($currentUser->getId() == $customer->getId()) {
  224.                                 unset($objectArray[$key]);
  225.                             }
  226.                         }
  227.                     }
  228.                      // If no other users left, delete the customNotification
  229.                     if (empty($objectArray)) {
  230.                         $customNotification->delete();
  231.                         return ["success" => true"message" => $translator->trans("customer_notification_removed")];
  232.                     }
  233.                     $customNotification->setUser($objectArray);
  234.                     $customNotification->save();
  235.                     return ["success" => true"message" => $translator->trans("customer_notification_removed")];
  236.                 }
  237.             } else {
  238.                 return ["success" => false"message" => $translator->trans("notification_not_found")];
  239.             }
  240.             // if ($customNotifications) {
  241.             //     $customNotifications[0]->setStatus(false);
  242.             //     $customNotification = $customNotifications[0]->save();
  243.             //     $customNotification->delete();
  244.             //     return ["success" => true, "message" => $translator->trans("customer_notification_removed")];
  245.             // } else {
  246.             //     return ["success" => false, "message" => $translator->trans("notification_not_found")];
  247.             // }
  248.         } catch (\Exception $ex) {
  249.             throw new \Exception($ex->getMessage());
  250.         }
  251.     }
  252.     public function unSubscribeAlertsBulk($customer$notificationIds$translator)
  253.     {
  254.             $userId $customer->getId();
  255.             // retrieve customer by userId            
  256.             if (!$customer instanceof Customer) {
  257.                 return ["success" => false"message" => $translator->trans("customer_not_found")];
  258.             }
  259.             foreach ($notificationIds as $notificationId) {
  260.                 $notification CustomNotification::getById($notificationId);
  261.                 if (!$notification) {
  262.                     return ["success" => false"message" => $translator->trans('notification_not_found') . {$notificationId}"];
  263.                 }
  264.                 $existingUsers $notification->getUser();
  265.                 $remainingUsers = [];
  266.                 $userFound false;
  267.                 foreach ($existingUsers as $user) {
  268.                     // print_r($user->getObjectId());
  269.                     if ($user->getObjectId() && $user->getObjectId() == $userId) {
  270.                         $userFound true;
  271.                         continue; // skip this user (removing)
  272.                     }
  273.                     $remainingUsers[] = $user;
  274.                 }
  275.                 // Only act if the user was part of this notification
  276.                 if ($userFound) {
  277.                     if (count($remainingUsers) === 0) {
  278.                         // No other users â€” delete the notification
  279.                         $notification->delete();
  280.                         \App\Lib\Utility::storeActivityLog($notification$user$action 'delete-notification'$translator);
  281.                     } else {
  282.                         // Save updated user list
  283.                         $notification->setUser($remainingUsers);
  284.                         $notification->save();
  285.                     }
  286.                 }            
  287.             }
  288.             return ["success" => true"message" => $translator->trans("customer_notifications_removed")];
  289.     }
  290.     public function getUserAlerts($userId$locationId$params$paginator)
  291.     {
  292.         $response = [];
  293.         $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  294.         $page = isset($params['page']) ? $params['page'] : 1;
  295.         // retrieve customer by userId
  296.         $customer DataObject::getById($userId);
  297.         if (!$customer) {
  298.             throw new \Exception('Customer not found for userId: ' $userId);
  299.         }
  300.         $customerId $customer->getId();
  301.         if ($locationId 0) {
  302.             $locationId DataObject::getById($locationId);
  303.             if (!$locationId) {
  304.                 throw new \Exception('Location not found for userId: ' $locationId);
  305.             }
  306.         }
  307.         // Get All the Classes
  308.         $class = new \Pimcore\Model\DataObject\ClassDefinition();
  309.         $custom_notification $class->getDao()->getIdByName('CustomNotification');
  310.         $customer $class->getDao()->getIdByName('Customer');
  311.         $location $class->getDao()->getIdByName('Location');
  312.         $tag $class->getDao()->getIdByName('Tags');
  313.         $db Db::get();
  314.         $select $db->createQueryBuilder();
  315.         $select->select('notification.oo_id');
  316.         $select->from('object_' $custom_notification'notification');
  317.         //$select->leftJoin('notification', 'object_query_' . $customer, 'customer', 'customer.oo_id = notification.user__id');
  318.         $select->leftJoin('notification''object_query_' $location'location''location.oo_id = notification.location__id');
  319.         $select->leftJoin('location''object_query_' $tag'tag''tag.oo_id = location.Tag');
  320.         if (isset($params['title']) && !empty($params['title'])) {
  321.             $select->andWhere("notification.title LIKE " $db->quote("%" $params['title'] . "%"));
  322.         }
  323.         if (isset($params['color']) && !empty($params['color'])) {
  324.             $select->andWhere("notification.color LIKE " $db->quote("%" $params['color'] . "%"));
  325.         }
  326.         if (isset($params['calculation']) && !empty($params['calculation'])) {
  327.             $select->andWhere("notification.calculate LIKE " $db->quote("%" $params['calculation'] . "%"));
  328.         }
  329.         if (isset($params['weatherModel']) && !empty($params['weatherModel'])) {
  330.             $select->andWhere("notification.weatherModel LIKE " $db->quote("%" $params['weatherModel'] . "%"));
  331.         }
  332.         if (isset($params['tagId']) && !empty($params['tagId'])) {
  333.             $tagConditions = [];
  334.             foreach ($params['tagId'] as $tag) {
  335.                 $tagConditions[] = "location.Tag LIKE " $db->quote("%" $tag "%");
  336.             }
  337.             $select->andWhere(implode(' OR '$tagConditions));
  338.         }
  339.         $select->andWhere("notification.user like " $db->quote("%" $customerId "%"));
  340.         $select->andWhere("o_published = 1");
  341.         // $select->andWhere("notification.user__id = ".$db->quote($userId));
  342.         $select->orderBy('oo_id''DESC');
  343.         $select->groupBy(array('oo_id'));
  344.         // Bind parameters
  345.         $paginator $paginator->paginate(
  346.             $select,
  347.             $page,
  348.             $pageSize
  349.         );
  350.         if ($select) {
  351.             foreach ($paginator as $customNotification) {
  352.                 $customNotification DataObject\CustomNotification::getById($customNotification['oo_id'], true);
  353.                 if ($customNotification instanceof \Pimcore\Model\DataObject\CustomNotification) {
  354.                     if ($customNotification->getLocation() && $customNotification->getAlert()) {
  355.                         $tags = [];
  356.                         if ($customNotification->getLocation()) {
  357.                             foreach ($customNotification->getLocation()->getTag() as $tag) {
  358.                                 $tags[] = [
  359.                                     "id" => $tag->getId(),
  360.                                     "nameEn" => ($tag->getTagName('en') == "" || $tag->getTagName('en') == null) ? null $tag->getTagName('en'),
  361.                                     "nameAr" => ($tag->getTagName('ar') == "" || $tag->getTagName('ar') == null) ? null :  $tag->getTagName('ar'),
  362.                                     "metaDataEn" => ($tag->getMetaData('en') == "" || $tag->getMetaData('en') == null) ? null $tag->getMetaData('en'),
  363.                                     "metaDataAr" => ($tag->getMetaData('ar') == "" || $tag->getMetaData('ar') == null) ? null :  $tag->getMetaData('ar'),
  364.                                 ];
  365.                             }
  366.                         }
  367.                         $objectArray = ($customNotification) ? $customNotification->getUser() : [];
  368.                         $userMetaData = [];
  369.                         if ($objectArray) {
  370.                             foreach ($objectArray as $key => $objUser) {
  371.                                 $currentUser $objUser->getObject();
  372.                                 if ($currentUser->getId() == $userId) {
  373.                                     $userData $objUser->getData();
  374.                                     $userMetaData['alert_on_email'] = isset($userData['alert_on_email']) && $userData['alert_on_email'] == '1' true false;
  375.                                     $userMetaData['alert_on_sms'] = isset($userData['alert_on_sms']) && $userData['alert_on_sms'] == '1' true false;
  376.                                     break; // Stop the loop once a match is found
  377.                                 }
  378.                             }
  379.                         }
  380.                         $userGroups = [];
  381.                         if ($customNotification->getUserGroup()) {
  382.                             foreach ($customNotification->getUserGroup() as $userGroup) {
  383.                                 $userGroups[] = [
  384.                                     "id" => $userGroup->getId(),
  385.                                     "groupName_en" => $userGroup->getGroupName("en"),
  386.                                     "groupName_ar" => $userGroup->getGroupName("ar"),
  387.                                 ];
  388.                             }
  389.                         }
  390.                         $response[] = [
  391.                             "id" => $customNotification->getId(),
  392.                             'location_id' => ($customNotification->getLocation()) ? $customNotification->getLocation()->getId() : 0,
  393.                             "alert_type" => $customNotification->getAlert()->getName(),
  394.                             "alert_key" => $customNotification->getAlert()->getAlertKey(),
  395.                             "parameter_name_en" => $customNotification->getAlert()->getName("en"),
  396.                             "parameter_name_ar" => $customNotification->getAlert()->getName("ar"),
  397.                             "location_name" => $customNotification->getLocation()->getTitle(),
  398.                             "title" => $customNotification->gettitle(),
  399.                             "color" => $customNotification->getColor(),
  400.                             "color_ar" => (\App\Lib\Utility::getArabicTranslation($customNotification->getColor(), CUSTOM_NOTIFICATION_COLORS) ? \App\Lib\Utility::getArabicTranslation($customNotification->getColor(), CUSTOM_NOTIFICATION_COLORS) : ''),
  401.                             "units" => $customNotification->getunits(),
  402.                             "units_ar" => (\App\Lib\Utility::getArabicTranslationUnits($customNotification->getunits()) ? \App\Lib\Utility::getArabicTranslationUnits($customNotification->getunits()) : ''),
  403.                             "min_value" => $customNotification->getMinValue(),
  404.                             "max_value" => $customNotification->getMaxValue(),
  405.                             "weather_model" => $customNotification->getWeatherModel(),
  406.                             "alert_on_email" => $userMetaData['alert_on_email'],
  407.                             "alert_on_sms" => $userMetaData['alert_on_sms'],
  408.                             "calculation" => $customNotification->getCalculate(),
  409.                             "calculation_ar" => (\App\Lib\Utility::getArabicTranslation($customNotification->getCalculate(), CUSTOM_NOTIFICATION_CONDITION) ? \App\Lib\Utility::getArabicTranslation($customNotification->getCalculate(), CUSTOM_NOTIFICATION_CONDITION) : ''),
  410.                             "duration" => $customNotification->getDuration(),
  411.                             "frequency" => $customNotification->getFrequency(),
  412.                             "tags" => $tags,
  413.                             "userGroups" => $userGroups
  414.                         ];
  415.                     }
  416.                 }
  417.             }
  418.         }
  419.         return ["success" => true"data" => $response'paginationVariables' => $paginator->getPaginationData()];
  420.     }
  421.     public function getAlertMaster()
  422.     {
  423.         $response = [];
  424.         $alertMaster = new DataObject\AlertMaster\Listing();
  425.         $alertMaster->addConditionParam("isHidden is null OR isHidden = 0");
  426.         $alertMaster->setOrderKey("order");
  427.         $alertMaster->setOrder("asc");
  428.         $alertMasters $alertMaster->load();
  429.         if ($alertMasters) {
  430.             foreach ($alertMasters as $alertMaster) {
  431.                 $response[] = ["id" => $alertMaster->getId(), "name_en" => $alertMaster->getName('en'), "name_ar" => $alertMaster->getName('ar'), "alert_key" => $alertMaster->getAlertKey(), "meteo_matics_key" => $alertMaster->getMeteoMaticsKey(), "units" => $alertMaster->getUnits(), "unit_title" => $alertMaster->getUnitTitle('en'), "unit_title_ar" => $alertMaster->getUnitTitle('ar')];
  432.             }
  433.         }
  434.         return ["success" => true"data" => $response];
  435.     }
  436.     public function mannedAlertFilters()
  437.     {
  438.         $response = [];
  439.         $alertMaster = new DataObject\AlertStatus\Listing();
  440.         $alertMasters $alertMaster->load();
  441.         $imageTemplate = [];
  442.         if ($alertMasters) {
  443.             foreach ($alertMasters as $alertMaster) {
  444.                 //if(!in_array($alertMaster->getImageTemplate(),$imageTemplate)){
  445.                 $response['alert_status'][] = ["id" => $alertMaster->getAlertStatusId(), "name_en" => $alertMaster->getName('en'), "name_ar" => $alertMaster->getName('ar')];
  446.                 // $imageTemplate[] = $alertMaster->getName('en');
  447.                 // }
  448.             }
  449.         }
  450.         $regionMaster = new DataObject\Region\Listing();
  451.         $regionMasters $regionMaster->load();
  452.         if ($regionMasters) {
  453.             foreach ($regionMasters as $regionMaster) {
  454.                 $response['regions'][] = ["id" => $regionMaster->getRegionId(), "name_en" => $regionMaster->getName('en'), "name_ar" => $regionMaster->getName('ar')];
  455.             }
  456.         }
  457.         $alertHazardMaster = new DataObject\AlertHazard\Listing();
  458.         $alertHazardMasters $alertHazardMaster->load();
  459.         if ($alertHazardMasters) {
  460.             foreach ($alertHazardMasters as $alertHazardMaster) {
  461.                 $response['alert_hazards'][] = ["id" => $alertHazardMaster->getAlertHazardId(), "name_en" => $alertHazardMaster->getName('en'), "name_ar" => $alertHazardMaster->getName('ar')];
  462.             }
  463.         }
  464.         $alertTypeMaster = new DataObject\AlertType\Listing();
  465.         $alertTypeMasters $alertTypeMaster->load();
  466.         if ($alertTypeMasters) {
  467.             foreach ($alertTypeMasters as $alertTypeMaster) {
  468.                 $response['alert_type'][] = ["id" => $alertTypeMaster->getAlertTypeId(), "name_en" => $alertTypeMaster->getName('en'), "name_ar" => $alertTypeMaster->getName('ar')];
  469.             }
  470.         }
  471.         $alertActionMaster = new DataObject\AlertAction\Listing();
  472.         $alertActionMasters $alertActionMaster->load();
  473.         if ($alertActionMasters) {
  474.             $alertActionArr = [];
  475.             foreach ($alertActionMasters as $alertActionMaster) {
  476.                 //if(!in_array($alertActionMaster->getSeverity(),$alertActionArr)){
  477.                 $response['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "severity" => ucwords($alertActionMaster->getName('en'))];
  478.                 // $alertActionArr[] = $alertActionMaster->getSeverity();
  479.                 //}
  480.             }
  481.         }
  482.         return ["success" => true"data" => $response];
  483.     }
  484.     // public function getMannedAlerts($params, $paginator)
  485.     // {
  486.     //     $response = [];
  487.     //     $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  488.     //     $page = isset($params['page']) ? $params['page'] : 1;
  489.     //     $mannedAlert = new DataObject\MannedAlertNotification\Listing();
  490.     //     //$mannedAlert->setCondition("o_creationDate > " . strtotime('-2 days'));
  491.     //     if (!empty($params['alert_status'])) {
  492.     //         $alertStatusSql = null;
  493.     //         foreach ($params['alert_status'] as $alertStatus) {
  494.     //             $alertStatus = \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($alertStatus, true);
  495.     //             if ($alertStatus) {
  496.     //                 $alertStatusSql .= "alertStatus__id = " . $alertStatus->getId() . " OR ";
  497.     //             }
  498.     //         }
  499.     //         $mannedAlert->addConditionParam("(" . substr($alertStatusSql, 0, -3) . ")");
  500.     //     }
  501.     //     if (isset($params['id']) && !empty($params['id'])) {
  502.     //         $idSql = '';
  503.     //         $idSql .= "alertId = " . $params['id'] . " OR ";
  504.     //         $mannedAlert->addConditionParam("(" . substr($idSql, 0, -3) . ")");
  505.     //     }
  506.     //     if (!empty($params['alert_region'])) {
  507.     //         $alertRegionSql = null;
  508.     //         foreach ($params['alert_region'] as $alertRegionId) {
  509.     //             $alertRegion = \Pimcore\Model\DataObject\Region::getByRegionId($alertRegionId, true);
  510.     //             if ($alertRegion) {
  511.     //                 $alertRegionSql .= "region__id = " . $alertRegion->getId() . " OR ";
  512.     //             }
  513.     //         }
  514.     //         if (!empty($alertRegion)) {
  515.     //             $mannedAlert->addConditionParam("(" . substr($alertRegionSql, 0, -3) . ")");
  516.     //         }
  517.     //     }
  518.     //     // added filter for public portal 
  519.     //     if (isset($params['governorate_id']) && !empty($params['governorate_id'])) {
  520.     //         $alertGovernorateSql = null;
  521.     //         foreach ($params['governorate_id'] as $alertGovernorateId) {
  522.     //             $alertGovernorate = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($alertGovernorateId, true);
  523.     //             if ($alertGovernorate) {
  524.     //                 $alertGovernorateSql .= "governorates LIKE '%," . $alertGovernorate->getId() . ",%' OR ";
  525.     //             }
  526.     //         }
  527.     //         if (!empty($alertGovernorateSql)) {
  528.     //             $mannedAlert->addConditionParam("(" . substr($alertGovernorateSql, 0, -3) . ")");
  529.     //         }
  530.     //     }
  531.     //     if (!empty($params['alert_type'])) {
  532.     //         $alertTypeSql = null;
  533.     //         foreach ($params['alert_type'] as $alertTypeId) {
  534.     //             $alertType = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alertTypeId, true);
  535.     //             if ($alertType) {
  536.     //                 $alertTypeSql .= "alertType__id = " . $alertType->getId() . " OR ";
  537.     //             }
  538.     //         }
  539.     //         if (!empty($alertTypeSql)) {
  540.     //             $mannedAlert->addConditionParam("(" . substr($alertTypeSql, 0, -3) . ")");
  541.     //         }
  542.     //     }
  543.     //     if (!empty($params['alert_actions'])) {
  544.     //         $alertActionIdSql = "";
  545.     //         foreach ($params['alert_actions'] as $alertAction) {
  546.     //             $alertAction = \Pimcore\Model\DataObject\AlertAction::getByAlertActionId($alertAction, true);
  547.     //             if ($alertAction) {
  548.     //                 $alertActionIdSql .= "alertAction LIKE '%," . $alertAction->getId() . ",%' OR ";
  549.     //             }
  550.     //         }
  551.     //         if (!empty($alertActionIdSql)) {
  552.     //             $mannedAlert->addConditionParam("(" . substr($alertActionIdSql, 0, -3) . ")");
  553.     //         }
  554.     //     }
  555.     //     if (!empty($params['from_date'])  && !empty($params['to_date'])) {
  556.     //         // $mannedAlert->filterByFromDate($params['from_date'], ">=");
  557.     //         // $mannedAlert->filterByToDate($params['to_date'], "<=");
  558.     //         // $mannedAlert->filterByFromDate(strtotime($params['from_date']), ">=");
  559.     //         $mannedAlert->filterByToDate(time(), ">=");
  560.     //     }
  561.     //     $mannedAlert->setOrderKey("lastModifiedDate");
  562.     //     $mannedAlert->setOrder("desc");
  563.     //     $mannedAlerts = $mannedAlert->load();
  564.     //     // code for devide api which does not need pagination
  565.     //     if ($paginator == null) {
  566.     //         $count = 0;
  567.     //         foreach ($mannedAlerts as $mannedAlert) {
  568.     //             $response[$count] = [
  569.     //                 "id" => $mannedAlert->getAlertId(),
  570.     //                 "title" => $mannedAlert->getTitle(),
  571.     //                 "other_locations" => [
  572.     //                     "en" => ($mannedAlert->getotherLocation()) ? $mannedAlert->getotherLocation()->getName('en') : null,
  573.     //                     "ar" => ($mannedAlert->getotherLocation()) ? $mannedAlert->getotherLocation()->getName('ar') : null
  574.     //                 ],
  575.     //                 "alert_type" => [
  576.     //                     "id" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getAlertTypeId() : null,
  577.     //                     "en" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('en') : null,
  578.     //                     "ar" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('ar') : null,
  579.     //                     "color" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getColor() : null
  580.     //                 ],
  581.     //                 "fromDate" => $mannedAlert->getFromDate()->toDateTimeString(),
  582.     //                 "toDate" => $mannedAlert->getToDate()->toDateTimeString(),
  583.     //                 "lastModifiedDate" => $mannedAlert->getLastModifiedDate()->toDateTimeString(),
  584.     //                 "rawData" => $mannedAlert->getRawText(),
  585.     //                 "region" => [
  586.     //                     "id" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getRegionId() : null,
  587.     //                     "en" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('en') : null,
  588.     //                     "ar" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('ar') : null
  589.     //                 ],
  590.     //                 "alert_status" => [
  591.     //                     "id" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getalertStatusId() : null,
  592.     //                     "en" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('en') : null,
  593.     //                     "ar" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('ar') : null
  594.     //                 ]
  595.     //             ];
  596.     //             $alertHazards = $mannedAlert->getalertHazards();
  597.     //             if ($alertHazards) {
  598.     //                 foreach ($alertHazards as $alertHazard) {
  599.     //                     $response[$count]['alert_hazard'][] = ["id" => $alertHazard->getAlertHazardId(), "name_en" => $alertHazard->getName('en'), "name_ar" => $alertHazard->getName('ar')];
  600.     //                 }
  601.     //             }
  602.     //             $governorates = $mannedAlert->getGovernorates();
  603.     //             if ($governorates) {
  604.     //                 $alertJsonDecodeData =   json_decode($mannedAlert->getRawText());
  605.     //                 $governoratesData = $alertJsonDecodeData->governorates;
  606.     //                 foreach ($governorates as $governorate) {
  607.     //                     $isEnrireGovernorate = false;
  608.     //                     foreach ($governoratesData as $governorateData) {
  609.     //                         if ($governorateData->id == $governorate->getGovernoteId()) {
  610.     //                             if (count($governorateData->municipalities) == 0) {
  611.     //                                 $isEnrireGovernorate = true;
  612.     //                                 break;
  613.     //                             }
  614.     //                         }
  615.     //                     }
  616.     //                     $response[$count]['governorates'][] = ["id" => $governorate->getGovernoteId(), "name_en" => $governorate->getName('en'), "name_ar" => $governorate->getName('ar'), 'isEnrireGovernorate' => $isEnrireGovernorate];
  617.     //                 }
  618.     //             }
  619.     //             $alertActionMasters = $mannedAlert->getAlertAction();
  620.     //             if ($alertActionMasters) {
  621.     //                 foreach ($alertActionMasters as $alertActionMaster) {
  622.     //                     $response[$count]['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "name_en" => $alertActionMaster->getName('en'), "name_ar" => $alertActionMaster->getName('ar')];
  623.     //                 }
  624.     //             }
  625.     //             $alert = json_decode($mannedAlert->getRawText(), true);
  626.     //             // extra param js
  627.     //             $alertObj = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
  628.     //             $alertName = $alertObj->getName() ? $alertObj->getName() : '';
  629.     //             $alert['host'] = API_BASE_URL;
  630.     //             $alert['alertColor'] = $alertName;
  631.     //             $backgroundColor = '#fcb82526';
  632.     //             $borderColor = '#000000';
  633.     //             $textColor = '#000000';
  634.     //             if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
  635.     //                 $alertColorLower = strtolower(trim($alert['alertColor']));
  636.     //                 if ($alertColorLower === 'red') {
  637.     //                     $backgroundColor = '#f6000017';
  638.     //                     $borderColor = '#F60000';
  639.     //                     $textColor = '#F60000';
  640.     //                 } elseif ($alertColorLower === 'orange') {
  641.     //                     $backgroundColor = '#ff66001f';
  642.     //                     $borderColor = '#FF6600';
  643.     //                     $textColor = '#FF6600';
  644.     //                 } elseif ($alertColorLower === 'yellow') {
  645.     //                     $backgroundColor = '#fcb82526';
  646.     //                     $borderColor = '#FCB825';
  647.     //                     $textColor = '#FCB825';
  648.     //                 }
  649.     //             }
  650.     //             $alert['backgroundColor'] = $backgroundColor;
  651.     //             $alert['borderColor'] = $borderColor;
  652.     //             $alert['textColor'] = $textColor;
  653.     //             $alert['name'] = ""; // ned to fiex this 
  654.     //             if ($mannedAlert->getRawText()) {
  655.     //                 $html = $this->templating->render('web2print/_manned_alert_notification_en.html.twig', $alert);
  656.     //                 $response[$count]['message_en'] = $html;
  657.     //                 $html = $this->templating->render('web2print/_manned_alert_notification.html.twig', $alert);
  658.     //                 $response[$count]['message_ar'] = $html;
  659.     //             } else {
  660.     //                 $response[$count]['message'] = [];
  661.     //             }
  662.     //             $count++;
  663.     //         }
  664.     //         return ["success" => true, "data" => $response];
  665.     //     }
  666.     //     $paginator = $paginator->paginate(
  667.     //         $mannedAlerts,
  668.     //         $page,
  669.     //         $pageSize
  670.     //     );
  671.     //     if ($paginator) {
  672.     //         $count = 0;
  673.     //         foreach ($paginator as $mannedAlert) {
  674.     //             $response[$count] = [
  675.     //                 "id" => $mannedAlert->getAlertId(),
  676.     //                 "title" => $mannedAlert->getTitle(),
  677.     //                 "other_locations" => [
  678.     //                     "en" => ($mannedAlert->getotherLocation()) ? $mannedAlert->getotherLocation()->getName('en') : null,
  679.     //                     "ar" => ($mannedAlert->getotherLocation()) ? $mannedAlert->getotherLocation()->getName('ar') : null
  680.     //                 ],
  681.     //                 "alert_type" => [
  682.     //                     "id" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getAlertTypeId() : null,
  683.     //                     "en" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('en') : null,
  684.     //                     "ar" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('ar') : null,
  685.     //                     "color" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getColor() : null
  686.     //                 ],
  687.     //                 "fromDate" => $mannedAlert->getFromDate()->toDateTimeString(),
  688.     //                 "toDate" => $mannedAlert->getToDate()->toDateTimeString(),
  689.     //                 "lastModifiedDate" => $mannedAlert->getLastModifiedDate()->toDateTimeString(),
  690.     //                 "region" => [
  691.     //                     "id" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getRegionId() : null,
  692.     //                     "en" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('en') : null,
  693.     //                     "ar" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('ar') : null
  694.     //                 ],
  695.     //                 "alert_status" => [
  696.     //                     "id" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getalertStatusId() : null,
  697.     //                     "en" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('en') : null,
  698.     //                     "ar" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('ar') : null
  699.     //                 ]
  700.     //             ];
  701.     //             $alertHazards = $mannedAlert->getalertHazards();
  702.     //             if ($alertHazards) {
  703.     //                 foreach ($alertHazards as $alertHazard) {
  704.     //                     $response[$count]['alert_hazard'][] = ["id" => $alertHazard->getAlertHazardId(), "name_en" => $alertHazard->getName('en'), "name_ar" => $alertHazard->getName('ar')];
  705.     //                 }
  706.     //             }
  707.     //             $governorates = $mannedAlert->getGovernorates();
  708.     //             if ($governorates) {
  709.     //                 foreach ($governorates as $governorate) {
  710.     //                     $response[$count]['governorates'][] = ["id" => $governorate->getGovernoteId(), "name_en" => $governorate->getName('en'), "name_ar" => $governorate->getName('ar')];
  711.     //                 }
  712.     //             }
  713.     //             $alertActionMasters = $mannedAlert->getAlertAction();
  714.     //             if ($alertActionMasters) {
  715.     //                 foreach ($alertActionMasters as $alertActionMaster) {
  716.     //                     $response[$count]['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "name_en" => $alertActionMaster->getName('en'), "name_ar" => $alertActionMaster->getName('ar')];
  717.     //                 }
  718.     //             }
  719.     //             $alert = json_decode($mannedAlert->getRawText(), true);
  720.     //             // extra param js
  721.     //             $alertObj = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
  722.     //             $alertName = $alertObj->getName() ? $alertObj->getName() : '';
  723.     //             $alert['host'] = API_BASE_URL;
  724.     //             $alert['alertColor'] = $alertName;
  725.     //             $backgroundColor = '#fcb82526';
  726.     //             $borderColor = '#000000';
  727.     //             $textColor = '#000000';
  728.     //             if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
  729.     //                 $alertColorLower = strtolower(trim($alert['alertColor']));
  730.     //                 if ($alertColorLower === 'red') {
  731.     //                     $backgroundColor = '#f6000017';
  732.     //                     $borderColor = '#F60000';
  733.     //                     $textColor = '#F60000';
  734.     //                 } elseif ($alertColorLower === 'orange') {
  735.     //                     $backgroundColor = '#ff66001f';
  736.     //                     $borderColor = '#FF6600';
  737.     //                     $textColor = '#FF6600';
  738.     //                 } elseif ($alertColorLower === 'yellow') {
  739.     //                     $backgroundColor = '#fcb82526';
  740.     //                     $borderColor = '#FCB825';
  741.     //                     $textColor = '#FCB825';
  742.     //                 }
  743.     //             }
  744.     //             $alert['backgroundColor'] = $backgroundColor;
  745.     //             $alert['borderColor'] = $borderColor;
  746.     //             $alert['textColor'] = $textColor;
  747.     //             $alert['name'] = ""; // ned to fiex this 
  748.     //             if ($mannedAlert->getRawText()) {
  749.     //                 $html = $this->templating->render('web2print/_manned_alert_notification_en.html.twig', $alert);
  750.     //                 $response[$count]['message_en'] = $html;
  751.     //                 $html = $this->templating->render('web2print/_manned_alert_notification.html.twig', $alert);
  752.     //                 $response[$count]['message_ar'] = $html;
  753.     //             } else {
  754.     //                 $response[$count]['message'] = [];
  755.     //             }
  756.     //             $count++;
  757.     //         }
  758.     //     }
  759.     //     return ["success" => true, "total" => count($mannedAlerts), "data" => $response, "paginationVariables" => $paginator->getPaginationData()];
  760.     // }
  761.     public function getMannedAlerts($params$paginator)
  762.     {
  763.         $response = [];
  764.         $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  765.         $page = isset($params['page']) ? $params['page'] : 1;
  766.         $mannedAlert = new DataObject\EwsNotification\Listing();
  767.         $mannedAlert->filterByIsManned(1);
  768.         //$mannedAlert->setCondition("o_creationDate > " . strtotime('-2 days'));
  769.         if (!empty($params['alert_status'])) {
  770.             $alertStatusSql null;
  771.             foreach ($params['alert_status'] as $alertStatus) {
  772.                 $alertStatus \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($alertStatustrue);
  773.                 if ($alertStatus) {
  774.                     $alertStatusSql .= "alertStatus__id = " $alertStatus->getId() . " OR ";
  775.                 }
  776.             }
  777.             $mannedAlert->addConditionParam("(" substr($alertStatusSql0, -3) . ")");
  778.         }
  779.         if (isset($params['id']) && !empty($params['id'])) {
  780.             $idSql '';
  781.             $idSql .= "alertId = " $params['id'] . " OR ";
  782.             $mannedAlert->addConditionParam("(" substr($idSql0, -3) . ")");
  783.         }
  784.         if (!empty($params['alert_region'])) {
  785.             $alertRegionSql null;
  786.             foreach ($params['alert_region'] as $alertRegionId) {
  787.                 $alertRegion \Pimcore\Model\DataObject\Region::getByRegionId($alertRegionIdtrue);
  788.                 if ($alertRegion) {
  789.                     $alertRegionSql .= "region__id = " $alertRegion->getId() . " OR ";
  790.                 }
  791.             }
  792.             if (!empty($alertRegion)) {
  793.                 $mannedAlert->addConditionParam("(" substr($alertRegionSql0, -3) . ")");
  794.             }
  795.         }
  796.         // added filter for public portal 
  797.         if (isset($params['governorate_id']) && !empty($params['governorate_id'])) {
  798.             $alertGovernorateSql null;
  799.             foreach ($params['governorate_id'] as $alertGovernorateId) {
  800.                 $alertGovernorate \Pimcore\Model\DataObject\Governorate::getByGovernoteId($alertGovernorateIdtrue);
  801.                 if ($alertGovernorate) {
  802.                     $alertGovernorateSql .= "governorate LIKE '%," $alertGovernorate->getId() . ",%' OR ";
  803.                 }
  804.             }
  805.             if (!empty($alertGovernorateSql)) {
  806.                 $mannedAlert->addConditionParam("(" substr($alertGovernorateSql0, -3) . ")");
  807.             }
  808.         }
  809.         if (!empty($params['alert_type'])) {
  810.             $alertTypeSql null;
  811.             foreach ($params['alert_type'] as $alertTypeId) {
  812.                 $alertType \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alertTypeIdtrue);
  813.                 if ($alertType) {
  814.                     $alertTypeSql .= "alertType__id = " $alertType->getId() . " OR ";
  815.                 }
  816.             }
  817.             if (!empty($alertTypeSql)) {
  818.                 $mannedAlert->addConditionParam("(" substr($alertTypeSql0, -3) . ")");
  819.             }
  820.         }
  821.         if (!empty($params['alert_actions'])) {
  822.             $alertActionIdSql "";
  823.             foreach ($params['alert_actions'] as $alertAction) {
  824.                 $alertAction \Pimcore\Model\DataObject\AlertAction::getByAlertActionId($alertActiontrue);
  825.                 if ($alertAction) {
  826.                     $alertActionIdSql .= "alertAction LIKE '%," $alertAction->getId() . ",%' OR ";
  827.                 }
  828.             }
  829.             if (!empty($alertActionIdSql)) {
  830.                 $mannedAlert->addConditionParam("(" substr($alertActionIdSql0, -3) . ")");
  831.             }
  832.         }
  833.         if (!empty($params['from_date'])  && !empty($params['to_date'])) {
  834.             // $mannedAlert->filterByFromDate($params['from_date'], ">=");
  835.             // $mannedAlert->filterByToDate($params['to_date'], "<=");
  836.             // $mannedAlert->filterByFromDate(strtotime($params['from_date']), ">=");
  837.             $mannedAlert->filterByEndDate(time(), ">=");
  838.         }
  839.         $mannedAlert->setOrderKey("lastModifiedDate");
  840.         $mannedAlert->setOrder("desc");
  841.         $mannedAlerts $mannedAlert->load();
  842.         $timezone = new \DateTimeZone(TIMEZONE);
  843.         // code for devide api which does not need pagination
  844.         if ($paginator == null) {
  845.             $count 0;
  846.             foreach ($mannedAlerts as $mannedAlert) {
  847.                 $response[$count] = [
  848.                     "id" => $mannedAlert->getAlertId(),
  849.                     "title" => $mannedAlert->getTitle(),
  850.                     "other_locations" => [
  851.                         "en" => $mannedAlert->getOtherLocation(),
  852.                         "ar" => $mannedAlert->getOtherLocation()
  853.                     ],
  854.                     "alert_type" => [
  855.                         "id" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getAlertTypeId() : null,
  856.                         "en" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('en') : null,
  857.                         "ar" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('ar') : null,
  858.                         "color" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getColor() : null
  859.                     ],
  860.                     "fromDate" => $mannedAlert->getStartDate()->setTimezone($timezone)->toDateTimeString(),
  861.                     "toDate" => $mannedAlert->getEndDate()->setTimezone($timezone)->toDateTimeString(),
  862.                     "lastModifiedDate" => $mannedAlert->getLastModifiedDate()->toDateTimeString(),
  863.                     "rawData" => $mannedAlert->getRawText(),
  864.                     "region" => [
  865.                         "id" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getRegionId() : null,
  866.                         "en" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('en') : null,
  867.                         "ar" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('ar') : null
  868.                     ],
  869.                     "alert_status" => [
  870.                         "id" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getalertStatusId() : null,
  871.                         "en" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('en') : null,
  872.                         "ar" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('ar') : null
  873.                     ]
  874.                 ];
  875.                 $alertHazards $mannedAlert->getalertHazard();
  876.                 if ($alertHazards) {
  877.                     foreach ($alertHazards as $alertHazard) {
  878.                         $response[$count]['alert_hazard'][] = ["id" => $alertHazard->getAlertHazardId(), "name_en" => $alertHazard->getName('en'), "name_ar" => $alertHazard->getName('ar')];
  879.                     }
  880.                 }
  881.                 $governorates $mannedAlert->getGovernorate();
  882.                 if ($governorates) {
  883.                     $alertJsonDecodeData =   json_decode($mannedAlert->getRawText());
  884.                     $governoratesData $alertJsonDecodeData->governorates;
  885.                     foreach ($governorates as $governorate) {
  886.                         $isEnrireGovernorate false;
  887.                         $municipalities = [];
  888.                         foreach ($governoratesData as $governorateData) {
  889.                             if ($governorateData->id == $governorate->getGovernoteId()) {
  890.                                 if (count($governorateData->municipalities) == 0) {
  891.                                     $isEnrireGovernorate true;
  892.                                 } else {
  893.                                     foreach ($governorateData->municipalities as $municipality) {
  894.                                         $municipalities[] = [
  895.                                             "id" => $municipality->id,
  896.                                             "name_en" => $municipality->nameEn,
  897.                                             "name_ar" => $municipality->nameAr,
  898.                                             "longitude" => $municipality->longitude,
  899.                                             "latitude" => $municipality->latitude
  900.                                         ];
  901.                                     }
  902.                                 }
  903.                                 break;
  904.                             }
  905.                         }
  906.                         $response[$count]['governorates'][] = [
  907.                             "id" => $governorate->getGovernoteId(),
  908.                             "name_en" => $governorate->getName('en'),
  909.                             "name_ar" => $governorate->getName('ar'),
  910.                             'isEnrireGovernorate' => $isEnrireGovernorate,
  911.                             'municipalities' => $municipalities
  912.                         ];
  913.                     }
  914.                 }
  915.                 $alertActionMasters $mannedAlert->getAlertAction();
  916.                 if ($alertActionMasters) {
  917.                     foreach ($alertActionMasters as $alertActionMaster) {
  918.                         $response[$count]['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "name_en" => $alertActionMaster->getName('en'), "name_ar" => $alertActionMaster->getName('ar')];
  919.                     }
  920.                 }
  921.                 $alert json_decode($mannedAlert->getRawText(), true);
  922.                 // extra param js
  923.                 $alertObj \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
  924.                 $alertName $alertObj->getName() ? $alertObj->getName() : '';
  925.                 $alert['host'] = API_BASE_URL;
  926.                 $alert['alertColor'] = $alertName;
  927.                 $backgroundColor '#fcb82526';
  928.                 $borderColor '#000000';
  929.                 $textColor '#000000';
  930.                 if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
  931.                     $alertColorLower strtolower(trim($alert['alertColor']));
  932.                     if ($alertColorLower === 'red') {
  933.                         $backgroundColor '#f6000017';
  934.                         $borderColor '#F60000';
  935.                         $textColor '#F60000';
  936.                     } elseif ($alertColorLower === 'orange') {
  937.                         $backgroundColor '#ff66001f';
  938.                         $borderColor '#FF6600';
  939.                         $textColor '#FF6600';
  940.                     } elseif ($alertColorLower === 'yellow') {
  941.                         $backgroundColor '#fcb82526';
  942.                         $borderColor '#FCB825';
  943.                         $textColor '#FCB825';
  944.                     }
  945.                 }
  946.                 $alert['backgroundColor'] = $backgroundColor;
  947.                 $alert['borderColor'] = $borderColor;
  948.                 $alert['textColor'] = $textColor;
  949.                 $alert['name'] = ""// ned to fiex this 
  950.                 if ($mannedAlert->getRawText()) {
  951.                     $html $this->templating->render('web2print/_manned_alert_notification_en.html.twig'$alert);
  952.                     $response[$count]['message_en'] = $html;
  953.                     $html $this->templating->render('web2print/_manned_alert_notification.html.twig'$alert);
  954.                     $response[$count]['message_ar'] = $html;
  955.                 } else {
  956.                     $response[$count]['message'] = [];
  957.                 }
  958.                 $count++;
  959.             }
  960.             return ["success" => true"data" => $response];
  961.         }
  962.         $paginator $paginator->paginate(
  963.             $mannedAlerts,
  964.             $page,
  965.             $pageSize
  966.         );
  967.         if ($paginator) {
  968.             $count 0;
  969.             foreach ($paginator as $mannedAlert) {
  970.                 $response[$count] = [
  971.                     "id" => $mannedAlert->getAlertId(),
  972.                     "title" => $mannedAlert->getTitle(),
  973.                     "other_locations" => [
  974.                         "en" => $mannedAlert->getOtherLocation(),
  975.                         "ar" => $mannedAlert->getOtherLocation()
  976.                     ],
  977.                     "alert_type" => [
  978.                         "id" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getAlertTypeId() : null,
  979.                         "en" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('en') : null,
  980.                         "ar" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getName('ar') : null,
  981.                         "color" => ($mannedAlert->getAlertType()) ? $mannedAlert->getAlertType()->getColor() : null
  982.                     ],
  983.                     "fromDate" => $mannedAlert->getStartDate()->toDateTimeString(),
  984.                     "toDate" => $mannedAlert->getEndDate()->toDateTimeString(),
  985.                     "lastModifiedDate" => $mannedAlert->getLastModifiedDate()->toDateTimeString(),
  986.                     "region" => [
  987.                         "id" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getRegionId() : null,
  988.                         "en" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('en') : null,
  989.                         "ar" => ($mannedAlert->getRegion()) ? $mannedAlert->getRegion()->getName('ar') : null
  990.                     ],
  991.                     "alert_status" => [
  992.                         "id" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getalertStatusId() : null,
  993.                         "en" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('en') : null,
  994.                         "ar" => ($mannedAlert->getalertStatus()) ? $mannedAlert->getalertStatus()->getName('ar') : null
  995.                     ]
  996.                 ];
  997.                 $alertHazards $mannedAlert->getalertHazard();
  998.                 if ($alertHazards) {
  999.                     foreach ($alertHazards as $alertHazard) {
  1000.                         $response[$count]['alert_hazard'][] = ["id" => $alertHazard->getAlertHazardId(), "name_en" => $alertHazard->getName('en'), "name_ar" => $alertHazard->getName('ar')];
  1001.                     }
  1002.                 }
  1003.                 $governorates $mannedAlert->getGovernorate();
  1004.                 if ($governorates) {
  1005.                     foreach ($governorates as $governorate) {
  1006.                         $response[$count]['governorates'][] = ["id" => $governorate->getGovernoteId(), "name_en" => $governorate->getName('en'), "name_ar" => $governorate->getName('ar')];
  1007.                     }
  1008.                 }
  1009.                 $alertActionMasters $mannedAlert->getAlertAction();
  1010.                 if ($alertActionMasters) {
  1011.                     foreach ($alertActionMasters as $alertActionMaster) {
  1012.                         $response[$count]['alert_actions'][] = ["id" => $alertActionMaster->getAlertActionId(), "name_en" => $alertActionMaster->getName('en'), "name_ar" => $alertActionMaster->getName('ar')];
  1013.                     }
  1014.                 }
  1015.                 $alert json_decode($mannedAlert->getRawText(), true);
  1016.                 // extra param js
  1017.                 $alertObj \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
  1018.                 $alertName $alertObj->getName() ? $alertObj->getName() : '';
  1019.                 $alert['host'] = API_BASE_URL;
  1020.                 $alert['alertColor'] = $alertName;
  1021.                 $backgroundColor '#fcb82526';
  1022.                 $borderColor '#000000';
  1023.                 $textColor '#000000';
  1024.                 if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
  1025.                     $alertColorLower strtolower(trim($alert['alertColor']));
  1026.                     if ($alertColorLower === 'red') {
  1027.                         $backgroundColor '#f6000017';
  1028.                         $borderColor '#F60000';
  1029.                         $textColor '#F60000';
  1030.                     } elseif ($alertColorLower === 'orange') {
  1031.                         $backgroundColor '#ff66001f';
  1032.                         $borderColor '#FF6600';
  1033.                         $textColor '#FF6600';
  1034.                     } elseif ($alertColorLower === 'yellow') {
  1035.                         $backgroundColor '#fcb82526';
  1036.                         $borderColor '#FCB825';
  1037.                         $textColor '#FCB825';
  1038.                     }
  1039.                 }
  1040.                 $alert['backgroundColor'] = $backgroundColor;
  1041.                 $alert['borderColor'] = $borderColor;
  1042.                 $alert['textColor'] = $textColor;
  1043.                 $alert['name'] = ""// ned to fiex this 
  1044.                 if ($mannedAlert->getRawText()) {
  1045.                     $html $this->templating->render('web2print/_manned_alert_notification_en.html.twig'$alert);
  1046.                     $response[$count]['message_en'] = $html;
  1047.                     $html $this->templating->render('web2print/_manned_alert_notification.html.twig'$alert);
  1048.                     $response[$count]['message_ar'] = $html;
  1049.                 } else {
  1050.                     $response[$count]['message'] = [];
  1051.                 }
  1052.                 $count++;
  1053.             }
  1054.         }
  1055.         return ["success" => true"total" => count($mannedAlerts), "data" => $response"paginationVariables" => $paginator->getPaginationData()];
  1056.     }
  1057.     public function getAlertHistory($user$params)
  1058.     {
  1059.         $response = [];
  1060.         $alertHistory = new DataObject\AlertHistory\Listing();
  1061.         $alertHistory->filterByUser($user);
  1062.         if (!empty($params['location_id'])) {
  1063.             $location_id $params['location_id'];
  1064.             $alertHistory->addConditionParam("Location__id = ?"$location_id"AND");
  1065.         }
  1066.         if (!empty($params['title'])) {
  1067.             $title $params['title'];
  1068.             $alertHistory->addConditionParam("AdministrativeTitle LIKE ?""%$title%""AND");
  1069.         }
  1070.         $alertHistory->setOffset(!empty($params['offset']) ? $params['offset'] : 0);
  1071.         $alertHistory->setLimit(!empty($params['limit']) ? $params['limit'] : LIMIT_PER_PAGE);
  1072.         $alertHistory->setOrderKey("o_creationDate");
  1073.         $alertHistory->setOrder("desc");
  1074.         $alertHistorys $alertHistory->load();
  1075.         if ($alertHistorys) {
  1076.             foreach ($alertHistorys as $alertHistory) {
  1077.                 $response[] = [
  1078.                     "id" => $alertHistory->getId(),
  1079.                     "modification_date" => $alertHistory->getModificaitonDate()->toDateTimeString(),
  1080.                     "title" => $alertHistory->getAdministrativeTitle(),
  1081.                     "color" => $alertHistory->getColorCode(),
  1082.                     "units" => $alertHistory->getUnits(),
  1083.                     "min_value" => $alertHistory->getMinValue(),
  1084.                     "max_value" => $alertHistory->getMaxValue(),
  1085.                     "weather_model" => $alertHistory->getWeatherModel(),
  1086.                     "alert_enable" => $alertHistory->getAlertEnable(),
  1087.                     "alert_type" => $alertHistory->getAlertType(),
  1088.                     "location" => ($alertHistory->getLocation()) ? $alertHistory->getLocation()->getName() : '',
  1089.                     "user" => $alertHistory->getUser()->getEmail(),
  1090.                     "is_sent" => $alertHistory->getisSent(),
  1091.                 ];
  1092.             }
  1093.         }
  1094.         return ["success" => true"total" => count($alertHistorys), "data" => $response];
  1095.     }
  1096.     public function getCustomNotificationLog($id)
  1097.     {
  1098.         $notificationArr = [];
  1099.         $notificationLog = new Listing();
  1100.         if ($id) {
  1101.             $notificationLog->setCondition("customNotificationId = {$id}");
  1102.         }
  1103.         $notifications $notificationLog->load();
  1104.         if ($notifications) {
  1105.             $count 0;
  1106.             foreach ($notifications as $notification) {
  1107.                 $customNotification \Pimcore\Model\DataObject::getById($notification->getcustomNotificationId());
  1108.                 if ($customNotification) {
  1109.                     $notificationArr[$count]['id'] = $notification->getId();
  1110.                     $notificationArr[$count]['customNotificationId'] = $notification->getcustomNotificationId();
  1111.                     $notificationArr[$count]['datetime'] = $notification->getDatetime();
  1112.                     $notificationArr[$count]['thresholdValue'] = $notification->getthresholdValue();
  1113.                     $notificationArr[$count]['color'] = $notification->getColor();
  1114.                     $notificationArr[$count]['customNotificaiton'] = [
  1115.                         "id" => $customNotification->getId(),
  1116.                         'location_id' => ($customNotification->getLocation()) ? $customNotification->getLocation()->getId() : 0,
  1117.                         "alert_type" => $customNotification->getAlert()->getName(),
  1118.                         "alert_key" => $customNotification->getAlert()->getAlertKey(),
  1119.                         "location_name" => $customNotification->getLocation()->getName(),
  1120.                         "title" => $customNotification->gettitle(),
  1121.                         "color" => $customNotification->getColor(),
  1122.                         "units" => $customNotification->getunits(),
  1123.                         "min_value" => $customNotification->getMinValue(),
  1124.                         "max_value" => $customNotification->getMaxValue(),
  1125.                         "weather_model" => $customNotification->getWeatherModel(),
  1126.                         "alert_on_email" => $customNotification->getalertOnEmail(),
  1127.                         "alert_on_sms" => $customNotification->getalertOnSMS(),
  1128.                         "calculation" => $customNotification->getCalculate()
  1129.                     ];
  1130.                 }
  1131.             }
  1132.         }
  1133.         return $notificationArr;
  1134.     }
  1135.     public function getUserCustomNotificationByOrganization($params$organizationId$loggedInUser$paginator)
  1136.     {
  1137.         // try {
  1138.         $response = [];
  1139.         $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  1140.         $page = isset($params['page']) ? $params['page'] : 1;
  1141.         $organization \Pimcore\Model\DataObject::getById($organizationId);
  1142.         if (!$organization instanceof \Pimcore\Model\DataObject\Organization) {
  1143.             throw new \Exception("Organization does not exists");
  1144.         }
  1145.         // retrieve customer by userId  
  1146.         $customers = new Customer\Listing();
  1147.         $customers->filterByOrganization($organization);
  1148.         if ($customers->getCount() == 0) {
  1149.             throw new \Exception("Customer does not exists in this organization");
  1150.         }
  1151.         foreach ($customers as $customer) {
  1152.             $customNotifications = new CustomNotification\Listing();
  1153.             $customNotifications->addConditionParam("user like '%," $customer->getId() . ",%'");
  1154.             //filter by Name
  1155.             if (isset($params['search']) && !empty($params['search'])) {
  1156.                 $customNotifications->addConditionParam("title like '%" $params['search'] . "%'");
  1157.             }
  1158.             //filter by color
  1159.             if (isset($params['color']) && !empty($params['color'])) {
  1160.                 $customNotifications->addConditionParam("color like '%" $params['color'] . "%'");
  1161.             }
  1162.             //filter by calculation 
  1163.             if (isset($params['calculation']) && !empty($params['calculation'])) {
  1164.                 $customNotifications->addConditionParam("calculate like '%" $params['calculation'] . "%'");
  1165.             }
  1166.             //$customNotifications->filterByUser($customer);
  1167.             if ($customNotifications->getCount() > 0) {
  1168.                 foreach ($customNotifications as $customNotification) {
  1169.                     //  p_r($customNotification->getAlert());exit; 
  1170.                     if (count($customNotification->getUser()) > 0) {
  1171.                         foreach ($customNotification->getUser() as $user) {
  1172.                             $user $user->getObject();
  1173.                             if ($user instanceof Customer && $user->getId() != $loggedInUser->getId()) {
  1174.                                 if ($customNotification->getLocation() && $customNotification->getAlert()) {
  1175.                                     // Check if the entry already exists for this customer and notification
  1176.                                     $existingEntry array_filter(
  1177.                                         $response,
  1178.                                         function ($entry) use ($customNotification$user) {
  1179.                                             return (
  1180.                                                 $entry['id'] == $customNotification->getId() &&
  1181.                                                 $entry['customerId'] == $user->getId()
  1182.                                             );
  1183.                                         }
  1184.                                     );
  1185.                                     // Add the entry only if it doesn't exist
  1186.                                     if (empty($existingEntry)) {
  1187.                                         $response[] = [
  1188.                                             "id" => $customNotification->getId(),
  1189.                                             'location_id' => ($customNotification->getLocation()) ? $customNotification->getLocation()->getId() : 0,
  1190.                                             "alert_type" => $customNotification->getAlert()->getName(),
  1191.                                             "alert_key" => $customNotification->getAlert()->getAlertKey(),
  1192.                                             "location_name" => $customNotification->getLocation()->getName(),
  1193.                                             "title" => $customNotification->gettitle(),
  1194.                                             "color" => $customNotification->getColor(),
  1195.                                             "units" => $customNotification->getunits(),
  1196.                                             "min_value" => $customNotification->getMinValue(),
  1197.                                             "max_value" => $customNotification->getMaxValue(),
  1198.                                             "weather_model" => $customNotification->getWeatherModel(),
  1199.                                             "alert_on_email" => $customNotification->getalertOnEmail(),
  1200.                                             "alert_on_sms" => $customNotification->getalertOnSMS(),
  1201.                                             "calculation" => $customNotification->getCalculate(),
  1202.                                             "duration" => $customNotification->getDuration(),
  1203.                                             "customerId" => $user->getId(),
  1204.                                             "customerName" => $user->getName(),
  1205.                                             "customerEmail" => $user->getEmail()
  1206.                                         ];
  1207.                                     }
  1208.                                 }
  1209.                             }
  1210.                         }
  1211.                     }
  1212.                 }
  1213.             }
  1214.         }
  1215.         $paginator $paginator->paginate(
  1216.             $response,
  1217.             $page,
  1218.             $pageSize
  1219.         );
  1220.         // } catch (\Exception $e) {
  1221.         //     throw new \Exception($e->getMessage());
  1222.         // }
  1223.         return ["success" => true"data" => $paginator'paginationVariables' => $paginator->getPaginationData()];
  1224.     }
  1225.     public function updateSubscribeAlerts($customer$notificationId$locationId$alertType$title$color$units$minValue$maxValue$weatherModel$alertOnEmail$alertOnSMS$calculate$duration$frequency=1$translator)
  1226.     {
  1227.         // retrieve customer by userId
  1228.         if (!$customer instanceof Customer) {
  1229.             throw new \Exception('Customer not found for userId:');
  1230.         }
  1231.         // retrieve location by locationId
  1232.         $location DataObject::getById($locationId);
  1233.         if (!$location) {
  1234.             throw new \Exception('Location not found for locationId: ' $locationId);
  1235.         }
  1236.         // retrieve alertType by alertType
  1237.         $alertType AlertMaster::getByAlertKey($alertTypetrue);
  1238.         if (!$alertType) {
  1239.             throw new \Exception('Alert type not found: ' $alertType);
  1240.         }
  1241.         $customNotification \Pimcore\Model\DataObject::getById($notificationIdtrue);
  1242.         if (!$customNotification instanceof CustomNotification) {
  1243.             throw new \Exception('Custom notification not found with id.');
  1244.         }
  1245.         $customNotification->setTitle($title);
  1246.         $customNotification->setColor($color);
  1247.         $customNotification->setUnits($units);
  1248.         $customNotification->setMinValue($minValue);
  1249.         $customNotification->setMaxValue($maxValue);
  1250.         $customNotification->setWeatherModel($weatherModel);
  1251.         $customNotification->setLocation($location);
  1252.         $objectArray = ($customNotification) ? $customNotification->getUser() : [];
  1253.         if ($objectArray) {
  1254.             foreach ($objectArray as $key => $objUser) {
  1255.                 $currentUser $objUser->getObject();
  1256.                 if ($currentUser->getId() == $customer->getId()) {
  1257.                     unset($objectArray[$key]);
  1258.                     break; // Stop the loop once a match is found
  1259.                 }
  1260.             }
  1261.             $objectMetadata = new DataObject\Data\ObjectMetadata('user', ['token''alert_on_email''alert_on_sms'],  $customer);
  1262.             $objectMetadata->setToken("");
  1263.             $objectMetadata->setAlert_on_email($alertOnEmail);
  1264.             $objectMetadata->setAlert_on_sms($alertOnSMS);
  1265.             array_push($objectArray$objectMetadata);
  1266.             $customNotification->setUser($objectArray);
  1267.         }
  1268.         $customNotification->setAlert($alertType);
  1269.         $customNotification->setStatus(true);
  1270.         $customNotification->setPublished(true);
  1271.         $customNotification->setCalculate($calculate);
  1272.         $customNotification->setDuration($duration);
  1273.         $customNotification->setFrequency($frequency);
  1274.         $customNotification->save();
  1275.         return [
  1276.             "success" => true,
  1277.             "data" => [
  1278.                 "id" => $customNotification->getId()
  1279.             ],
  1280.             "message" => $translator->trans("update_successfully")
  1281.         ];
  1282.     }
  1283.     public function getCustomNotificationAlerts($params$paginator)
  1284.     {
  1285.         $response = [];
  1286.         $customNotifications = [];
  1287.         $customNotificationQuery = new CustomNotification\Listing();
  1288.         $color '';
  1289.         $condition '';
  1290.         $model '';
  1291.         if (!empty($params['color'])) {
  1292.             $color $params['color'];
  1293.             $customNotificationQuery->addConditionParam("color = ?"$color"AND");
  1294.         }
  1295.         if (!empty($params['condition'])) {
  1296.             $condition $params['condition'];
  1297.             $customNotificationQuery->addConditionParam("calculate = ?"$condition"AND");
  1298.         }
  1299.         if (!empty($params['model'])) {
  1300.             $model $params['model'];
  1301.             $customNotificationQuery->addConditionParam("weatherModel = ?"$model"AND");
  1302.         }
  1303.         $customNotificationQuery->setOffset(!empty($params['offset']) ? $params['offset'] : 0);
  1304.         $customNotificationQuery->setLimit(!empty($params['limit']) ? $params['limit'] : LIMIT_PER_PAGE);
  1305.         $customNotificationQuery->setOrder("desc");
  1306.         $customNotifications $customNotificationQuery->load();
  1307.         if (!empty($customNotifications)) {
  1308.             foreach ($customNotifications as $customNotification) {
  1309.                 $response[] = [
  1310.                     "id" => $customNotification->getId(),
  1311.                     'location_id' => ($customNotification->getLocation()) ? $customNotification->getLocation()->getId() : 0,
  1312.                     "alert_type" => $customNotification->getAlert()->getName(),
  1313.                     "alert_key" => $customNotification->getAlert()->getAlertKey(),
  1314.                     "location_name" => ($customNotification->getLocation()) ? $customNotification->getLocation()->getTitle() : '',
  1315.                     "title" => $customNotification->getTitle(),
  1316.                     "color" => $customNotification->getColor(),
  1317.                     "units" => $customNotification->getunits(),
  1318.                     "min_value" => $customNotification->getMinValue(),
  1319.                     "max_value" => $customNotification->getMaxValue(),
  1320.                     "weather_model" => $customNotification->getWeatherModel(),
  1321.                     "alert_on_email" => $customNotification->getalertOnEmail(),
  1322.                     "alert_on_sms" => $customNotification->getalertOnSMS(),
  1323.                     "calculation" => $customNotification->getCalculate(),
  1324.                 ];
  1325.             }
  1326.         }
  1327.         return ["success" => true"total" => count($customNotifications), "data" => $response];
  1328.     }
  1329.     public function customNotificationFilters($translator)
  1330.     {
  1331.         $response = [];
  1332.         $response[] = [
  1333.             "model" => \App\Lib\Utility::customNotificationWeatherModelList(),
  1334.             "parameters" => \App\Lib\Utility::customNotificationParametersList(),
  1335.             "colors" => \App\Lib\Utility::customNotificationConfigColorsList(),
  1336.             "condition" => \App\Lib\Utility::customNotificationConditionList(),
  1337.             "durations" => \App\Lib\Utility::customNotificationDurationsList($translator)
  1338.         ];
  1339.         return ["success" => true"data" => $response];
  1340.     }
  1341.     public function updateSubscribeNotification($token$translator)
  1342.     {
  1343.         $db Db::get();
  1344.         $select $db->createQueryBuilder();
  1345.         $select->select('cn.o_id AS cn_id''cn.dest_id  AS user_id''cn.auto_id  AS id')
  1346.             ->from('object_metadata_custom_notification''cn')
  1347.             ->andwhere('cn.column = :type')
  1348.             ->andwhere('cn.data = :token')
  1349.             ->setParameter('token'$token)
  1350.             ->setParameter('type''token');
  1351.         $result $select->execute()->fetchAllAssociative();
  1352.         if (empty($result)) {
  1353.             return ["success" => false"message" => $translator->trans("invalid_token")];
  1354.         }
  1355.         $result $result[0];
  1356.         $user \Pimcore\Model\DataObject\Customer::getById($result['user_id']);
  1357.         $customNotification \Pimcore\Model\DataObject\CustomNotification::getById($result['cn_id']);
  1358.         if ($customNotification instanceof \Pimcore\Model\DataObject\CustomNotification && $user instanceof \Pimcore\Model\DataObject\Customer) {
  1359.             $objectArray = ($customNotification) ? $customNotification->getUser() : [];
  1360.             if ($objectArray) {
  1361.                 foreach ($objectArray as $key => $objUser) {
  1362.                     $currentUser $objUser->getObject();
  1363.                     if ($currentUser->getId() == $user->getId()) {
  1364.                         unset($objectArray[$key]);
  1365.                         break; // Stop the loop once a match is found
  1366.                     }
  1367.                 }
  1368.                 $objectMetadata = new DataObject\Data\ObjectMetadata('user', ['token''alert_on_email''alert_on_sms'],  $user);
  1369.                 $objectMetadata->setToken("");
  1370.                 $objectMetadata->setAlert_on_email(false);
  1371.                 $objectMetadata->setAlert_on_sms(false);
  1372.                 array_push($objectArray$objectMetadata);
  1373.                 $customNotification->setUser($objectArray);
  1374.                 $customNotification->save();
  1375.             }
  1376.             return ["success" => true"message" => $translator->trans("you_have_successfully_unsubscribed_that_notification")];
  1377.         } else {
  1378.             return ["success" => false"message" => $translator->trans("notification_not_found")];
  1379.         }
  1380.     }
  1381.     public function unSubscribeEwsNotification($token$translator)
  1382.     {
  1383.         $user \Pimcore\Model\DataObject\Customer::getByEwsNotificationToken($tokentrue);
  1384.         if ($user) {
  1385.             $user->setEwsNotificationToken("");
  1386.             $user->setSendEwsEmail(false);
  1387.             $user->save();
  1388.             return ["success" => true"message" => $translator->trans("you_have_successfully_unsubscribed_that_notification")];
  1389.         } else {
  1390.             return ["success" => false"message" => $translator->trans("user_not_found")];
  1391.         }
  1392.     }
  1393.     public function mannedAlertSubscription($customer$params$translator)
  1394.     {
  1395.         $region_id = isset($params['region_id']) ? $params['region_id'] : null;
  1396.         $governorate_ids = isset($params['governorate_id']) ? (array)$params['governorate_id'] : [];
  1397.         $alert_status_id = isset($params['alert_status_id']) ? $params['alert_status_id'] : 0;
  1398.         $alert_type_ids = isset($params['alert_type_id']) ? $params['alert_type_id'] : [];
  1399.         $phenomena_ids = isset($params['phenomena_id']) ? $params['phenomena_id'] : [];
  1400.         $is_public = isset($params['is_public']) ? $params['is_public'] : false;
  1401.         $email = isset($params['email']) ? strtolower($params['email']) : '';
  1402.         $notifyEmail = isset($params['notifyEmail']) ? $params['notifyEmail'] : true;
  1403.         $notifySMS = isset($params['notifySMS']) ? $params['notifySMS'] : true;
  1404.         if (!$customer instanceof Customer) {
  1405.             return ["success" => false"message" => $translator->trans("customer_not_found_for_" $customer->getId())];
  1406.         }
  1407.         $alertRegion null;
  1408.         if ($region_id) {
  1409.             $alertRegion \Pimcore\Model\DataObject\Region::getByRegionId($region_idtrue);
  1410.             if (!$alertRegion) {
  1411.                 return ["success" => false"message" => $translator->trans("region_not_found_for_" $region_id)];
  1412.             }
  1413.         }
  1414.         // $alertStatus = \Pimcore\Model\DataObject\AlertStatus::getById($alert_status_id, true);
  1415.         // if (!$alertStatus) {
  1416.         //     return ["success" => false, "message" => $translator->trans("alert_status_not_found_for_".$alert_status_id)];
  1417.         // }
  1418.         $alertTypeIDS = [];
  1419.         foreach ($alert_type_ids as $alert_type_id) {
  1420.             $alertType \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert_type_idtrue);
  1421.             if (!$alertType) {
  1422.                 return ["success" => false"message" => $translator->trans("alert_type_not_found_for_" $alert_type_id)];
  1423.             }
  1424.             $alertTypeIDS[] = $alertType->getId();
  1425.         }
  1426.         $governateIDS = [];
  1427.         $governorate null;
  1428.         foreach ($governorate_ids as $govId) {
  1429.             $governorate \Pimcore\Model\DataObject\Governorate::getByGovernoteId($govIdtrue);
  1430.             if (!$governorate) {
  1431.                 return ["success" => false"message" => $translator->trans("governorate_not_found_for_" $govId)];
  1432.             }
  1433.             $governateIDS[] = $governorate->getId();
  1434.         }
  1435.         $phenomenaIDS = [];
  1436.         foreach ($phenomena_ids as $phenomena_id) {
  1437.             $phenomena \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($phenomena_idtrue);
  1438.             if (!$phenomena) {
  1439.                 return ["success" => false"message" => $translator->trans("alert_status_not_found_for_" $phenomena_id)];
  1440.             }
  1441.             $phenomenaIDS[] = $phenomena->getId();
  1442.         }
  1443.         $govID implode(','$governateIDS);
  1444.         $alertID implode(','$alertTypeIDS);
  1445.         $phenomenaID implode(','$phenomenaIDS);
  1446.         $existingSubscription = new DataObject\MannedAlertSubscription\Listing();
  1447.         if ($alertRegion) {
  1448.             $existingSubscription->addConditionParam("region__id = ?", [$alertRegion->getId()]);
  1449.         }
  1450.         $existingSubscription->addConditionParam("governorate = ? ", [',' $govID ',']);
  1451.         $existingSubscription->addConditionParam("alertType = ? ", [',' $alertID ',']);
  1452.         $existingSubscription->addConditionParam("alertStatus = ? ", [',' $phenomenaID ',']);
  1453.         if ($is_public) {
  1454.             $existingSubscription->addConditionParam("LOWER(email) = ?", [$email]);
  1455.         } else {
  1456.             $existingSubscription->addConditionParam("creator__id = ?", [$customer->getId()]);
  1457.         }
  1458.         $existingSubscription->setOrderKey("oo_id");
  1459.         $existingSubscription->setOrder("desc");
  1460.         $existingSubscription->load();
  1461.         if (count($existingSubscription) > 0) {
  1462.             return ["success" => false"message" => $translator->trans("manned_alert_subscription_already_exists")];
  1463.         }
  1464.         // Create the subscription if it doesn't exist
  1465.         if ($governorate !== null) {
  1466.             $key \Pimcore\Model\Element\Service::getValidKey($governorate->getId(), 'object');
  1467.         } else {
  1468.             $key \Pimcore\Model\Element\Service::getValidKey($email'object');
  1469.         }
  1470.         $mannedSubscription = new \Pimcore\Model\DataObject\MannedAlertSubscription();
  1471.         $mannedSubscription->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Subscription/' $customer->getEmail()));
  1472.         $mannedSubscription->setKey($key time() . rand(0100));
  1473.         $mannedSubscription->setRegion($alertRegion);
  1474.         $governorateOBJ = [];
  1475.         foreach ($governorate_ids as $govId) {
  1476.             $governorateOBJ[] = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($govIdtrue);
  1477.         }
  1478.         $alert_typeOBJ = [];
  1479.         foreach ($alert_type_ids as $alert_type_id) {
  1480.             $alert_typeOBJ[] = \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert_type_idtrue);
  1481.         }
  1482.         $phenomenaOBJ = [];
  1483.         foreach ($phenomena_ids as $phenomena_id) {
  1484.             $phenomenaOBJ[] = \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($phenomena_idtrue);
  1485.         }
  1486.         $mannedSubscription->setGovernorate($governorateOBJ);
  1487.         $mannedSubscription->setAlertType($alert_typeOBJ);
  1488.         $mannedSubscription->setAlertStatus($phenomenaOBJ);
  1489.         $mannedSubscription->setCreator($customer);
  1490.         $mannedSubscription->setIsSubscribed($notifyEmail);
  1491.         $mannedSubscription->setNotifyEmail($notifyEmail);
  1492.         $mannedSubscription->setNotifySMS($notifySMS);
  1493.         $mannedSubscription->setIsPublic($is_public);
  1494.         $mannedSubscription->setEmail($email);
  1495.         $mannedSubscription->setPublished(true);
  1496.         $mannedSubscription->save();
  1497.         return ["success" => true"message" => $translator->trans("manned_alert_subscription_created")];
  1498.     }
  1499.     public function mannedAlertSubscriber($params$user$translator)
  1500.     {
  1501.         $subscription_id = isset($params['subscription_id']) ? (int)$params['subscription_id'] : 0;
  1502.         $isOwner = isset($params['isOwner']) ? (bool)$params['isOwner'] : false;
  1503.         // Permission check: only client admin can assign
  1504.         if (!empty($user->getRole()) && $user->getRole()->getName() !== USER_ROLES['CLIENT_ADMIN']) {
  1505.             return ["success" => false"message" => $translator->trans("you_are_not_allowed_to_assign_subscription")];
  1506.         }
  1507.         // Load and validate subscription once
  1508.         $subscription \Pimcore\Model\DataObject\MannedAlertSubscription::getById($subscription_idtrue);
  1509.         if (!$subscription instanceof \Pimcore\Model\DataObject\MannedAlertSubscription) {
  1510.             return ["success" => false"message" => $translator->trans("subscription_not_found_for_subscription_id_" $subscription_id)];
  1511.         }
  1512.         // Normalize user ids: user_id can be scalar or array
  1513.         $userIds = [];
  1514.         if (isset($params['user_id'])) {
  1515.             if (is_array($params['user_id'])) {
  1516.                 $userIds array_values(array_unique(array_map('intval'array_filter($params['user_id']))));
  1517.             } else {
  1518.                 $userIds = [ (int)$params['user_id'] ];
  1519.             }
  1520.         }
  1521.         $added 0;
  1522.         $keyBase \Pimcore\Model\Element\Service::getValidKey($subscription->getId(), 'object');
  1523.         foreach ($userIds as $user_id) {
  1524.             if (!$user_id) {
  1525.                 continue;
  1526.             }
  1527.             $customer \Pimcore\Model\DataObject\Customer::getById($user_idtrue);
  1528.             if (!$customer instanceof Customer) {
  1529.                 continue; // skip invalid user ids
  1530.             }
  1531.             // Check for existing assignment
  1532.             $existingSubscriber = new DataObject\MannedAlertSubscriber\Listing();
  1533.             $existingSubscriber->addConditionParam("userId__id = ?", [$customer->getId()]);
  1534.             $existingSubscriber->addConditionParam("subscriptionId__id = ?", [$subscription->getId()]);
  1535.             $existingSubscriber->setOrderKey("o_id");
  1536.             $existingSubscriber->setOrder("desc");
  1537.             $existingSubscriber->load();
  1538.             if (count($existingSubscriber) > 0) {
  1539.                 continue; // skip duplicates
  1540.             }
  1541.             // Create subscription assignment
  1542.             $mannedSubscriber = new \Pimcore\Model\DataObject\MannedAlertSubscriber();
  1543.             $mannedSubscriber->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath('/MannedAlert/Subscriber/' $customer->getEmail()));
  1544.             $mannedSubscriber->setKey($keyBase time() . rand(0100));
  1545.             $mannedSubscriber->setUserId($customer);
  1546.             $mannedSubscriber->setSubscriptionId($subscription);
  1547.             $mannedSubscriber->setIsOwner($isOwner);
  1548.             $mannedSubscriber->setPublished(true);
  1549.             $mannedSubscriber->save();
  1550.             // Also add to subscription subscribers relation (avoid duplicates)
  1551.             $currentSubscribers $subscription->getSubscribers();
  1552.             $updatedSubscribers = [];
  1553.             if ($currentSubscribers instanceof \Traversable || is_array($currentSubscribers)) {
  1554.                 foreach ($currentSubscribers as $existing) {
  1555.                     $updatedSubscribers[] = $existing;
  1556.                 }
  1557.             }
  1558.             $alreadyRelated false;
  1559.             foreach ($updatedSubscribers as $existing) {
  1560.                 if (method_exists($existing'getId') && $existing->getId() === $customer->getId()) {
  1561.                     $alreadyRelated true;
  1562.                     break;
  1563.                 }
  1564.             }
  1565.             if (!$alreadyRelated) {
  1566.                 $updatedSubscribers[] = $customer;
  1567.                 $subscription->setSubscribers($updatedSubscribers);
  1568.                 $subscription->save();
  1569.             }
  1570.             $added++;
  1571.         }
  1572.         if (count($userIds) > 1) {
  1573.             // Collective response for multiple users
  1574.             return ["success" => $added 0"message" => $translator->trans("subscription_assigned_successfully") . ": " $added];
  1575.         }
  1576.         // Single user response
  1577.         if ($added === 1) {
  1578.             return ["success" => true"message" => $translator->trans("subscription_assigned_successfully")];
  1579.         }
  1580.         return ["success" => false"message" => $translator->trans("this_subscription_already_assigned_to_this_user")];
  1581.     }
  1582.     public function listMannedAlertSubscription($params$user$paginator)
  1583.     {
  1584.         $pageSize $params['page_size'] ?? LIMIT_PER_PAGE;
  1585.         $page $params['page'] ?? 1;
  1586.         $mannedAlertSubscription = new DataObject\MannedAlertSubscription\Listing();
  1587.         if (isset($params['isAssigned'])) {
  1588.             $isAssignedParam $params['isAssigned'];
  1589.             $truthyValues = [true1'1''true''TRUE''True'];
  1590.             $falsyValues = [false0'0''false''FALSE''False'];
  1591.             if (in_array($isAssignedParam$truthyValuestrue)) {
  1592.                 // Only subscriptions assigned to the user (not created by them)
  1593.                 $mannedAlertSubscription->addConditionParam("FIND_IN_SET(?, subscribers) > 0 AND creator__id != ?", [$user->getId(), $user->getId()]);
  1594.             } elseif (in_array($isAssignedParam$falsyValuestrue)) {
  1595.                 // Only subscriptions created by the user
  1596.                 $mannedAlertSubscription->addConditionParam("creator__id = ?", [$user->getId()]);
  1597.             } else {
  1598.                 // Fallback to default behavior if param is malformed
  1599.                 $mannedAlertSubscription->addConditionParam("creator__id = ? OR FIND_IN_SET(?, subscribers) > 0", [$user->getId(), $user->getId()]);
  1600.             }
  1601.         } else {
  1602.             // Default: include subscriptions created by the user OR assigned to the user
  1603.             $mannedAlertSubscription->addConditionParam("creator__id = ? OR FIND_IN_SET(?, subscribers) > 0", [$user->getId(), $user->getId()]);
  1604.         }
  1605.         if (isset($params['region_id']) && !empty($params['region_id'])) {
  1606.             $region_ids $params['region_id'];
  1607.             $regionIDS = [];
  1608.             foreach ($region_ids as $regionId) {
  1609.                 $region \Pimcore\Model\DataObject\Region::getByRegionId($regionIdtrue);
  1610.                 $regionIDS[] = $region->getId();
  1611.             }
  1612.             // Use placeholders for each region ID
  1613.             $placeholders implode(','array_fill(0count($regionIDS), '?'));
  1614.             $mannedAlertSubscription->addConditionParam('region__id IN (' $placeholders ')'$regionIDS);
  1615.         }
  1616.         if (isset($params['alert_id']) && !empty($params['alert_id'])) {
  1617.             $alertIds $params['alert_id'];
  1618.             $alertTypeIDS = [];
  1619.             foreach ($alertIds as $alert_type_id) {
  1620.                 $alertType \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert_type_idtrue);
  1621.                 $alertTypeIDS[] = $alertType->getId();
  1622.             }
  1623.             $alertTypeID implode(','$alertTypeIDS);
  1624.             // $mannedAlertSubscription->addConditionParam("alertType = ? ", [','.$alertTypeID.',']);
  1625.             $mannedAlertSubscription->addConditionParam("alertType REGEXP CONCAT('(^|,)(', REPLACE('$alertTypeID',',', '|'), ')(,|$)')");
  1626.         }
  1627.         if (isset($params['phenomena_id']) && !empty($params['phenomena_id'])) {
  1628.             $alertStatusIds $params['phenomena_id'];
  1629.             $alertStatusIDS = [];
  1630.             foreach ($alertStatusIDS as $alertStatusId) {
  1631.                 $alertStatus \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($alertStatusIdtrue);
  1632.                 $alertStatusIDS[] = $$alertStatus->getId();
  1633.             }
  1634.             $alertStatusID implode(','$alertStatusIDS);
  1635.             // $mannedAlertSubscription->addConditionParam("phenomena = ? ", [','.$phenomenaID.',']);
  1636.             $mannedAlertSubscription->addConditionParam("alertStatus REGEXP CONCAT('(^|,)(', REPLACE('$alertStatusID',',', '|'), ')(,|$)')");
  1637.         }
  1638.         $mannedAlertSubscription->setOrderKey("oo_id");
  1639.         $mannedAlertSubscription->setOrder("desc");
  1640.         $paginator $paginator->paginate(
  1641.             $mannedAlertSubscription,
  1642.             $page,
  1643.             $pageSize
  1644.         );
  1645.         $response = [];
  1646.         foreach ($paginator as $subscription) {
  1647.             if ($subscription) {
  1648.                 $governorates = [];
  1649.                 foreach ($subscription->getGovernorate() as $governorate) {
  1650.                     $governorates[] = [
  1651.                         "id" => $governorate->getGovernoteId(),
  1652.                         "en" => $governorate->getName('en'),
  1653.                         "ar" => $governorate->getName('ar')
  1654.                     ];
  1655.                 }
  1656.                 $alert_types = [];
  1657.                 foreach ($subscription->getAlertType() as $alert_type) {
  1658.                     $alert_types[] = [
  1659.                         "id" => $alert_type->getAlertTypeId(),
  1660.                         "color" => $alert_type->getColor(),
  1661.                         "en" => $alert_type->getName('en'),
  1662.                         "ar" => $alert_type->getName('ar')
  1663.                     ];
  1664.                 }
  1665.                 $phenomenas = [];
  1666.                 if ($subscription->getAlertStatus()) {
  1667.                     foreach ($subscription->getAlertStatus() as $subscriptionAlertStatus) {
  1668.                         $phenomenas[] = [
  1669.                             "id" => $subscriptionAlertStatus->getAlertStatusId(),
  1670.                             "en" => $subscriptionAlertStatus->getName('en'),
  1671.                             "ar" => $subscriptionAlertStatus->getName('ar')
  1672.                         ];
  1673.                     }
  1674.                 }
  1675.                 $response[] = [
  1676.                     "id" => $subscription->getId(),
  1677.                     "region" => [
  1678.                         [
  1679.                             "id" => $subscription->getRegion()->getRegionId(),
  1680.                             "en" => $subscription->getRegion()->getName('en'),
  1681.                             "ar" => $subscription->getRegion()->getName('ar')
  1682.                         ]
  1683.                     ],
  1684.                     "alertType" => $alert_types,
  1685.                     "governorate" => $governorates,
  1686.                     "phenomena" => $phenomenas,
  1687.                     "notifyEmail" => $subscription->getNotifyEmail() == null false $subscription->getNotifyEmail(),
  1688.                     "notifySMS" => $subscription->getNotifySMS() == null false $subscription->getNotifySMS(),
  1689.                     "creator" => $subscription->getCreator()?->getEmail(),
  1690.                     "isAssigned" => $subscription->getCreator()?->getEmail() !== $user->getEmail() ? true false
  1691.                 ];
  1692.             }
  1693.         }
  1694.         return [
  1695.             "success" => true,
  1696.             "data" => $response,
  1697.             'paginationVariables' => $paginator->getPaginationData()
  1698.         ];
  1699.     }
  1700.     public function deleteMannedAlertSubscription($request$params$user$translator)
  1701.     {
  1702.         $subscription_id = isset($params['subscription_id']) ? $params['subscription_id'] : null;
  1703.         $alertSubscription \Pimcore\Model\DataObject\MannedAlertSubscription::getById($subscription_idtrue);
  1704.         if (!$alertSubscription) {
  1705.             return ["success" => false"message" => $translator->trans("alert_subscription_not_found")];
  1706.         }
  1707.         if ($alertSubscription->getCreator() == $user) {
  1708.             if ($alertSubscription instanceof \Pimcore\Model\DataObject\MannedAlertSubscription) {
  1709.                 $alertSubscription->delete();
  1710.                 return ["success" => true"message" => $translator->trans("subscription_deleted")];
  1711.             }
  1712.         } else {
  1713.             $subscribedUser = [];
  1714.             $message "user_not_found_in_this_subscription";
  1715.             foreach ($alertSubscription->getSubscribers() as $assignUser) {
  1716.                 if ($assignUser == $user) {
  1717.                     $message "subscription_deleted";
  1718.                 } else {
  1719.                     $subscribedUser[] = $assignUser;
  1720.                 }
  1721.                 $alertSubscription->setSubscribers($subscribedUser);
  1722.                 $alertSubscription->save();
  1723.             }
  1724.             return ["success" => true"message" => $translator->trans($message)];
  1725.         }
  1726.     }
  1727.     public function mannedAlertSubscribe($request$params$user$translator)
  1728.     {
  1729.         $subscription_id = isset($params['subscription_id']) ? $params['subscription_id'] : null;
  1730.         $notifyEmail = isset($params['notifyEmail']) ? $params['notifyEmail'] : false;
  1731.         $notifySMS = isset($params['notifySMS']) ? $params['notifySMS'] : false;
  1732.         $subscription = new DataObject\MannedAlertSubscription\Listing();
  1733.         $subscription->setCondition("oo_id = ?", [$subscription_id]);
  1734.         $subscription->filterByCreator($user);
  1735.         $subscriptionData $subscription->current();
  1736.         if ($subscriptionData instanceof \Pimcore\Model\DataObject\MannedAlertSubscription) {
  1737.             try {
  1738.                 $subscriptionData->setIsSubscribed($notifyEmail);
  1739.                 $subscriptionData->setNotifyEmail($notifyEmail);
  1740.                 $subscriptionData->setNotifySMS($notifySMS);
  1741.                 $subscriptionData->save();
  1742.                 return ["success" => true"message" => $translator->trans('Subscription_unsubscribed_successfully')];
  1743.             } catch (\Exception $e) {
  1744.                 throw new \Exception($e->getMessage());
  1745.             }
  1746.         }
  1747.         return ["success" => false"message" => $translator->trans("subscription_not_found_for_id_" $subscription_id)];
  1748.     }
  1749.     public function assignUsersWithCustomNotification($request$userIdsArray$notificationId$translator)
  1750.     {
  1751.         $users = [];
  1752.         $customNotification CustomNotification::getById($notificationId);
  1753.         if (!$customNotification) {
  1754.             return ["success" => false"message" => $translator->trans("custom_notification_not_found_for_id_" $notificationId)];
  1755.         }
  1756.         $objectArray = ($customNotification) ? $customNotification->getUser() : [];
  1757.         if ($objectArray) {
  1758.             foreach ($objectArray as $key => $objUser) {
  1759.                 $users[] = $objUser->getObject();
  1760.             }
  1761.         }
  1762.         if (count($userIdsArray) > 0) {
  1763.             // validate if users are available to given ids
  1764.             foreach ($userIdsArray as $userId) {
  1765.                 $user Customer::getById($userId);
  1766.                 if (!$user) {
  1767.                     return ["success" => false"message" => $translator->trans("user_not_found_for_id_" $userId)];
  1768.                 } else {
  1769.                     if (!in_array($user$users)) {
  1770.                         $objectMetadata = new DataObject\Data\ObjectMetadata('user', ['alert_on_email''alert_on_sms'],  $user);
  1771.                         $objectMetadata->setAlert_on_email(true);
  1772.                         $objectMetadata->setAlert_on_sms(true);
  1773.                         array_push($objectArray$objectMetadata);
  1774.                     }
  1775.                 }
  1776.             }
  1777.             $customNotification->setUser($objectArray);
  1778.             $customNotification->save();
  1779.             return ["success" => true"message" => $translator->trans("custom_notification_assigned_successfully")];
  1780.         } else {
  1781.             return ["success" => false"message" => $translator->trans("user_id_array_is_empty")];
  1782.         }
  1783.     }
  1784.     public function unSubscribeNotification($customer$translator)
  1785.     {
  1786.         $ownerNotifications = new AdvanceCustomNotification\Listing();
  1787.         // $$ownerNotification=->filterByUser($customer);
  1788.         $ownerNotifications->setCondition("owner__id =?", [$customer->getId()]);
  1789.         $ownerNotifications->load();
  1790.         if ($ownerNotifications) {
  1791.             foreach ($ownerNotifications as $ownerNotification) {
  1792.                 // Assuming 'getAlerts' is the name of your multi-selection field
  1793.                 $sendNotificationAlertTypes $ownerNotification->getAlerts();
  1794.                 // Check if 'email' is currently selected
  1795.                 if (is_array($sendNotificationAlertTypes)) {
  1796.                     if (in_array('email'$sendNotificationAlertTypes)) {
  1797.                         // Remove 'email' from the selection
  1798.                         $updatedMethods array_filter($sendNotificationAlertTypes, function ($method) {
  1799.                             return $method !== 'email';
  1800.                         });
  1801.                         // Set the updated selection without 'email'
  1802.                         $ownerNotification->setAlerts(array_values($updatedMethods)); // Ensure array is reindexed if necessary
  1803.                     }
  1804.                 }
  1805.                 $ownerNotification->save();
  1806.             }
  1807.         }
  1808.         $customer->setUnSubscribeCustomNotificationToken("");
  1809.         $customer->save();
  1810.         /* DO NOT REMOVE BELOW CODE */
  1811.         // $customNotifications = new AdvanceCustomNotification\Listing();
  1812.         // $userGroup = $customer->getUserGroup(); // getUserGroup method based on your relation name
  1813.         // $userGroupId = null;
  1814.         // $likePatternUserGroup=null;
  1815.         // if ($userGroup) {
  1816.         //     $userGroupId = $userGroup->getId();
  1817.         //     $likePatternUserGroup = '%,' . $userGroupId . ',%';
  1818.         // }
  1819.         // $likePatternUser = '%,' . $customer->getId() . ',%';
  1820.         // $condition = "(user LIKE ? OR usergroup LIKE ?)";
  1821.         // $customNotifications->setCondition($condition, [$likePatternUser, $likePatternUserGroup]);
  1822.         // if ($customNotifications) {
  1823.         //     foreach ($customNotifications as $customNotification) {
  1824.         //         $objectArray = $customNotification->getUnSubscriber();
  1825.         //         // Flag to check if the customer is already in the unsubscriber list
  1826.         //         $isAlreadyUnsubscribed = false;
  1827.         //         // Step 2: Check if the customer is already in that list
  1828.         //         foreach ($objectArray as $objectMetadata) {
  1829.         //             if ($objectMetadata->getObject() instanceof \Pimcore\Model\DataObject\Customer && $objectMetadata->getObject()->getId() == $customer->getId()) {
  1830.         //                 // The customer is already an unsubscriber
  1831.         //                 $isAlreadyUnsubscribed = true;
  1832.         //                 break; // No need to check further
  1833.         //             }
  1834.         //         }
  1835.         //         // Step 3: If not already unsubscribed, add the customer to the list
  1836.         //         if (!$isAlreadyUnsubscribed) {
  1837.         //             // Create a new ObjectMetadata instance for the new unsubscriber
  1838.         //             // Assuming you don't need to add specific metadata here, otherwise include those fields in the array
  1839.         //             $newUnsubscriber = new ObjectMetadata('unSubscriber', ['date'], $customer);
  1840.         //             // Set the current date for the 'date' metadata field
  1841.         //             $currentDate = new \DateTime();
  1842.         //             $newUnsubscriber->setDate($currentDate->format('Y-m-d H:i:s'));
  1843.         //             // $newUnsubscriber->setMetadata('date', 'text', $currentDate->format('Y-m-d H:i:s'));
  1844.         //             // Add the new unsubscriber to the objectArray
  1845.         //             $objectArray[] = $newUnsubscriber;
  1846.         //             // Set the updated array back to the CustomNotification object
  1847.         //             $customNotification->setUnSubscriber($objectArray);
  1848.         //             // Save the CustomNotification object
  1849.         //             $customNotification->save();
  1850.         //         }
  1851.         //     }
  1852.         //     $customer->setUnSubscribeCustomNotificationToken("");
  1853.         //     $customer->save();
  1854.         //     return ["success" => true, "message" => $translator->trans("You have successfully unsubscribed to all notifications")];
  1855.         // }
  1856.         return ["success" => true"message" => $translator->trans("You have successfully unsubscribed to all notifications")];
  1857.         // else {
  1858.         //     return ["success" => false, "message" => $translator->trans("Notifications Not Found")];
  1859.         // }
  1860.     }
  1861.     public function assignAlertSubscription($customer$params$translator)
  1862.     {
  1863.         $alert_subscription_id = isset($params['AlertSubscriptionId']) ? $params['AlertSubscriptionId'] : null;
  1864.         $user_ids = isset($params['UserId']) ? $params['UserId'] : 0;
  1865.         $alertSubscription \Pimcore\Model\DataObject\MannedAlertSubscription::getById($alert_subscription_idtrue);
  1866.         if (!$alertSubscription) {
  1867.             return ["success" => false"message" => $translator->trans("alert_subscription_not_found")];
  1868.         }
  1869.         if ($alertSubscription->getCreator() !== $customer) {
  1870.             return ["success" => false"message" => $translator->trans("alert_does_not_create_by_login_user")];
  1871.         }
  1872.         $message = [];
  1873.         foreach ($user_ids as $user_id) {
  1874.             $assignedUser DataObject\Customer::getById($user_id);
  1875.             if ($assignedUser) {
  1876.                 if (!($customer->getOrganization() == $assignedUser->getOrganization())) {
  1877.                     // return ["success" => false, "message" => $translator->trans("user_does_not_belongs_to_same_organization")];
  1878.                     $message[] = $translator->trans("user_does_not_belongs_to_same_organization");
  1879.                 }
  1880.                 $subscribedUser = [];
  1881.                 foreach ($alertSubscription->getSubscribers() as $user) {
  1882.                     if ($user == $assignedUser) {
  1883.                         $message[] = $translator->trans("user_already_assigned");
  1884.                     } else {
  1885.                         $subscribedUser[] = $user;
  1886.                     }
  1887.                 }
  1888.                 $subscribedUser[] = $assignedUser;
  1889.                 $alertSubscription->setSubscribers($subscribedUser);
  1890.                 $alertSubscription->save();
  1891.             }
  1892.         }
  1893.         return ["success" => true"message" => $translator->trans("manned_alert_subscription_assigned")];
  1894.     }
  1895.     public function assignUserGroupWithCustomNotification($request$userGroupIdsArray$notificationId$translator)
  1896.     {
  1897.         $customNotification CustomNotification::getById($notificationId);
  1898.         if (!$customNotification) {
  1899.             return ["success" => false"message" => $translator->trans("custom_notification_not_found_for_id_" $notificationId)];
  1900.         }
  1901.         if (count($userGroupIdsArray) > 0) {
  1902.             $selectedUserGroups = [];
  1903.             $newObjectArray = [];
  1904.             $processedUserIds = [];
  1905.             // Get existing users (retain all and avoid duplicates)
  1906.             $existingUsers = [];
  1907.             if ($customNotification) {
  1908.                 try {
  1909.                     $existingUsers $customNotification->getUser();
  1910.                 } catch (\Throwable $e) {
  1911.                     // In case of broken relation IDs, proceed with empty existing users
  1912.                     $existingUsers = [];
  1913.                 }
  1914.             }
  1915.             if ($existingUsers) {
  1916.                 foreach ($existingUsers as $existingUserMetadata) {
  1917.                     if (!$existingUserMetadata) {
  1918.                         continue;
  1919.                     }
  1920.                     // If metadata exists, keep users that are not from user groups
  1921.                     if ($existingUserMetadata instanceof \Pimcore\Model\DataObject\Data\ObjectMetadata) {
  1922.                         // Only keep if the underlying object still exists
  1923.                         $related $existingUserMetadata->getObject();
  1924.                         if ($related) {
  1925.                             $newObjectArray[] = $existingUserMetadata;
  1926.                             $processedUserIds[] = $related->getId();
  1927.                         }
  1928.                         continue;
  1929.                     }
  1930.                     // If item is a plain Customer (no metadata), wrap into metadata for the 'user' field
  1931.                     if ($existingUserMetadata instanceof Customer) {
  1932.                         $wrapped = new DataObject\Data\ObjectMetadata('user', ['alert_on_email''alert_on_sms''is_group_user','group_id'], $existingUserMetadata);
  1933.                         $wrapped->setAlert_on_email(true);
  1934.                         $wrapped->setAlert_on_sms(true);
  1935.                         $wrapped->setIs_group_user(false);
  1936.                         $wrapped->setGroup_id(null);
  1937.                         $newObjectArray[] = $wrapped;
  1938.                         $processedUserIds[] = $existingUserMetadata->getId();
  1939.                     }
  1940.                 }
  1941.             }
  1942.             // Process new user groups
  1943.             if (!empty($userGroupIdsArray)) {
  1944.                 foreach ($userGroupIdsArray as $userGroup) {
  1945.                     $UserGroupObject UserGroup::getById($userGrouptrue);
  1946.                     if ($UserGroupObject) {
  1947.                         $selectedUserGroups[] = $UserGroupObject;
  1948.                         
  1949.                         $userGroupUsers Customer::getByUserGroup($UserGroupObject);
  1950.                         foreach ($userGroupUsers as $userGroupUser) {
  1951.                             // Check if user is not already processed to avoid duplicates
  1952.                             if (!in_array($userGroupUser->getId(), $processedUserIds)) {
  1953.                                 $objectMetadata = new DataObject\Data\ObjectMetadata('user', ['alert_on_email''alert_on_sms''is_group_user','group_id'], $userGroupUser);
  1954.                                 $objectMetadata->setAlert_on_email(true);
  1955.                                 $objectMetadata->setAlert_on_sms(true);
  1956.                                 $objectMetadata->setIs_group_user(true);
  1957.                                 $objectMetadata->setGroup_id($UserGroupObject->getId());
  1958.                                 $newObjectArray[] = $objectMetadata;
  1959.                                 $processedUserIds[] = $userGroupUser->getId();
  1960.                             }
  1961.                         }
  1962.                     }
  1963.                 }
  1964.             }
  1965.             // Update the notification with new user groups and users
  1966.             $customNotification->setUserGroup($selectedUserGroups);
  1967.             $customNotification->setUser($newObjectArray);
  1968.             $customNotification->save();
  1969.             return ["success" => true"message" => $translator->trans("custom_notification_assigned_successfully")];
  1970.         } else {
  1971.             return ["success" => false"message" => $translator->trans("user_group_array_is_empty")];
  1972.         }
  1973.     }
  1974.     public function assignUserGroupWithAlertSubscription($request$userGroupIdsArray$notificationId$translator)
  1975.     {
  1976.         $alertSubscription MannedAlertSubscription::getById($notificationIdtrue);
  1977.         if (!$alertSubscription) {
  1978.             return ["success" => false"message" => $translator->trans("custom_notification_not_found_for_id_" $notificationId)];
  1979.         }
  1980.         if (count($userGroupIdsArray) > 0) {
  1981.             $selectedUserGroups = [];
  1982.             $newObjectArray = [];
  1983.             $processedUserIds = [];
  1984.         // Get existing subscribers (retain all and avoid duplicates). This relation does NOT support metadata.
  1985.         $existingUsers = [];
  1986.             if ($alertSubscription) {
  1987.                 try {
  1988.                     $existingUsers $alertSubscription->getSubscribers();
  1989.                 } catch (\Throwable $e) {
  1990.                     // In case of broken relation IDs, proceed with empty existing users
  1991.                     $existingUsers = [];
  1992.                 }
  1993.             }
  1994.             if ($existingUsers) {
  1995.                 foreach ($existingUsers as $existingUserMetadata) {
  1996.                     if (!$existingUserMetadata) {
  1997.                         continue;
  1998.                     }
  1999.                 // Subscribers is many-to-many without metadata: keep customers directly
  2000.                 if ($existingUserMetadata instanceof Customer) {
  2001.                     $newObjectArray[] = $existingUserMetadata;
  2002.                     $processedUserIds[] = $existingUserMetadata->getId();
  2003.                 }
  2004.                 }
  2005.             }
  2006.             // Process new user groups
  2007.             if (!empty($userGroupIdsArray)) {
  2008.                 foreach ($userGroupIdsArray as $userGroup) {
  2009.                     $UserGroupObject UserGroup::getById($userGrouptrue);
  2010.                     if ($UserGroupObject) {
  2011.                         $selectedUserGroups[] = $UserGroupObject;
  2012.                         
  2013.                         $userGroupUsers Customer::getByUserGroup($UserGroupObject);
  2014.                         foreach ($userGroupUsers as $userGroupUser) {
  2015.                             // Check if user is not already processed to avoid duplicates
  2016.                             if (!in_array($userGroupUser->getId(), $processedUserIds)) {
  2017.                                 $newObjectArray[] = $userGroupUser;
  2018.                                 $processedUserIds[] = $userGroupUser->getId();
  2019.                             }
  2020.                         }
  2021.                     }
  2022.                 }
  2023.             }
  2024.             // Update the notification with new user groups and users
  2025.             $alertSubscription->setUserGroup($selectedUserGroups);
  2026.             $alertSubscription->setSubscribers($newObjectArray);
  2027.             $alertSubscription->save();
  2028.             return ["success" => true"message" => $translator->trans("custom_notification_assigned_successfully")];
  2029.         } else {
  2030.             return ["success" => false"message" => $translator->trans("user_group_array_is_empty")];
  2031.         }
  2032.     }
  2033.     
  2034. }