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