src/Model/EwsNotificationModel.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\Model;
  3. use DateTime;
  4. use Pimcore\Db;
  5. use DOMDocument;
  6. use SimpleXMLElement;
  7. use Pimcore\Model\Asset;
  8. use Doctrine\DBAL\Connection;
  9. use Pimcore\Model\DataObject;
  10. use Symfony\Component\Uid\UuidV4;
  11. use Pimcore\Model\DataObject\Region;
  12. use Pimcore\Model\DataObject\AlertType;
  13. use Pimcore\Model\DataObject\EwsNotification;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Pimcore\Model\DataObject\FetchSentEwsEmail;
  16. use App\C2IntegrationBundle\Service\C2Service;
  17. use Pimcore\Model\Asset\MetaData\ClassDefinition\Data\DataObject as DataDataObject;
  18. use Pimcore\Model\DataObject\EwsAndReportUserGroup;
  19. use App\Model\UserModel;
  20. use Symfony\Component\Process\Process;
  21. use Symfony\Component\Process\Exception\ProcessFailedException;
  22. class EwsNotificationModel
  23. {
  24.     public $c2Service;
  25.     private $userModel;
  26.     function __construct()
  27.     {
  28.         $this->c2Service = new C2Service();
  29.         $this->userModel = new UserModel();
  30.     }
  31.     public function createNotification($request$params$userInterface$translator): array
  32.     {
  33.         $result = [];
  34.         // try {
  35.         $regionId $params['regionId'] ?? null;
  36.         $governorateIds $params['governateIds'] ?? null;
  37.         $municipalities $params['municipalityIds'] ?? null;
  38.         $ewsOtherLocationIds $params['ewsOtherLocationIds'] ?? null;
  39.         $alertActionId $params['alertActionId'] ?? null;
  40.         $alertTypeId $params['alertTypeId'] ?? null;
  41.         $weatherPhenomenonId $params['weatherPhenomenonId'] ?? null;
  42.         $coordinates json_encode($params['coordinates'] ?? []);
  43.         $message $params['message'] ?? [];
  44.         $alertHazardId $params['alertHazardId'] ?? null;
  45.         $otherLocationId $params['otherLocationId'] ?? null;
  46.         $enableTwitterNotification $params['enableTwitterNotification'] ?? false;
  47.         $enableSMSNotification $params['enableSMSNotification'] ?? false;
  48.         $enableEmailNotification $params['enableEmailNotification'] ?? false;
  49.         $x_post $params['x_post'] ?? "";
  50.         $previewText = isset($params['previewText']) ? $params['previewText'] : false;
  51.         $ewsNotification = new DataObject\EwsNotification();
  52.         $ewsNotification->setParent(DataObject\Service::createFolderByPath('/Notification/EWSNotification'));
  53.         $ewsNotification->setKey(md5($coordinates $regionId $governorateIds) . '-' time());
  54.         $ewsNotification->setGuid(\App\Lib\Utility::getUUID()->toRfc4122());
  55.         if (isset($params['startDate'])) {
  56.             $startTime $params['startTime'] ?? '00:00:00';
  57.             $fromDate $params['startDate'] . ' ' $startTime;
  58.             $ewsNotification->setStartDate(\Carbon\Carbon::createFromFormat('Y-m-d H:i:s'$fromDate));
  59.         }
  60.         if (isset($params['endDate'])) {
  61.             $endTime $params['endTime'] ?? '00:00:00';
  62.             $endDate $params['endDate'] . ' ' $endTime;
  63.             $ewsNotification->setEndDate(\Carbon\Carbon::createFromFormat('Y-m-d H:i:s'$endDate));
  64.         }
  65.         if (isset($message['en'])) {
  66.             $ewsNotification->setMessage($message['en'], 'en');
  67.         }
  68.         if (isset($message['ar'])) {
  69.             $ewsNotification->setMessage($message['ar'], 'ar');
  70.         }
  71.         if (!empty($regionId)) {
  72.             $regionObj DataObject\Region::getByRegionId($regionId1);
  73.             if (!empty($regionObj)) {
  74.                 $ewsNotification->setRegion($regionObj);
  75.                 if ($governorateIds) {
  76.                     $governorateIdArr explode(","$governorateIds);
  77.                     if ($governorateIdArr) {
  78.                         $applyGovernates = [];
  79.                         foreach ($governorateIdArr as $id) {
  80.                             if(!empty($id)){
  81.                                 $applyGovernates[] = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($idtrue);
  82.                                 if (!empty(array_unique($applyGovernates))) {
  83.                                     $ewsNotification->setGovernorate(array_unique($applyGovernates));
  84.                                 }
  85.                             }
  86.                         }
  87.                     }
  88.                     if ($municipalities) {
  89.                         $municipalitiesIdArr explode(","$municipalities);
  90.                         if ($municipalitiesIdArr) {
  91.                             $applyMunicipalities = [];
  92.                             foreach ($municipalitiesIdArr as $id) {
  93.                                 $applyMunicipalities[] = \Pimcore\Model\DataObject\Municipality::getByMunicipalityid($idtrue);
  94.                                 if (!empty(array_unique($applyMunicipalities))) {
  95.                                     $ewsNotification->setMunicipality(array_unique($applyMunicipalities));
  96.                                 }
  97.                             }
  98.                         }
  99.                     }
  100.                 } else {
  101.                     $ewsNotification->setGovernorate($this->governorateByRegion($regionObj->getId()));
  102.                 }
  103.             }
  104.         }
  105.         if ($ewsOtherLocationIds) {
  106.             $ewsOtherLocationIdArr explode(","$ewsOtherLocationIds);
  107.             if ($ewsOtherLocationIdArr) {
  108.                 $applyOtherGovernates = [];
  109.                 foreach ($ewsOtherLocationIdArr as $id) {
  110.                     $applyOtherGovernates[] = \Pimcore\Model\DataObject\EwsOtherLocation::getByGovernoteId($idtrue);
  111.                     if (!empty(array_unique($applyOtherGovernates))) {
  112.                         $ewsNotification->setEwsOtherLocations(array_unique($applyOtherGovernates));
  113.                     }
  114.                 }
  115.             }
  116.         }
  117.         if (!empty($alertHazardId)) {
  118.             $alertHazardArr explode(","$alertHazardId);
  119.             if ($alertHazardArr) {
  120.                 $alertHazardArrRequest = [];
  121.                 foreach ($alertHazardArr as $alertHazardId) {
  122.                     $weatherPhenomenonAffect DataObject\AlertHazard::getByAlertHazardId($alertHazardId1);
  123.                     if ($weatherPhenomenonAffect) {
  124.                         $alertHazardArrRequest[] = $weatherPhenomenonAffect;
  125.                     }
  126.                 }
  127.                 $ewsNotification->setAlertHazard($alertHazardArrRequest);
  128.             }
  129.         }
  130.         if (!empty($alertTypeId)) {
  131.             $alertType DataObject\AlertType::getByAlertTypeId($alertTypeId1);
  132.             $ewsNotification->setAlertType($alertType);
  133.         }
  134.         if (!empty($alertActionId)) {
  135.             $alertActionArr explode(","$alertActionId);
  136.             if ($alertActionArr) {
  137.                 $alertActionArrRequest = [];
  138.                 foreach ($alertActionArr as $alertActionId) {
  139.                     $alertAction DataObject\AlertAction::getByAlertActionId($alertActionId1);
  140.                     if ($alertAction) {
  141.                         $alertActionArrRequest[] = $alertAction;
  142.                     }
  143.                 }
  144.                 $ewsNotification->setAlertAction($alertActionArrRequest);
  145.             }
  146.         }
  147.         if (!empty($otherLocationId)) {
  148.             $otherLocationArr explode(","$otherLocationId);
  149.             if ($otherLocationArr) {
  150.                 $otherLocationArrRequest = [];
  151.                 foreach ($otherLocationArr as $otherLocationId) {
  152.                     $otherLocation DataObject\OtherLocation::getByOtherLocationId($otherLocationId1);
  153.                     if ($otherLocation) {
  154.                         $otherLocationArrRequest[] = $otherLocation;
  155.                     }
  156.                 }
  157.                 $ewsNotification->setOtherLocations($otherLocationArrRequest);
  158.             }
  159.         }
  160.         if (!empty($weatherPhenomenonId)) {
  161.             $alertStatus DataObject\AlertStatus::getByAlertStatusId($weatherPhenomenonIdtrue);
  162.             $ewsNotification->setAlertStatus($alertStatus);
  163.         }
  164.         $ewsNotification->setCoordinates($coordinates);
  165.         $addressComponents $params['address_components'] ?? [];
  166.         $this->addAddressComponentsFieldCollection($addressComponents$ewsNotification);
  167.         if (!empty($params['file'])) {
  168.             $asset $this->createAsset($params['file'], time() . $params['filename']);
  169.             if ($asset) {
  170.                 $ewsNotification->setAttachment($asset);
  171.             }
  172.         }
  173.         if (!empty($params['x_img'])) {
  174.             $asset $this->createAsset($params['x_img'], time() . "EWSTwitterImages.png");
  175.             if ($asset) {
  176.                 $ewsNotification->setXAttachment($asset);
  177.             }
  178.         }
  179.         $ewsNotification->setXPost($x_post);
  180.         $ewsNotification->setEnableTwitterNotification($enableTwitterNotification);
  181.         $ewsNotification->setEnableSMSNotification($enableSMSNotification);
  182.         $ewsNotification->setEnableEmailNotification($enableEmailNotification);
  183.         $ewsNotification->setUser($userInterface);
  184.         $ewsNotification->setEditor($userInterface);
  185.         $ewsNotification->setPublished(false);
  186.         $ewsNotification->setPreviewText($previewText);
  187.         //$ewsNotification->save(["versionNote" => "Update"]);
  188.         //set ews search Id
  189.         $currentDate = new \DateTime();
  190.         $formattedDate $currentDate->format('dmY') . '-' $ewsNotification->getId();
  191.         $searchIdEn 'Early Warning System | ' $formattedDate ' | ' ucfirst($ewsNotification->getAlertType()?->getColor()) . ' Alert | ' $ewsNotification->getWeatherPhenomenon()?->getTitle("en");
  192.         $searchIdAr $translator->trans('Early Warning System', [], null"ar") . ' | ' $formattedDate ' | ' $translator->trans(ucfirst($ewsNotification->getAlertType()?->getColor()) . ' Alert', [], null"ar") . ' | ' $ewsNotification->getWeatherPhenomenon()?->getTitle("ar");
  193.         $ewsNotification->setEwsSearchId($searchIdEn"en");
  194.         $ewsNotification->setEwsSearchId($searchIdAr"ar");
  195.         //$ewsNotification->save(["versionNote" => "Update"]);
  196.         $ewsNotification->save();
  197.         return ['success' => true'message' => $translator->trans('ews_notification_added_successifully'), "notification_id" => $ewsNotification->getId()];
  198.         // } catch (\Exception $ex) {
  199.         //     $result = ['success' => false, 'message' => $ex->getMessage()];
  200.         // }
  201.         return $result;
  202.     }
  203.     public function updateNotification($request$params$userInterface$translator$userGroupIds$isPublished$emailService$templating$logger): array
  204.     {
  205.         $result = [];
  206.         // try {
  207.         $id $params['id'] ?? null;
  208.         if (!$id) {
  209.             throw new \Exception("EWS id is required");
  210.         }
  211.         $regionId $params['regionId'] ?? null;
  212.         $governorateIds $params['governateIds'] ?? null;
  213.         $municipalities $params['municipalityIds'] ?? null;
  214.         $ewsOtherLocationIds $params['ewsOtherLocationIds'] ?? null;
  215.         $alertActionId $params['alertActionId'] ?? null;
  216.         $alertTypeId $params['alertTypeId'] ?? null;
  217.         $weatherPhenomenonId $params['weatherPhenomenonId'] ?? null;
  218.         $coordinates json_encode($params['coordinates'] ?? []);
  219.         $message $params['message'] ?? [];
  220.         $alertHazardId $params['alertHazardId'] ?? null;
  221.         $enableTwitterNotification $params['enableTwitterNotification'] ?? false;
  222.         $enableSMSNotification $params['enableSMSNotification'] ?? false;
  223.         $enableEmailNotification $params['enableEmailNotification'] ?? false;
  224.         $previewText = isset($params['previewText']) ? $params['previewText'] : false;
  225.         $ewsNotification \Pimcore\Model\DataObject::getById($id);
  226.         if (!$ewsNotification instanceof \Pimcore\Model\DataObject\EwsNotification) {
  227.             // throw new \Exception("Ews notification not found");
  228.             return ['success' => false'message' => $translator->trans('ews_notification_not_found')];
  229.         }
  230.         if (isset($params['startDate'])) {
  231.             $startTime $params['startTime'] ?? '00:00:00';
  232.             $fromDate $params['startDate'] . ' ' $startTime;
  233.             $ewsNotification->setStartDate(\Carbon\Carbon::createFromFormat('Y-m-d H:i:s'$fromDate));
  234.         }
  235.         if (isset($params['endDate'])) {
  236.             $endTime $params['endTime'] ?? '00:00:00';
  237.             $endDate $params['endDate'] . ' ' $endTime;
  238.             $ewsNotification->setEndDate(\Carbon\Carbon::createFromFormat('Y-m-d H:i:s'$endDate));
  239.         }
  240.         if (isset($message['en'])) {
  241.             $ewsNotification->setMessage($message['en'], 'en');
  242.         }
  243.         if (isset($message['ar'])) {
  244.             $ewsNotification->setMessage($message['ar'], 'ar');
  245.         }
  246.         if (!empty($regionId)) {
  247.             $regionObj DataObject\Region::getByRegionId($regionId1);
  248.             if (!empty($regionObj)) {
  249.                 $ewsNotification->setRegion($regionObj);
  250.                 if ($governorateIds) {
  251.                     $governorateIdArr explode(","$governorateIds);
  252.                     if ($governorateIdArr) {
  253.                         $applyGovernates = [];
  254.                         foreach ($governorateIdArr as $id) {
  255.                             if(!empty($id)){
  256.                                 $applyGovernates[] = \Pimcore\Model\DataObject\Governorate::getByGovernoteId($idtrue);
  257.                                 if (!empty(array_unique($applyGovernates))) {
  258.                                     $ewsNotification->setGovernorate(array_unique($applyGovernates));
  259.                                 }
  260.                             }
  261.                         }
  262.                     }
  263.                     if ($municipalities) {
  264.                         $municipalitiesIdArr explode(","$municipalities);
  265.                         if ($municipalitiesIdArr) {
  266.                             $applyMunicipalities = [];
  267.                             foreach ($municipalitiesIdArr as $id) {
  268.                                 $applyMunicipalities[] = \Pimcore\Model\DataObject\Municipality::getByMunicipalityid($idtrue);
  269.                                 if (!empty(array_unique($applyMunicipalities))) {
  270.                                     $ewsNotification->setMunicipality(array_unique($applyMunicipalities));
  271.                                 }
  272.                             }
  273.                         }
  274.                     }
  275.                 } else {
  276.                     $ewsNotification->setGovernorate($this->governorateByRegion($regionObj->getId()));
  277.                 }
  278.             }
  279.         }
  280.         if ($ewsOtherLocationIds) {
  281.             $ewsOtherLocationIdArr explode(","$ewsOtherLocationIds);
  282.             if ($ewsOtherLocationIdArr) {
  283.                 $applyOtherGovernates = [];
  284.                 foreach ($ewsOtherLocationIdArr as $id) {
  285.                     $applyOtherGovernates[] = \Pimcore\Model\DataObject\EwsOtherLocation::getByGovernoteId($idtrue);
  286.                     if (!empty(array_unique($applyOtherGovernates))) {
  287.                         $ewsNotification->setEwsOtherLocations(array_unique($applyOtherGovernates));
  288.                     }
  289.                 }
  290.             }
  291.         }
  292.         if (!empty($alertTypeId)) {
  293.             $alertType DataObject\AlertType::getByAlertTypeId($alertTypeId1);
  294.             $ewsNotification->setAlertType($alertType);
  295.         }
  296.         if (!empty($alertActionId)) {
  297.             $alertActionArr explode(","$alertActionId);
  298.             if ($alertActionArr) {
  299.                 $alertActionArrRequest = [];
  300.                 foreach ($alertActionArr as $alertActionId) {
  301.                     $alertAction DataObject\AlertAction::getByAlertActionId($alertActionId1);
  302.                     if ($alertAction) {
  303.                         $alertActionArrRequest[] = $alertAction;
  304.                     }
  305.                 }
  306.                 $ewsNotification->setAlertAction($alertActionArrRequest);
  307.             }
  308.         }
  309.         if (!empty($weatherPhenomenonId)) {
  310.             $alertStatus DataObject\AlertStatus::getByAlertStatusId($weatherPhenomenonIdtrue);
  311.             $ewsNotification->setAlertStatus($alertStatus);
  312.         }
  313.         if (!empty($alertHazardId)) {
  314.             $alertHazardArr explode(","$alertHazardId);
  315.             if ($alertHazardArr) {
  316.                 $alertHazardArrRequest = [];
  317.                 foreach ($alertHazardArr as $alertHazardId) {
  318.                     $weatherPhenomenonAffect DataObject\AlertHazard::getByAlertHazardId($alertHazardId1);
  319.                     if ($weatherPhenomenonAffect) {
  320.                         $alertHazardArrRequest[] = $weatherPhenomenonAffect;
  321.                     }
  322.                 }
  323.                 $ewsNotification->setAlertHazard($alertHazardArrRequest);
  324.             }
  325.         }
  326.         $ewsNotification->setCoordinates($coordinates);
  327.         $addressComponents $params['address_components'] ?? [];
  328.         $this->addAddressComponentsFieldCollection($addressComponents$ewsNotification);
  329.         if (!empty($params['file'])) {
  330.             $asset $this->createAsset($params['file'], time() . $params['filename']);
  331.             if ($asset) {
  332.                 $ewsNotification->setAttachment($asset);
  333.             }
  334.         }
  335.         if (!empty($params['x_img'])) {
  336.             $asset $this->createAsset($params['x_img'], time() . "EWSTwitterImages.png");
  337.             if ($asset) {
  338.                 $ewsNotification->setXAttachment($asset);
  339.             }
  340.         }
  341.         if (!empty($params['x_post'])) {
  342.             $ewsNotification->setXPost($params['x_post']);
  343.         }
  344.         $ewsNotification->setEnableTwitterNotification($enableTwitterNotification);
  345.         $ewsNotification->setEnableSMSNotification($enableSMSNotification);
  346.         $ewsNotification->setEnableEmailNotification($enableEmailNotification);
  347.         $ewsNotification->setPreviewText($previewText);
  348.         //$ewsNotification->setPublished(true);
  349.         $ewsNotification->setUser($userInterface);
  350.         $ewsNotification->setEditor($userInterface);
  351.         //set ews search Id
  352.         $currentDate = new \DateTime();
  353.         $formattedDate $currentDate->format('dmY') . '-' $ewsNotification->getId();
  354.         $searchIdEn 'Early Warning System | ' $formattedDate ' | ' ucfirst($ewsNotification->getAlertType()?->getColor()) . ' Alert | ' $ewsNotification->getWeatherPhenomenon()?->getTitle("en");
  355.         $searchIdAr $translator->trans('Early Warning System', [], null"ar") . ' | ' $formattedDate ' | ' $translator->trans(ucfirst($ewsNotification->getAlertType()?->getColor()) . ' Alert', [], null"ar") . ' | ' $ewsNotification->getWeatherPhenomenon()?->getTitle("ar");
  356.         $ewsNotification->setEwsSearchId($searchIdEn"en");
  357.         $ewsNotification->setEwsSearchId($searchIdAr"ar");
  358.         $ewsNotification->save(["versionNote" => "Update"]);
  359.         if ($isPublished) {
  360.             // send email
  361.             // Ensure you use 'php' to execute the command.
  362.             $jsonUserGroupIds json_encode($userGroupIds);
  363.             $process = new Process(['php''bin/console''app:send-early-warning-alert-email''--alertId=' $ewsNotification->getId(), '--userGroupIds=' $jsonUserGroupIds]);
  364.             $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
  365.             try {
  366.                 $process->mustRun();
  367.                 $result['success'] = true;
  368.                 $logger->info("update EwsNotification command executed successfully: " $process->getOutput());
  369.                 $result['message'] = $process->getOutput();
  370.             } catch (ProcessFailedException $exception) {
  371.                 $logger->error("update EwsNotification command failed: " $exception->getMessage());
  372.                 return ['success' => false'message' => $exception->getMessage()];
  373.             }
  374.         }
  375.         return ['success' => true'message' => $translator->trans('ews_notification_updated_successifully'), "notification_id" => $ewsNotification->getId()];
  376.         // } catch (\Exception $ex) {
  377.         //     $result = ['success' => false, 'message' => $ex->getMessage()];
  378.         // }
  379.         return $result;
  380.     }
  381.     public function governorateByRegion($regionId)
  382.     {
  383.         $governorateArr = [];
  384.         $governorateList = new DataObject\Governorate\Listing();
  385.         $governorateList->setCondition('regionId__id = ?'$regionId);
  386.         $governorateList->load();
  387.         if (!empty($governorateList)) {
  388.             foreach ($governorateList as $governorate) {
  389.                 array_push($governorateArr$governorate);
  390.             }
  391.         }
  392.         return $governorateArr;
  393.     }
  394.     public function notificationListing($params$paginator$translator): array
  395.     {
  396.         $response = [];
  397.         // try {
  398.         $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  399.         $page = isset($params['page']) ? $params['page'] : 1;
  400.         $notificationList = new DataObject\EwsNotification\Listing();
  401.         $notificationList->setUnpublished(true);
  402.         if ($params['unpublished'] == false) {
  403.             $notificationList->filterByPublished(true);
  404.         } else {
  405.             $notificationList->filterByPublished(false);
  406.         }
  407.         if (isset($params['region']) && !empty($params['region'])) {
  408.             $regionSql null;
  409.             $alertRegion \Pimcore\Model\DataObject\Region::getByRegionId($params['region'], true);
  410.             if ($alertRegion) {
  411.                 $regionSql .= "region__id = " $alertRegion->getId() . " OR ";
  412.             }
  413.             $notificationList->addConditionParam("(" substr($regionSql0, -3) . ")");
  414.         }
  415.         if (isset($params['status']) && !empty($params['status'])) {
  416.             $notificationList->addConditionParam("status IN (?)", [$params['status']]);
  417.         }
  418.         if (isset($params['addressCmp']) && !empty($params['addressCmp'])) {
  419.             //TODO
  420.         }
  421.         if (isset($params['start_date']) && !empty($params['start_date'])  && isset($params['end_date']) && !empty($params['end_date'])) {
  422.             $notificationList->filterByStartDate(strtotime($params['start_date']), ">=");
  423.             $notificationList->filterByEndDate(strtotime($params['end_date']), "<=");
  424.         }
  425.         if (isset($params['fromDate']) && isset($params['toDate']) && !empty($params['fromDate']) && !empty($params['toDate'])) {
  426.             $fromDate = new \DateTime($params['fromDate']);
  427.             $toDate = new \DateTime($params['toDate']);
  428.             $fromDateStr strtotime($fromDate->format('Y-m-d H:i:s'));
  429.             $toDateStr strtotime($toDate->format('Y-m-d') . ' 23:59:59');
  430.             $notificationList->addConditionParam(
  431.                 "(o_creationDate >= ? AND o_creationDate <= ?)",
  432.                 [$fromDateStr$toDateStr]
  433.             );
  434.         }
  435.         // Set default sorting
  436.         $notificationList->setOrderKey("o_creationDate");
  437.         $notificationList->setOrder("desc");
  438.         // Load all data for proper sorting
  439.         $notificationList->load();
  440.         if ($notificationList) {
  441.             // Create structured data for sorting (same approach as searchEwsNotification)
  442.             $sortedData = [];
  443.             foreach ($notificationList as $notification) {
  444.                 $regionEn $notification->getRegion() ? $notification->getRegion()->getName("en") : '';
  445.                 $startDate $notification->getStartDate() ? $notification->getStartDate()->format('Y-m-d H:i:s') : '';
  446.                 $endDate $notification->getEndDate() ? $notification->getEndDate()->format('Y-m-d H:i:s') : '';
  447.                 $alertStatusEn = !empty($notification->getAlertStatus()) ? $notification->getAlertStatus()->getName("en") : "";
  448.                 $creationDate $notification->getCreationDate();
  449.                 $title $notification->getStartDate() ? $notification->getStartDate()->format("dmY") . '-' $notification->getId() : '';
  450.                 $alertTypeEn $notification->getAlertType() ? ucwords($notification->getAlertType()->getColor()) : '';
  451.                 $fromDate $notification->getStartDate() ? $notification->getStartDate()->format('Y-m-d H:i:s') : '';
  452.                 $toDate $notification->getEndDate() ? $notification->getEndDate()->format('Y-m-d H:i:s') : '';
  453.                 $created_at $notification->getCreationDate() ? date("Y-m-d H:i:s"$notification->getCreationDate()) : '';
  454.                 
  455.                 $sortedData[] = [
  456.                     'notification' => $notification,
  457.                     'region' => $regionEn,
  458.                     'alertStatus' => $alertStatusEn,
  459.                     'startDate' => $startDate,
  460.                     'endDate' => $endDate,
  461.                     'creationDate' => $creationDate,
  462.                     'title' => $title,
  463.                     'alertType' => $alertTypeEn,
  464.                     'fromDate' => $fromDate,
  465.                     'toDate' => $toDate,
  466.                     'created_at' => $created_at
  467.                 ];
  468.             }
  469.             
  470.             // Apply sorting to the complete dataset
  471.             // Support multiple parameter names for sorting
  472.             $orderKey $params['orderkey'] ?? $params['orderKey'] ?? $params['sortBy'] ?? null;
  473.             $orderDirection = isset($params['order']) ? strtolower($params['order']) : 'desc';
  474.             
  475.             if ($orderKey && in_array($orderKey, ['title''alertType''fromDate''toDate''region''alertStatus''created_at'])) {
  476.                 usort($sortedData, function($a$b) use ($orderKey$orderDirection) {
  477.                     $valueA $a[$orderKey] ?? '';
  478.                     $valueB $b[$orderKey] ?? '';
  479.                     
  480.                     // Handle null/empty values
  481.                     if (empty($valueA) && !empty($valueB)) {
  482.                         return $orderDirection === 'asc' ? -1;
  483.                     }
  484.                     if (!empty($valueA) && empty($valueB)) {
  485.                         return $orderDirection === 'asc' : -1;
  486.                     }
  487.                     if (empty($valueA) && empty($valueB)) {
  488.                         return 0;
  489.                     }
  490.                     
  491.                     // For date fields, convert to timestamp for proper comparison
  492.                     if (in_array($orderKey, ['fromDate''toDate''created_at'])) {
  493.                         $timestampA strtotime($valueA);
  494.                         $timestampB strtotime($valueB);
  495.                         
  496.                         if ($timestampA === false || $timestampB === false) {
  497.                             // If date parsing fails, fall back to string comparison
  498.                             $comparison strcasecmp($valueA$valueB);
  499.                         } else {
  500.                             $comparison $timestampA <=> $timestampB;
  501.                         }
  502.                     } else {
  503.                         // For text fields, use case-insensitive string comparison
  504.                         $comparison strcasecmp($valueA$valueB);
  505.                     }
  506.                     
  507.                     return $orderDirection === 'asc' $comparison : -$comparison;
  508.                 });
  509.             }
  510.             
  511.             // Extract the sorted notifications
  512.             $sortedNotifications array_map(function ($item) {
  513.                 return $item['notification'];
  514.             }, $sortedData);
  515.             
  516.             // Convert to response format
  517.             foreach ($sortedNotifications as $notification) {
  518.                 $response[] = $this->createNotificationFormat($notification$translator);
  519.             }
  520.         }
  521.         
  522.         // If no paginator, return all sorted data
  523.         if ($paginator == null) {
  524.             return ["success" => TRUE"data" => $response];
  525.         }
  526.         $paginator $paginator->paginate(
  527.             $response,
  528.             $page,
  529.             $pageSize
  530.         );
  531.         return ["success" => TRUE"data" => $paginator"paginationVariables" => $paginator->getPaginationData()];
  532.         // return $response;
  533.         // } catch (\Exception $ex) {
  534.         //     $result = ["success" => false, "message" => $ex->getMessage()];
  535.         // }
  536.         // return $result;
  537.     }
  538.     public function capAlertNotificationListingxml($request$params$lang$translator)
  539.     {
  540.         $response = [];
  541.         try {
  542.             $notificationList = new DataObject\EwsNotification\Listing();
  543.             $notificationList->setLimit(100);
  544.             // Get the current date as a DateTime object
  545.             $timezone = new \DateTimeZone(TIMEZONE);
  546.             $currentDate = new \DateTime();
  547.             // Set the condition to filter for notifications where endDate is greater than the current date
  548.             $notificationList->setCondition("endDate > ?", [$currentDate->format('Y-m-d H:i:s')]);
  549.             $notificationList->setOrderKey("o_creationDate");
  550.             $notificationList->setOrder("desc");
  551.             // Loop through the notifications to find the last updated date
  552.             // Initialize $lastUpdatedDate with a default value or a date in the past
  553.             $lastUpdatedDate = new DateTime('1900-01-01 00:00:00'); // Replace with your desired default value
  554.             foreach ($notificationList as $notification) {
  555.                 $notificationUpdatedDate $notification->getEndDate()->setTimezone($timezone);
  556.                 if ($notificationUpdatedDate $lastUpdatedDate) {
  557.                     $lastUpdatedDate $notificationUpdatedDate;
  558.                 }
  559.             }
  560.             // Create an empty RSS XML structure
  561.             $rss = new SimpleXMLElement('<rss version="2.0"/>');
  562.             // Create the <channel> element
  563.             $channel $rss->addChild('channel');
  564.             // Add elements inside <channel>
  565.             $channel->addChild('title'$translator->trans("Early warning system from the National Center of Meteorology, Kingdom of Saudi Arabia"));
  566.             //$channel->addChild('link', 'https://ncm.gov.sa/Ar/alert/Pages/feedalerts.aspx');
  567.             $channel->addChild('link'$_ENV['BASE_URL_DEMO_AJWAA_API'] . '/' $lang '/cap-alerts');
  568.             $channel->addChild('description'$translator->trans("Early warning system from the National Center of Meteorology, Kingdom of Saudi Arabia"));
  569.             $channel->addChild('language'$lang);
  570.             $channel->addChild('copyright'$translator->trans("All rights reserved to the National Center of Meteorology, Kingdom of Saudi Arabia"));
  571.             $channel->addChild('pubDate'$lastUpdatedDate->format('D, d M Y H:i:s \G\M\T'));
  572.             // Create the <image> element
  573.             $image $channel->addChild('image');
  574.             $image->addChild('title'$translator->trans("Early warning system from the National Center of Meteorology, Kingdom of Saudi Arabia"));
  575.             $image->addChild('url'$_ENV['BASE_URL_DEMO_AJWAA_API'] . '/assets/images/logo2.3.png');
  576.             //$image->addChild('link', 'https://ncm.gov.sa/Ar/alert/Pages/feedalerts.aspx');
  577.             $image->addChild('link'$_ENV['BASE_URL_DEMO_AJWAA_API'] . '/' $lang '/cap-alerts');
  578.             // Create multiple <alert> elements and add them to the <alerts> element
  579.             // Create child elements and add them to the alert
  580.             foreach ($notificationList as $notification) { // Create two <alert> elements as an example
  581.                 $hazardNames "";
  582.                 if (!empty($notification->getAlertHazard())) {
  583.                     $hazardNamesArr = [];
  584.                     foreach ($notification->getAlertHazard() as $hazard) {
  585.                         $hazardNamesArr[] = $hazard->getName();
  586.                     }
  587.                     $hazardNames .= implode(", "$hazardNamesArr);
  588.                 }
  589.                 $governorateNames "";
  590.                 $governorateCoordinates "";
  591.                 if ($notification->getGovernorate() && !empty($notification->getGovernorate())) {
  592.                     $governorateNames .= " The governorates of ";
  593.                     $governorateNamesArr = [];
  594.                     $governorateCoordinatesArr = [];
  595.                     foreach ($notification->getGovernorate() as $governorate) {
  596.                         $governorateNamesArr[] = $governorate->getName();
  597.                         $governorateCoordinatesArr[] = $governorate->getLatitude() . "," $governorate->getLongitude();
  598.                     }
  599.                     $governorateNames .= implode(", "$governorateNamesArr) . " are expected to be affected.";
  600.                     $governorateCoordinates .= implode(" "$governorateCoordinatesArr);
  601.                 }
  602.                 // Create one or more <item> elements
  603.                 $item $channel->addChild('item');
  604.                 //$item->addChild('guid', $notification->getGuid());
  605.                 $item->addChild('guid'"{" $notification->getGuid() . "}");
  606.                 $item->addChild('title', ($notification->getAlertStatus() ? $notification->getAlertStatus()->getName($lang) : "") . " ,  " . ($notification->getRegion() ? $notification->getRegion()->getName() : ""));
  607.                 $item->addChild('link'$_ENV['BASE_URL_DEMO_AJWAA_API'] . '/cap/' $lang '/alerts/' $notification->getGuid() . '.xml');
  608.                 //$item->addChild('link', $request->getSchemeAndHttpHost() . '/cap/' . $lang . '/alerts/' . $notification->getId() . '-' . $notification->getGuid() . '.xml');
  609.                 $item->addChild('description'"A severe weather event is expected in the " . ($notification->getRegion() ? $notification->getRegion()->getName() : "UNKNOWN") . " region with a potential for " . (!empty($notification->getAlertStatus()) ? $notification->getAlertStatus()->getName($lang) : "UNKNOWN") . ", which could result in " $hazardNames ", " $governorateNames " Alert Start Date: " . (!empty($notification->getStartDate()) ? $notification->getStartDate()->format('d/m/Y H:i:s A') : "UNKNOWN") . " Alert End Date: " . (!empty($notification->getEndDate()) ? $notification->getEndDate()->format("d/m/Y H:i:s A") : "UNKNOWN"));
  610.                 $item->addChild('author'AUTHOR);
  611.                 $item->addChild('pubDate'$notification->getStartDate()->setTimeZone($timezone)->format('D, d M Y H:i:s \G\M\T'));
  612.             }
  613.             // Create additional <item> elements as needed
  614.             // Format the XML for output
  615.             $dom dom_import_simplexml($rss)->ownerDocument;
  616.             $dom->formatOutput true;
  617.             // Save the XML to a file
  618.             $xmlString $dom->saveXML();
  619.             // Set the Content-Type header to specify that the response is XML
  620.             header("Content-Type: application/xml");
  621.             // Save the XML to a file or output it
  622.             $xmlString $rss->saveXML();
  623.             print $xmlString;
  624.             exit;
  625.             return $xmlString;
  626.         } catch (\Exception $ex) {
  627.             $result = ["success" => false"message" => $ex->getMessage()];
  628.         }
  629.         return $result;
  630.     }
  631.     public function capAlertNotificationDetailxml($guid$lang$translator)
  632.     {
  633.         $response = [];
  634.         $timezone = new \DateTimeZone(TIMEZONE);
  635.         try {
  636.             $notification \Pimcore\Model\DataObject\EwsNotification::getByGuid($guidtrue);
  637.             if (empty($notification)) {
  638.                 throw new \Exception('Notification not found.');
  639.             }
  640.             $doc = new DomDocument('1.0''UTF-8');
  641.             // Create the root element
  642.             $alert $doc->createElement('alert');
  643.             $alert->setAttribute('xmlns''urn:oasis:names:tc:emergency:cap:1.2');
  644.             $doc->appendChild($alert);
  645.             // Create child elements and add them to the alert
  646.             $identifier $doc->createElement('identifier',  $notification->getGuid()); //uuid
  647.             $sender $doc->createElement('sender'SENDER_EMAIL);
  648.             $sent $doc->createElement('sent'$notification->getStartDate()->setTimezone($timezone)->format('Y-m-d\TH:i:sP'));
  649.             $status $doc->createElement('status''Actual');
  650.             $msgType $doc->createElement('msgType''Alert');
  651.             $scope $doc->createElement('scope''Public');
  652.             $alert->appendChild($identifier);
  653.             $alert->appendChild($sender);
  654.             $alert->appendChild($sent);
  655.             $alert->appendChild($status);
  656.             $alert->appendChild($msgType);
  657.             $alert->appendChild($scope);
  658.             // Create the <info> element and add it to the alert
  659.             $info $doc->createElement('info');
  660.             $alert->appendChild($info);
  661.             // Create child elements for the <info> element
  662.             $category $doc->createElement('category''Met');
  663.             $event $doc->createElement('event'$notification->getAlertStatus() ? $notification->getAlertStatus()->getName($lang) : 'UNKNOWN'); //high rain
  664.             $urgency $doc->createElement('urgency''Immediate');
  665.             //$severity = $doc->createElement('severity',  $notification->getAlertAction()[0] ? $notification->getAlertAction()[0]->getCapStatus() : "UNKNOWN");
  666.             $severity $doc->createElement('severity',  "Severe" . ($notification->getAlertAction()[0] ? $notification->getAlertAction()[0]->getCapStatus() : "UNKNOWN"));
  667.             $certainty $doc->createElement('certainty''Observed');
  668.             $onset $doc->createElement('onset'$notification->getEndDate()->setTimezone($timezone)->format('Y-m-d\TH:i:sP'));
  669.             $expires $doc->createElement('expires'$notification->getEndDate()->setTimezone($timezone)->format('Y-m-d\TH:i:sP'));
  670.             $senderName $doc->createElement('senderName'$translator->trans("Focus-National-Meteorology"));
  671.             $headline $doc->createElement('headline''SEVERE ' $notification->getAlertStatus()->getName($lang) . ' WARNING');
  672.             $hazardNames "";
  673.             if (!empty($notification->getAlertHazard())) {
  674.                 $hazardNamesArr = [];
  675.                 foreach ($notification->getAlertHazard() as $hazard) {
  676.                     $hazardNamesArr[] = $hazard->getName($lang);
  677.                 }
  678.                 $hazardNames .= implode(", "$hazardNamesArr);
  679.             }
  680.             $governorateNames "";
  681.             $governorateCoordinates "";
  682.             if ($notification->getGovernorate() && !empty($notification->getGovernorate())) {
  683.                 $governorateNames .= " The governorates of ";
  684.                 $governorateNamesArr = [];
  685.                 $governorateCoordinatesArr = [];
  686.                 foreach ($notification->getGovernorate() as $governorate) {
  687.                     $governorateNamesArr[] = $governorate->getName($lang);
  688.                     $governorateCoordinatesArr[] = $governorate->getLatitude() . "," $governorate->getLongitude();
  689.                 }
  690.                 $governorateNames .= implode(", "$governorateNamesArr) . " are expected to be affected.";
  691.                 $governorateCoordinates .= implode(" "$governorateCoordinatesArr);
  692.             }
  693.             $description $doc->createElement('description'"A severe weather event is expected in the " . ($notification->getRegion() ? $notification->getRegion()->getName($lang) : "UNKNOWN") . " region with a potential for " . (!empty($notification->getAlertStatus()) ? $notification->getAlertStatus()->getName($lang) : "UNKNOWN") . ", which could result in " $hazardNames ", " $governorateNames " Alert Start Date: " . (!empty($notification->getStartDate()) ? $notification->getStartDate()->format('d/m/Y H:i:s A') : "UNKNOWN") . " Alert End Date: " . (!empty($notification->getEndDate()) ? $notification->getEndDate()->format("d/m/Y H:i:s A") : "UNKNOWN"));
  694.             $instruction $doc->createElement('instruction''');
  695.             $contact $doc->createElement('contact'CONTACT);
  696.             $web $doc->createElement('web''https://ncm.gov.sa//Ar/alert/Pages/MapDetail.aspx?AlertId=43431&amp;amp;VId=3.0');
  697.             $info->appendChild($category);
  698.             $info->appendChild($event);
  699.             $info->appendChild($urgency);
  700.             $info->appendChild($severity);
  701.             $info->appendChild($certainty);
  702.             $info->appendChild($onset);
  703.             $info->appendChild($expires);
  704.             $info->appendChild($senderName);
  705.             $info->appendChild($headline);
  706.             $info->appendChild($description);
  707.             $info->appendChild($instruction);
  708.             $info->appendChild($contact);
  709.             // Create the <area> element and add it to the <info> element
  710.             $area $doc->createElement('area');
  711.             $info->appendChild($area);
  712.             //$info->appendChild($web);
  713.             // Create child elements for the <area> element
  714.             //$areaDesc = $doc->createElement('areaDesc', $notification->getMessage());
  715.             $areaDesc $doc->createElement('areaDesc'"Makkah region including Al Taif, Madrakah" $notification->getMessage());
  716.             $polygon '';
  717.             // Remove square brackets at the beginning and end
  718.             $coordinatesString trim($notification->getCoordinates(), '[]');
  719.             // Split the coordinates into an array
  720.             $coordinates explode("],["$coordinatesString);
  721.             foreach ($coordinates as $coordinate) {
  722.                 $parts explode(","$coordinate);
  723.                 if (count($parts) == && is_numeric($parts[0]) && is_numeric($parts[1])) {
  724.                     $polygon .= $parts[0] . "," $parts[1] . ' ';
  725.                 }
  726.             }
  727.             // Remove the trailing comma
  728.             $polygon rtrim($polygon',');
  729.             if (!empty(trim($polygon))) {
  730.                 $polygon $doc->createElement('polygon'$polygon);
  731.             } else {
  732.                 $polygonDesc $notification->getRegion() ? $notification->getRegion()->getLatitude() . "," $notification->getRegion()->getLongitude() : '';
  733.                 $polygon $doc->createElement('polygon'$polygonDesc ' ' $polygonDesc ' ' $polygonDesc ' ' $polygonDesc);
  734.             }
  735.             $area->appendChild($areaDesc);
  736.             $area->appendChild($polygon);
  737.             // Save the XML to a file or output it
  738.             $xmlString $doc->saveXML();
  739.             print $xmlString;
  740.             exit;
  741.             return $xmlString;
  742.         } catch (\Exception $ex) {
  743.             $result = ["success" => false"message" => $ex->getMessage()];
  744.         }
  745.         return $result;
  746.     }
  747.     public function viewNotification($params$translator): array
  748.     {
  749.         $result = [];
  750.         // try {
  751.         $viewNotification DataObject\EwsNotification::getById($params['id'], false);
  752.         if (!$viewNotification) {
  753.             $viewNotification DataObject\EwsNotification::getById($params['id'], true);
  754.         }
  755.         if ($viewNotification) {
  756.             $notificationData $this->createNotificationFormat($viewNotification$translator);
  757.             $history =  $this->getVersions($viewNotification$translator);
  758.             return ["success" => true"data" => $notificationData"history" => $history];
  759.         }
  760.         return ["success" => false"message" => $translator->trans("ews_notification_does_not_exists")];
  761.         // } catch (\Exception $ex) {
  762.         //     $result = ["success" => false, "message" => $ex->getMessage()];
  763.         // }
  764.         return $result;
  765.     }
  766.     public function addAddressComponentsFieldCollection($addressComponentsDataObject\EwsNotification $object)
  767.     {
  768.         $items = new \Pimcore\Model\DataObject\Fieldcollection();
  769.         foreach ($addressComponents as $Data) {
  770.             #creating field collections
  771.             $item = new DataObject\Fieldcollection\Data\AddressComponents();
  772.             $item->setAddressValue(strip_tags($Data['long_name']));
  773.             $item->setAddressKey(strip_tags($Data['types'][0]));
  774.             $items->add($item);
  775.         }
  776.         return $object->setAddressComponents($items);
  777.     }
  778.     public function getAlertAction($id)
  779.     {
  780.         $alertActionObj DataObject\AlertAction::getById($id);
  781.         $data = [];
  782.         if (!empty($alertActionObj)) {
  783.             $data['id'] = $alertActionObj->getAlertActionId();
  784.             $data['severity'] = $alertActionObj->getSeverity();
  785.             $data['nameEn'] = $alertActionObj->getName('en');
  786.             $data['nameAr'] = $alertActionObj->getName('ar');
  787.         }
  788.         return $data;
  789.     }
  790.     public function getAlertType($id)
  791.     {
  792.         $alertTypeObj DataObject\AlertType::getById($id);
  793.         $data = [];
  794.         if (!empty($alertTypeObj)) {
  795.             $data['id'] = $alertTypeObj->getAlertTypeId();
  796.             $data['nameEn'] = $alertTypeObj->getName('en');
  797.             $data['nameAr'] = $alertTypeObj->getName('ar');
  798.         }
  799.         return $data;
  800.     }
  801.     public function getAlertStatus($id)
  802.     {
  803.         $alertStatus DataObject\AlertStatus::getById($id);
  804.         $data = [];
  805.         if (!empty($alertStatus)) {
  806.             $alertType $alertStatus->getAlertType();
  807.             $alertData = [];
  808.             if (!empty($alertType)) {
  809.                 $alertData = [
  810.                     "id" => $alertType->getAlertTypeId(),
  811.                     "nameEn" => $alertType->getName('en'),
  812.                     "nameAr" => $alertType->getName('ar')
  813.                 ];
  814.             }
  815.             $data['id'] = $alertStatus->getAlertStatusId();
  816.             $data['nameEn'] = $alertStatus->getName('en');
  817.             $data['nameAr'] = $alertStatus->getName('ar');
  818.             $data['alertType'] = $alertData;
  819.         }
  820.         return $data;
  821.     }
  822.     public function getAlertHazard($id)
  823.     {
  824.         $alertHazardObj DataObject\AlertHazard::getById($id);
  825.         $data = [];
  826.         if (!empty($alertHazardObj)) {
  827.             $data['id'] = $alertHazardObj->getAlertHazardId();
  828.             $data['nameEn'] = $alertHazardObj->getName('en');
  829.             $data['nameAr'] = $alertHazardObj->getName('ar');
  830.         }
  831.         return $data;
  832.     }
  833.     public function getRegion($id)
  834.     {
  835.         $regionObj DataObject\Region::getById($id);
  836.         $data = [];
  837.         if (!empty($regionObj)) {
  838.             $data['id'] = $regionObj->getRegionId();
  839.             $data['nameEn'] = $regionObj->getName('en');
  840.             $data['nameAr'] = $regionObj->getName('ar');
  841.             $data['longitude'] = $regionObj->getLongitude();
  842.             $data['latitude'] = $regionObj->getLatitude();
  843.         }
  844.         return $data;
  845.     }
  846.     public function getEvent($id)
  847.     {
  848.         $eventObj DataObject\Event::getById($id);
  849.         $data = [];
  850.         if (!empty($eventObj)) {
  851.             $data['id'] = $eventObj->getEventId();
  852.             $data['nameEn'] = $eventObj->getName('en');
  853.             $data['nameAr'] = $eventObj->getName('ar');
  854.         }
  855.         return $data;
  856.     }
  857.     public function getWeatherPhenomenon($id)
  858.     {
  859.         $weatherPhenObj DataObject\PhenomenaList::getById($id);
  860.         $data = [];
  861.         if (!empty($weatherPhenObj)) {
  862.             $data['id'] = $weatherPhenObj->getPhenomenaListId();
  863.             $data['nameEn'] = $weatherPhenObj->getTitle('en');
  864.             $data['nameAr'] = $weatherPhenObj->getTitle('ar');
  865.         }
  866.         return $data;
  867.     }
  868.     public function getWeatherPhenAffect($id)
  869.     {
  870.         $weatherPhenObj DataObject\WeatherPhenomenonAffect::getById($id);
  871.         $data = [];
  872.         if (!empty($weatherPhenObj)) {
  873.             $data['id'] = $weatherPhenObj->getWeatherPhenomenonAffectId();
  874.             $data['nameEn'] = $weatherPhenObj->getName('en');
  875.             $data['nameAr'] = $weatherPhenObj->getName('ar');
  876.         }
  877.         return $data;
  878.     }
  879.     // public function getGovernorateDetail($governorateList)
  880.     // {
  881.     //     $result = [];
  882.     //     if (!empty($governorateList)) {
  883.     //         for ($i = 0; $i < count($governorateList); $i++) {
  884.     //             $parentGovernates = null;
  885.     //             if ($governorateList[$i]->getIsMunicipality()) {
  886.     //                 $municipatlity = \Pimcore\Model\DataObject\Municipality::getByMunicipalityId($governorateList[$i]->getMunicipalityID(), true);
  887.     //                 if ($municipatlity &&  $municipatlity->getGovernorate()) {
  888.     //                     $parentGovernates = $municipatlity->getGovernorate();
  889.     //                 }
  890.     //             }
  891.     //             $result[$i]['id'] = $governorateList[$i]->getGovernoteId();
  892.     //             $result[$i]['nameEn'] = $governorateList[$i]->getName('en');
  893.     //             $result[$i]['nameAr'] = $governorateList[$i]->getName('ar');
  894.     //             $result[$i]['longitude'] = $governorateList[$i]->getLongitude();
  895.     //             $result[$i]['latitude'] = $governorateList[$i]->getLatitude();
  896.     //             $result[$i]['parentId'] = $parentGovernates ? $parentGovernates->getGovernoteId() : null;
  897.     //             $result[$i]['parenNameEn'] = $parentGovernates ? $parentGovernates->getName('en') : null;
  898.     //             $result[$i]['parenNameAr'] = $parentGovernates ? $parentGovernates->getName('ar') : null;
  899.     //             $result[$i]['parentLongitude'] = $parentGovernates ? $parentGovernates->getLongitude() : null;
  900.     //             $result[$i]['parentLatitude'] = $parentGovernates ? $parentGovernates->getLatitude() : null;
  901.     //             $result[$i]['isMunicipality'] = $governorateList[$i]->getIsMunicipality();
  902.     //             $result[$i]['municipalities'] = [];
  903.     //         }
  904.     //     }
  905.     //     return $result;
  906.     // }
  907.     public function getGovernorateDetail($governorateList)
  908.     {
  909.         $result = [];
  910.         if (!empty($governorateList)) {
  911.             $uniqueGovernorateArray = [];
  912.             foreach ($governorateList as $governorate) {
  913.                 $parentGovernates null;
  914.                 // Check if it is a municipality and fetch parent governorate
  915.                 if ($governorate->getIsMunicipality()) {
  916.                     $municipality \Pimcore\Model\DataObject\Municipality::getByMunicipalityId($governorate->getMunicipalityID(), true);
  917.                     if ($municipality && $municipality->getGovernorate()) {
  918.                         $parentGovernates $municipality->getGovernorate();
  919.                     }
  920.                 }
  921.                 // Initialize a unique governorate array if needed
  922.                 $parentId $parentGovernates $parentGovernates->getGovernoteId() : $governorate->getGovernoteId();
  923.                 if (!isset($uniqueGovernorateArray[$parentId])) {
  924.                     $uniqueGovernorateArray[$parentId] = [
  925.                         'id' => $parentId,
  926.                         'nameEn' => $parentGovernates $parentGovernates->getName('en') : $governorate->getName('en'),
  927.                         'nameAr' => $parentGovernates $parentGovernates->getName('ar') : $governorate->getName('ar'),
  928.                         'longitude' => $parentGovernates $parentGovernates->getLongitude() : $governorate->getLongitude(),
  929.                         'latitude' => $parentGovernates $parentGovernates->getLatitude() : $governorate->getLatitude(),
  930.                         'municipalities' => []
  931.                     ];
  932.                 }
  933.                 // Add municipality details if it is a municipality
  934.                 if ($governorate->getIsMunicipality()) {
  935.                     $uniqueGovernorateArray[$parentId]['municipalities'][] = [
  936.                         'id' => $governorate->getGovernoteId(),
  937.                         'nameEn' => $governorate->getName('en'),
  938.                         'nameAr' => $governorate->getName('ar'),
  939.                         'longitude' => $governorate->getLongitude(),
  940.                         'latitude' => $governorate->getLatitude()
  941.                     ];
  942.                 }
  943.             }
  944.             // Flatten the associative array to a numerical array for output
  945.             $result array_values($uniqueGovernorateArray);
  946.         }
  947.         return $result;
  948.     }
  949.     public function getMessageDetail($notificationObj)
  950.     {
  951.         $data = [];
  952.         if (!empty($notificationObj)) {
  953.             $data['messageEn'] = $notificationObj->getMessage('en');
  954.             $data['messageAr'] = $notificationObj->getMessage('ar');
  955.         }
  956.         return $data;
  957.     }
  958.     public function createAsset($fileData$filename)
  959.     {
  960.         // Validate the file data
  961.         if (preg_match('/^data:(image\/(png|jpe?g)|application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel));base64,/'$fileData) !== 1) {
  962.             return false// Invalid file data or MIME type
  963.         }
  964.         // Extract the file extension from the MIME type
  965.         $extension '';
  966.         if (preg_match('/^data:image\/(png|jpe?g);base64,/'$fileData)) {
  967.             $extension 'jpg'// Assume JPG for base64-encoded image data (PNG or JPEG)
  968.         } elseif (preg_match('/^data:application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel);base64,/'$fileData)) {
  969.             $extension 'pdf'// PDF, DOCX, or Excel
  970.         }
  971.         // Remove the "data:image/png;base64," or "data:application/pdf;base64," prefix to get the actual base64-encoded content
  972.         $base64Content preg_replace('/^data:(image\/png|application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel));base64,/'''$fileData);
  973.         // Decode the base64-encoded content
  974.         $fileContent base64_decode($base64Content);
  975.         // Validate the decoded content
  976.         if ($fileContent === false) {
  977.             return false// Invalid base64-encoded content
  978.         }
  979.         // Create the Pimcore asset
  980.         $asset = new \Pimcore\Model\Asset();
  981.         $parent Asset\Service::createFolderByPath('/EWSNotification');
  982.         $asset->setFilename($filename); // Replace with the desired filename and extension
  983.         $asset->setParent($parent);
  984.         $asset->setData($fileContent);
  985.         // Set the MIME type based on the file extension
  986.         $mimeType '';
  987.         if ($extension === 'pdf') {
  988.             $mimeType 'application/pdf';
  989.         } elseif ($extension === 'jpg') {
  990.             $mimeType 'image/jpeg';
  991.         } elseif ($extension === 'png') {
  992.             $mimeType 'image/png';
  993.         } elseif ($extension === 'docx') {
  994.             $mimeType 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  995.         } elseif ($extension === 'xlsx') {
  996.             $mimeType 'application/vnd.ms-excel';
  997.         }
  998.         // Validate the MIME type
  999.         if (!in_array($mimeType, ['image/jpeg''image/png''application/pdf''application/vnd.openxmlformats-officedocument.wordprocessingml.document''application/vnd.ms-excel'])) {
  1000.             return false// Invalid MIME type
  1001.         }
  1002.         $asset->setType($mimeType);
  1003.         // Save the asset
  1004.         $asset->save();
  1005.         return $asset;
  1006.     }
  1007.     public function getPhenomenaListByAlertId($alertID$lang "en")
  1008.     {
  1009.         $response = [];
  1010.         $alertType \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alertIDtrue);
  1011.         if ($alertType instanceof \Pimcore\Model\DataObject\AlertType) {
  1012.             $phenomenaList $alertType->getPhenomenaList();
  1013.             if ($phenomenaList) {
  1014.                 foreach ($phenomenaList as $phenomena) {
  1015.                     $phenomenaId $phenomena->getPhenomena();
  1016.                     if ($phenomenaId) {
  1017.                         $phenomenaObj \Pimcore\Model\DataObject::getById($phenomenaId);
  1018.                         $response[] = ["id" => $phenomenaObj->getphenomenaListId(), "nameEn" => $phenomenaObj->getTitle("en"), "nameAr" => $phenomenaObj->getTitle("ar"), "criteria" => $phenomena->getCriteria()];
  1019.                     }
  1020.                 }
  1021.             } else {
  1022.                 return ["success" => false"message" => "No criteria is set"];
  1023.             }
  1024.         } else {
  1025.             return ["success" => false"message" => "Invalid alert type id"];
  1026.         }
  1027.         return ["success" => true"data" => $response];
  1028.     }
  1029.     public function getPhenomenaListByAlertIds($alertIDs$lang "en")
  1030.     {
  1031.         $response = [];
  1032.         if (count($alertIDs) > 0) {
  1033.             foreach ($alertIDs as $alertID) {
  1034.                 $alertType \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alertIDtrue);
  1035.                 if ($alertType instanceof \Pimcore\Model\DataObject\AlertType) {
  1036.                     $phenomenaList $alertType->getPhenomenaList();
  1037.                     if ($phenomenaList) {
  1038.                         foreach ($phenomenaList as $phenomena) {
  1039.                             $phenomenaId $phenomena->getPhenomena();
  1040.                             if ($phenomenaId) {
  1041.                                 $phenomenaObj \Pimcore\Model\DataObject::getById($phenomenaId);
  1042.                                 if ($phenomenaObj instanceof \Pimcore\Model\DataObject) {
  1043.                                     $currentId $phenomenaObj->getphenomenaListId();
  1044.                                     $existingIds array_column($response'id');
  1045.                                     if (!in_array($currentId$existingIds)) {
  1046.                                         $response[] = [
  1047.                                             "id" => $currentId,
  1048.                                             "nameEn" => $phenomenaObj->getTitle("en"),
  1049.                                             "nameAr" => $phenomenaObj->getTitle("ar"),
  1050.                                             "criteria" => $phenomena->getCriteria()
  1051.                                         ];
  1052.                                     } else {
  1053.                                         $index array_search($currentId$existingIds);
  1054.                                         $response[$index]['criteria'] .= ', ' $phenomena->getCriteria();
  1055.                                     }
  1056.                                 }
  1057.                             }
  1058.                         }
  1059.                     } else {
  1060.                         return ["success" => false"message" => "No criteria is set"];
  1061.                     }
  1062.                 }
  1063.             }
  1064.             return ["success" => true"data" => $response];
  1065.         }
  1066.         return ["success" => false"message" => "Invalid alert type id"];
  1067.     }
  1068.     public function getAlertActions()
  1069.     {
  1070.         $response = [];
  1071.         $alertActions = new DataObject\AlertAction\Listing();
  1072.         $alertActions $alertActions->load();
  1073.         if ($alertActions) {
  1074.             foreach ($alertActions as $alertAction) {
  1075.                 $response[] = [
  1076.                     "id" => $alertAction->getAlertActionId(),
  1077.                     "nameEn" => $alertAction->getName('en'),
  1078.                     "nameAr" => $alertAction->getName('ar'),
  1079.                     "severity" => $alertAction->getSeverity()
  1080.                 ];
  1081.             }
  1082.         }
  1083.         return ["success" => true"data" => $response];
  1084.     }
  1085.     public function getAlertHazards()
  1086.     {
  1087.         $response = [];
  1088.         $alertHazards = new DataObject\AlertHazard\Listing();
  1089.         $alertHazards $alertHazards->load();
  1090.         if ($alertHazards) {
  1091.             foreach ($alertHazards as $alertHazard) {
  1092.                 $response[] = [
  1093.                     "id" => $alertHazard->getalertHazardId(),
  1094.                     "nameEn" => $alertHazard->getName('en'),
  1095.                     "nameAr" => $alertHazard->getName('ar'),
  1096.                     "OrderId" => $alertHazard->getOrderId()
  1097.                 ];
  1098.             }
  1099.         }
  1100.         return ["success" => true"data" => $response];
  1101.     }
  1102.     public function getAlertTypes()
  1103.     {
  1104.         $response = [];
  1105.         $alertTypes = new DataObject\AlertType\Listing();
  1106.         $alertTypes $alertTypes->load();
  1107.         if ($alertTypes) {
  1108.             foreach ($alertTypes as $alertType) {
  1109.                 $response[] = [
  1110.                     "id" => $alertType->getAlertTypeId(),
  1111.                     "color" => $alertType->getColor(),
  1112.                     "nameEn" => $alertType->getName('en'),
  1113.                     "nameAr" => $alertType->getName('ar')
  1114.                 ];
  1115.             }
  1116.         }
  1117.         return ["success" => true"data" => $response];
  1118.     }
  1119.     public function getEvents()
  1120.     {
  1121.         $response = [];
  1122.         $events = new DataObject\Event\Listing();
  1123.         $events $events->load();
  1124.         if ($events) {
  1125.             foreach ($events as $event) {
  1126.                 $response[] = [
  1127.                     "id" => $event->getEventId(),
  1128.                     "nameEn" => $event->getName('en'),
  1129.                     "nameAr" => $event->getName('ar')
  1130.                 ];
  1131.             }
  1132.         }
  1133.         return ["success" => true"data" => $response];
  1134.     }
  1135.     public function getWeatherPhenomenones()
  1136.     {
  1137.         $response = [];
  1138.         $weatherPhenomenons = new DataObject\PhenomenaList\Listing();
  1139.         $weatherPhenomenons $weatherPhenomenons->load();
  1140.         if ($weatherPhenomenons) {
  1141.             foreach ($weatherPhenomenons as $weatherPhenomenon) {
  1142.                 $response[] = [
  1143.                     "id" => $weatherPhenomenon->getPhenomenaListId(),
  1144.                     "nameEn" => $weatherPhenomenon->getTitle('en'),
  1145.                     "nameAr" => $weatherPhenomenon->getTitle('ar')
  1146.                 ];
  1147.             }
  1148.         }
  1149.         return ["success" => true"data" => $response];
  1150.     }
  1151.     public function getWeatherPhenomenonAffect()
  1152.     {
  1153.         $response = [];
  1154.         $getWeatherPhenomAffects = new DataObject\WeatherPhenomenonAffect\Listing();
  1155.         $getWeatherPhenomAffects $getWeatherPhenomAffects->load();
  1156.         if ($getWeatherPhenomAffects) {
  1157.             foreach ($getWeatherPhenomAffects as $getWeatherPhenomAffect) {
  1158.                 $response[] = [
  1159.                     "id" => $getWeatherPhenomAffect->getWeatherPhenomenonAffectId(),
  1160.                     "nameEn" => $getWeatherPhenomAffect->getName('en'),
  1161.                     "nameAr" => $getWeatherPhenomAffect->getName('ar')
  1162.                 ];
  1163.             }
  1164.         }
  1165.         return ["success" => true"data" => $response];
  1166.     }
  1167.     public function getAlertStatuses($params)
  1168.     {
  1169.         $response = [];
  1170.         $alertStatuss = new DataObject\AlertStatus\Listing();
  1171.         // Handle search by name
  1172.         if (isset($params['search']) && !empty($params['search'])) {
  1173.             $alertStatuss->addConditionParam("name LIKE ?""%" $params['search'] . "%");
  1174.         }
  1175.         // Handle alert type filter
  1176.         if (isset($params['alert_id']) && !empty($params['alert_id'])) {
  1177.             $alertTypeIds = [];
  1178.             $alertTypeList = new DataObject\AlertType\Listing();
  1179.             $alertTypeList->addConditionParam("alertTypeId IN (?)", [$params['alert_id']]);
  1180.             foreach ($alertTypeList as $alertType) {
  1181.                 $alertTypeIds[] = $alertType->getId();
  1182.             }
  1183.             $alertStatuss->addConditionParam("alertType__id IN (?)", [$alertTypeIds]);
  1184.         }
  1185.         // Check for regionId array and isLandLocked logic
  1186.         $excludeWavesRising false;
  1187.         if (isset($params['regionId']) && is_array($params['regionId']) && count($params['regionId']) > 0) {
  1188.             foreach ($params['regionId'] as $regionId) {
  1189.                 $region \Pimcore\Model\DataObject\Region::getByRegionId($regionIdtrue);
  1190.                 if ($region && $region->getIsLandLocked()) {
  1191.                     $excludeWavesRising true;
  1192.                     break;
  1193.                 }
  1194.             }
  1195.         }
  1196.         $alertStatuss $alertStatuss->load();
  1197.         if ($alertStatuss) {
  1198.             foreach ($alertStatuss as $alertStatus) {
  1199.                 // Exclude "Waves rising" if needed
  1200.                 if ($excludeWavesRising && ((strtolower(trim($alertStatus->getName('en'))) === 'waves rising'))) {
  1201.                     continue;
  1202.                 }
  1203.                 $alertType $alertStatus->getAlertType();
  1204.                 $alertData = [];
  1205.                 if (!empty($alertType)) {
  1206.                     $alertData = [
  1207.                         "id" => $alertType->getAlertTypeId(),
  1208.                         "nameEn" => $alertType->getName('en'),
  1209.                         "nameAr" => $alertType->getName('ar')
  1210.                     ];
  1211.                 }
  1212.                 $response[] = [
  1213.                     "id" => $alertStatus->getalertStatusId(),
  1214.                     "nameEn" => $alertStatus->getName('en'),
  1215.                     "nameAr" => $alertStatus->getName('ar'),
  1216.                     "imageTemplate" => $alertStatus->getimageTemplate(),
  1217.                     "alertType" => $alertData
  1218.                 ];
  1219.             }
  1220.         }
  1221.         return ["success" => true"data" => $response];
  1222.     }
  1223.     public function getGovernorates()
  1224.     {
  1225.         $response = [];
  1226.         $governorates = new DataObject\Governorate\Listing();
  1227.         $Governorates $governorates->load();
  1228.         if ($governorates) {
  1229.             foreach ($governorates as $governorate) {
  1230.                 $region $governorate->getregionId();
  1231.                 $regionData = [];
  1232.                 if (!empty($region)) {
  1233.                     $regionData = [
  1234.                         "id" => $region->getRegionId(),
  1235.                         "nameEn" => $region->getName('en'),
  1236.                         "nameAr" => $region->getName('ar'),
  1237.                         "longitude" => $region->getLongitude(),
  1238.                         "latitude" => $region->getLongitude()
  1239.                     ];
  1240.                 }
  1241.                 $response[] = [
  1242.                     "id" => $governorate->getgovernoteId(),
  1243.                     "nameEn" => $governorate->getName('en'),
  1244.                     "nameAr" => $governorate->getName('ar'),
  1245.                     "regionId" => $regionData,
  1246.                     "longitude" => $governorate->getLongitude(),
  1247.                     "latitude" => $governorate->getLatitude(),
  1248.                     "isHidden" => $governorate->getisHidden(),
  1249.                     "IsMunicipality" => $governorate->getIsMunicipality(),
  1250.                     "MunicipalityID" => $governorate->getMunicipalityID()
  1251.                 ];
  1252.             }
  1253.         }
  1254.         return ["success" => true"data" => $response];
  1255.     }
  1256.     public function getMunicipality($governorateId null$lang 'en')
  1257.     {
  1258.         $response = [];
  1259.         $municipalities = new DataObject\Municipality\Listing();
  1260.         if (is_array($governorateId)) {
  1261.             $govIdsArr = [];
  1262.             foreach ($governorateId as $govId) {
  1263.                 $governorate \Pimcore\Model\DataObject\Governorate::getByGovernoteId($govIdtrue);
  1264.                 if ($governorate) {
  1265.                     array_push($govIdsArr$governorate->getId());
  1266.                 }
  1267.             }
  1268.             $municipalities->setCondition("governorate__id IN (" implode(", "$govIdsArr) . ")");
  1269.         } else {
  1270.             if ($governorateId) {
  1271.                 $governorate \Pimcore\Model\DataObject\Governorate::getByGovernoteId($governorateIdtrue);
  1272.                 $municipalities->setCondition("governorate__id = ?", [$governorate->getId()]);
  1273.             }
  1274.         }
  1275.         $municipalities $municipalities->load();
  1276.         if ($municipalities) {
  1277.             foreach ($municipalities as $municipality) {
  1278.                 $response[] = [
  1279.                     "id" => $municipality->getMunicipalityid(),
  1280.                     "nameEn" => $municipality->getName('en'),
  1281.                     "nameAr" => $municipality->getName('ar'),
  1282.                     "longitude" => $municipality->getLongitude(),
  1283.                     "latitude" => $municipality->getLatitude(),
  1284.                     "governate" => $municipality->getGovernorate()->getGovernoteId()
  1285.                 ];
  1286.             }
  1287.         }
  1288.         // Determine sorting field based on language
  1289.         $sortField 'nameEn'// Default sorting by English
  1290.         if (isset($lang) && strtolower($lang) === 'ar') {
  1291.             $sortField 'nameAr'// Sorting by Arabic
  1292.         }
  1293.         // Sort manually using usort()
  1294.         usort($response, function ($a$b) use ($sortField) {
  1295.             return strcmp($a[$sortField], $b[$sortField]);
  1296.         });
  1297.         return ["success" => true"data" => $response];
  1298.     }
  1299.     public function getMunicipalityByParams($governorateId null,$search null$lang 'en')
  1300.     {
  1301.         $response = [];
  1302.         $municipalities = new DataObject\Municipality\Listing();
  1303.         if (is_array($governorateId)) {
  1304.             $govIdsArr = [];
  1305.             foreach ($governorateId as $govId) {
  1306.                 $governorate \Pimcore\Model\DataObject\Governorate::getByGovernoteId($govIdtrue);
  1307.                 if ($governorate) {
  1308.                     array_push($govIdsArr$governorate->getId());
  1309.                 }
  1310.             }
  1311.             $municipalities->setCondition("governorate__id IN (" implode(", "$govIdsArr) . ")");
  1312.         } else {
  1313.             if ($governorateId) {
  1314.                 $governorate \Pimcore\Model\DataObject\Governorate::getByGovernoteId($governorateIdtrue);
  1315.                 $municipalities->setCondition("governorate__id = ?", [$governorate->getId()]);
  1316.             }
  1317.         }
  1318.         if (isset($search)) {
  1319.             $municipalities->addConditionParam("name LIKE ?""%{$search}%");
  1320.         }
  1321.         $municipalities $municipalities->load();
  1322.         if ($municipalities) {
  1323.             foreach ($municipalities as $municipality) {
  1324.                 $response[] = [
  1325.                     "id" => $municipality->getMunicipalityid(),
  1326.                     "nameEn" => $municipality->getName('en'),
  1327.                     "nameAr" => $municipality->getName('ar'),
  1328.                     "longitude" => $municipality->getLongitude(),
  1329.                     "latitude" => $municipality->getLatitude(),
  1330.                     "governate" => $municipality->getGovernorate()->getGovernoteId()
  1331.                 ];
  1332.             }
  1333.         }
  1334.         // Determine sorting field based on language
  1335.         $sortField 'nameEn'// Default sorting by English
  1336.         if (isset($lang) && strtolower($lang) === 'ar') {
  1337.             $sortField 'nameAr'// Sorting by Arabic
  1338.         }
  1339.         // Sort manually using usort()
  1340.         usort($response, function ($a$b) use ($sortField) {
  1341.             return strcmp($a[$sortField], $b[$sortField]);
  1342.         });
  1343.         return ["success" => true"data" => $response];
  1344.     }
  1345.     public function getGovernoratesByRegion($params)
  1346.     {
  1347.         $response = [];
  1348.         $governorates = new DataObject\Governorate\Listing();
  1349.         if (isset($params['region_id'])) {
  1350.             $region \Pimcore\Model\DataObject\Region::getByRegionId($params['region_id'], true);
  1351.             if (!$region) {
  1352.                 throw new \Exception("Region not available");
  1353.             }
  1354.             $governorates->filterByRegionId($region);
  1355.         }
  1356.         if (isset($params['region_ids']) && !empty($params['region_ids'])) {
  1357.             $regionIds = [];
  1358.             $regionList = new DataObject\Region\Listing();
  1359.             $regionList->addConditionParam("regionId IN (?)", [$params['region_ids']]);
  1360.             foreach ($regionList as $region) {
  1361.                 $regionIds[] = $region->getId();
  1362.             }
  1363.             $governorates->addConditionParam("regionId__id IN (?)", [$regionIds]);
  1364.         }
  1365.         // Load governorates without sorting in Pimcore
  1366.         $governorates $governorates->load();
  1367.         // Convert to array for manual sorting
  1368.         $count 0;
  1369.         if ($governorates) {
  1370.             foreach ($governorates as $governorate) {
  1371.                 $region $governorate->getregionId();
  1372.                 $regionData = [];
  1373.                 if (!empty($region)) {
  1374.                     $regionData = [
  1375.                         "id" => $region->getRegionId(),
  1376.                         "nameEn" => $region->getName('en'),
  1377.                         "nameAr" => $region->getName('ar'),
  1378.                         "longitude" => $region->getLongitude(),
  1379.                         "latitude" => $region->getLatitude()
  1380.                     ];
  1381.                 }
  1382.                 $response[$count] = [
  1383.                     "id" => $governorate->getgovernoteId(),
  1384.                     "nameEn" => $governorate->getName('en'),
  1385.                     "nameAr" => $governorate->getName('ar'),
  1386.                     "regionId" => $regionData,
  1387.                     "longitude" => $governorate->getLongitude(),
  1388.                     "latitude" => $governorate->getLatitude(),
  1389.                     "isHidden" => $governorate->getisHidden(),
  1390.                     "IsMunicipality" => $governorate->getIsMunicipality(),
  1391.                     "MunicipalityID" => $governorate->getMunicipalityID(),
  1392.                     "bbox" => $governorate->getBbox()
  1393.                 ];
  1394.                 if ($governorate->getMunicipalityID() && $governorate->getIsMunicipality()) {
  1395.                     $municipality \Pimcore\Model\DataObject\Municipality::getBymunicipalityid($governorate->getMunicipalityID(), true);
  1396.                     if ($municipality) {
  1397.                         $muniGovernate $municipality->getgovernorate();
  1398.                         if ($muniGovernate) {
  1399.                             $response[$count]["parent_id"] = $muniGovernate->getgovernoteId();
  1400.                             $response[$count]["parent_longitude"] = $muniGovernate->getLongitude();
  1401.                             $response[$count]["parent_latitude"] = $muniGovernate->getLatitude();
  1402.                             $response[$count]["parent_name_en"] = $muniGovernate->getName("en");
  1403.                             $response[$count]["parent_name_ar"] = $muniGovernate->getName("ar");
  1404.                         }
  1405.                     }
  1406.                 }
  1407.                 $count++;
  1408.             }
  1409.         }
  1410.         // Determine sorting field based on language
  1411.         $sortField 'nameEn'// Default sorting by English
  1412.         if (isset($params['lang']) && strtolower($params['lang']) === 'ar') {
  1413.             $sortField 'nameAr'// Sorting by Arabic
  1414.         }
  1415.         // Sort manually using usort()
  1416.         usort($response, function ($a$b) use ($sortField) {
  1417.             return strcmp($a[$sortField], $b[$sortField]);
  1418.         });
  1419.         return ["success" => true"data" => $response];
  1420.     }
  1421.     public function getGovernoratesByParams($params)
  1422.     {
  1423.         $response = [];
  1424.         $governorates = new DataObject\Governorate\Listing();
  1425.         if (isset($params['region_id'])) {
  1426.             $region \Pimcore\Model\DataObject\Region::getByRegionId($params['region_id'], true);
  1427.             if (!$region) {
  1428.                 throw new \Exception("Region not available");
  1429.             }
  1430.             $governorates->filterByRegionId($region);
  1431.         }
  1432.         if (isset($params['region_ids']) && !empty($params['region_ids'])) {
  1433.             $regionIds = [];
  1434.             $regionList = new DataObject\Region\Listing();
  1435.             $regionList->addConditionParam("regionId IN (?)", [$params['region_ids']]);
  1436.             foreach ($regionList as $region) {
  1437.                 $regionIds[] = $region->getId();
  1438.             }
  1439.             $governorates->addConditionParam("regionId__id IN (?)", [$regionIds]);
  1440.         }
  1441.         if (isset($params['search'])) {
  1442.             $governorates->addConditionParam("name LIKE ?""%{$params['search']}%");
  1443.         }
  1444.         // Load governorates without sorting in Pimcore
  1445.         $governorates $governorates->load();
  1446.         // Convert to array for manual sorting
  1447.         $count 0;
  1448.         if ($governorates) {
  1449.             foreach ($governorates as $governorate) {
  1450.                 $region $governorate->getregionId();
  1451.                 $regionData = [];
  1452.                 if (!empty($region)) {
  1453.                     $regionData = [
  1454.                         "id" => $region->getRegionId(),
  1455.                         "nameEn" => $region->getName('en'),
  1456.                         "nameAr" => $region->getName('ar'),
  1457.                         "longitude" => $region->getLongitude(),
  1458.                         "latitude" => $region->getLatitude()
  1459.                     ];
  1460.                 }
  1461.                 $response[$count] = [
  1462.                     "id" => $governorate->getgovernoteId(),
  1463.                     "nameEn" => $governorate->getName('en'),
  1464.                     "nameAr" => $governorate->getName('ar'),
  1465.                     "regionId" => $regionData,
  1466.                     "longitude" => $governorate->getLongitude(),
  1467.                     "latitude" => $governorate->getLatitude(),
  1468.                     "isHidden" => $governorate->getisHidden(),
  1469.                     "IsMunicipality" => $governorate->getIsMunicipality(),
  1470.                     "MunicipalityID" => $governorate->getMunicipalityID(),
  1471.                     "bbox" => $governorate->getBbox()
  1472.                 ];
  1473.                 if ($governorate->getMunicipalityID() && $governorate->getIsMunicipality()) {
  1474.                     $municipality \Pimcore\Model\DataObject\Municipality::getBymunicipalityid($governorate->getMunicipalityID(), true);
  1475.                     if ($municipality) {
  1476.                         $muniGovernate $municipality->getgovernorate();
  1477.                         if ($muniGovernate) {
  1478.                             $response[$count]["parent_id"] = $muniGovernate->getgovernoteId();
  1479.                             $response[$count]["parent_longitude"] = $muniGovernate->getLongitude();
  1480.                             $response[$count]["parent_latitude"] = $muniGovernate->getLatitude();
  1481.                             $response[$count]["parent_name_en"] = $muniGovernate->getName("en");
  1482.                             $response[$count]["parent_name_ar"] = $muniGovernate->getName("ar");
  1483.                         }
  1484.                     }
  1485.                 }
  1486.                 $count++;
  1487.             }
  1488.         }
  1489.         // Determine sorting field based on language
  1490.         $sortField 'nameEn'// Default sorting by English
  1491.         if (isset($params['lang']) && strtolower($params['lang']) === 'ar') {
  1492.             $sortField 'nameAr'// Sorting by Arabic
  1493.         }
  1494.         // Sort manually using usort()
  1495.         usort($response, function ($a$b) use ($sortField) {
  1496.             return strcmp($a[$sortField], $b[$sortField]);
  1497.         });
  1498.         return ["success" => true"data" => $response];
  1499.     }
  1500.     public function getVersions($notificationObject$translator)
  1501.     {
  1502.         $result = [];
  1503.         $versions $notificationObject->getVersions();
  1504.         if ($versions) {
  1505.             foreach ($versions as $version) {
  1506.                 $note $version->getNote();
  1507.                 if ($note == "Update") {
  1508.                     $viewNotification $version->loadData();
  1509.                     if ($viewNotification instanceof EwsNotification) {
  1510.                         $result[] = $this->createNotificationFormat($viewNotification$translator);
  1511.                     }
  1512.                 }
  1513.             }
  1514.         }
  1515.         return $result;
  1516.     }
  1517.     private function createNotificationFormat($notification$translator)
  1518.     {
  1519.         $response = [];
  1520.         $critetia '';
  1521.         $critetiaAr '';
  1522.         $status 'active';
  1523.         $alertType $notification->getAlertType();
  1524.         $phenomena $notification->getWeatherPhenomenon();
  1525.         // Set the timezone to Asia/Riyadh
  1526.         $timezone = new \DateTimeZone(TIMEZONE);
  1527.         // Convert start and end dates to Asia/Riyadh timezone
  1528.         $startDate $notification->getStartDate() ? $notification->getStartDate()->setTimezone($timezone) : null;
  1529.         $endDate $notification->getEndDate() ? $notification->getEndDate()->setTimezone($timezone) : null;
  1530.         if ($alertType && $phenomena) {
  1531.             $phenomenaList $alertType->getPhenomenaList();
  1532.             if ($phenomenaList) {
  1533.                 $items $phenomenaList->getItems();
  1534.                 if ($items) {
  1535.                     foreach ($items as $item) {
  1536.                         if ($item->getPhenomena() == $phenomena->getId()) {
  1537.                             $critetia $item->getCriteria();
  1538.                             $critetiaAr $item->getCriteriaAr();
  1539.                             break;
  1540.                         }
  1541.                     }
  1542.                 }
  1543.             }
  1544.         }
  1545.         if ($endDate && $endDate < new \DateTime('now'$timezone)) {
  1546.             $status "expired";
  1547.         }
  1548.         $twentyFourHoursAgo = (new \DateTime('now'$timezone))->modify('-24 hours');
  1549.         if ($endDate && $endDate $twentyFourHoursAgo) {
  1550.             $status "archived";
  1551.         }
  1552.         $response = [
  1553.             "id" => $notification->getId(),
  1554.             "searchEwsIdEn" => $notification->getEwsSearchId("en"),
  1555.             "searchEwsIdAr" => $notification->getEwsSearchId("ar"),
  1556.             "title" => $startDate $startDate->format("dmY") . '-' $notification->getId() : '',
  1557.             "alertType" => !empty($notification->getAlertType()) ? $notification->getAlertType()->getAlertTypeId() : "",
  1558.             "alertTypeAr" => !empty($notification->getAlertType()) ? $notification->getAlertType()->getName("ar") : "",
  1559.             "alertTypeEn" => !empty($notification->getAlertType()) ? ucwords($notification->getAlertType()->getColor()) : "",
  1560.             "fromDate" => $startDate $startDate->format("Y-m-d H:i:s") : "",
  1561.             "toDate" => $endDate $endDate->format("Y-m-d H:i:s") : "",
  1562.             "alertStatusID" => !empty($notification->getAlertStatus()) ? $notification->getAlertStatus()->getAlertStatusId() : "",
  1563.             "alertStatusAr" => !empty($notification->getAlertStatus()) ? $notification->getAlertStatus()->getName("ar") : "",
  1564.             "alertStatusEn" => !empty($notification->getAlertStatus()) ? $notification->getAlertStatus()->getName("en") : "",
  1565.             "alertStatusCategory" => "",
  1566.             "alertHazard" => !empty($notification->getAlertHazard()) ? $this->getAlertHazardArr($notification->getAlertHazard()) : [],
  1567.             "regionID" => !empty($notification->getRegion()) ? $notification->getRegion()->getRegionId() : "",
  1568.             "regionAR" => !empty($notification->getRegion()) ? $notification->getRegion()->getName("ar") : "",
  1569.             "regionEn" => !empty($notification->getRegion()) ? $notification->getRegion()->getName("en") : "",
  1570.             "governorates" => ($notification->getRegion()) ? $this->getGovernorateDetail($notification->getGovernorate()) : [],
  1571.             "ewsOtherLocations" => ($notification->getRegion()) ? $this->getGovernorateDetail($notification->getEwsOtherLocations()) : [],
  1572.             "otherLocationsAr" => $this->getOtherLocationsNames($notification->getEwsOtherLocations(), 'ar'),
  1573.             "otherLocationsEn" => $this->getOtherLocationsNames($notification->getEwsOtherLocations(), 'en'),
  1574.             "tweetID" => "",
  1575.             "enableTwitterNotification" => $notification->getEnableTwitterNotification(),
  1576.             "enableSMSNotification" => $notification->getEnableSMSNotification(),
  1577.             "enableEmailNotification" => $notification->getEnableEmailNotification(),
  1578.             "alertActions" => $this->getAlertActionsByArr($notification->getAlertAction()),
  1579.             "municipalities" => $this->getMunicipalityArr($notification->getMunicipality()),
  1580.             "lastModified" => ($notification->getModificationDate()) ? date("Y-m-d H:i:s"$notification->getModificationDate()) : "",
  1581.             "last_modified_date" => ($notification->getModificationDate()) ? date("Y-m-d"$notification->getModificationDate()) : "",
  1582.             'coordinates' => $notification->getCoordinates(),
  1583.             'message' => $notification->getMessage("en"),
  1584.             "file" => (!empty($notification->getAttachment())) ? API_BASE_URL $notification->getAttachment()->getFullPath() : [],
  1585.             'criteria' => $critetia,
  1586.             'criteriaAr' => $critetiaAr,
  1587.             'created_at' => ($notification->getCreationDate()) ? date("Y-m-d H:i:s"$notification->getCreationDate()) : "",
  1588.             'created_by' => ($notification->getUser()) ? $notification->getUser()->getName() : "",
  1589.             'edited_by' => ($notification->getEditor()) ? $notification->getEditor()->getName() : (($notification->getUser()) ? $notification->getUser()->getName() : ""),
  1590.             'status_en' => ucfirst($status),
  1591.             'status_ar' => $translator->trans(ucfirst($status), [], null'ar'),
  1592.             'previewText' => $notification->getPreviewText() ?? false,
  1593.         ];
  1594.         return $response;
  1595.     }
  1596.     private function getAlertHazardArr($alertHazardArr)
  1597.     {
  1598.         $result = [];
  1599.         if ($alertHazardArr) {
  1600.             foreach ($alertHazardArr as $affect) {
  1601.                 $result[] = [
  1602.                     "pim_id" => $affect->getId(),
  1603.                     "id" => $affect->getAlertHazardId(),
  1604.                     "nameEn" => $affect->getName("en"),
  1605.                     "nameAr" => $affect->getName("ar"),
  1606.                 ];
  1607.             }
  1608.         }
  1609.         return $result;
  1610.     }
  1611.     private function getAlertActionsByArr($alertActions)
  1612.     {
  1613.         $result = [];
  1614.         if ($alertActions) {
  1615.             foreach ($alertActions as $alert) {
  1616.                 $result[] = [
  1617.                     "pim_id" => $alert->getId(),
  1618.                     "id" => $alert->getAlertActionId(),
  1619.                     "descriptionEn" => $alert->getName("en"),
  1620.                     "descriptionAr" => $alert->getName("ar"),
  1621.                 ];
  1622.             }
  1623.         }
  1624.         return $result;
  1625.     }
  1626.     private function getMunicipalityArr($municipalities)
  1627.     {
  1628.         $result = [];
  1629.         if ($municipalities) {
  1630.             foreach ($municipalities as $municipality) {
  1631.                 // p_R($municipality->getName());                
  1632.                 $result[] = [
  1633.                     "id" => $municipality->getMunicipalityId(),
  1634.                     "nameEn" => $municipality->getName("en"),
  1635.                     "nameAr" => $municipality->getName("ar"),
  1636.                     "governate" => $municipality->getGovernorate()->getGovernoteId()
  1637.                 ];
  1638.             }
  1639.         }
  1640.         return $result;
  1641.     }
  1642.     private function getOtherLocationsNames($otherLocations$lang 'ar')
  1643.     {
  1644.         $names = []; // Step 1: Initialize an array to hold the names
  1645.         if ($otherLocations) {
  1646.             foreach ($otherLocations as $otherLocation) {
  1647.                 $names[] = $otherLocation->getName($lang); // Step 2 & 3: Extract and collect names
  1648.             }
  1649.         }
  1650.         if (empty($names)) { // Check if the names array is empty
  1651.             return ''// Return an empty string if there are no names
  1652.         }
  1653.         $namesString implode(', '$names); // Step 4: Convert the array to a comma-separated string
  1654.         return $namesString// Return or use the comma-separated string as needed
  1655.     }
  1656.     public function publishedEwsNotification($notificationId$published$userGroupIds$translator$emailService$templating$logger)
  1657.     {
  1658.         $result = [];
  1659.         $viewNotification DataObject\EwsNotification::getById($notificationIdfalse);
  1660.         if (!$viewNotification) {
  1661.             $viewNotification DataObject\EwsNotification::getById($notificationIdtrue);
  1662.         }
  1663.         if ($published) {
  1664.             $viewNotification->setStatus("active");
  1665.         } else {
  1666.             $viewNotification->setStatus("");
  1667.         }
  1668.         $viewNotification->setPublished($published);
  1669.         //set ews search Id
  1670.         $currentDate = new \DateTime();
  1671.         $formattedDate $currentDate->format('dmY') . '-' $viewNotification->getId();
  1672.         $searchIdEn 'Early Warning System | ' $formattedDate ' | ' ucfirst($viewNotification->getAlertType()?->getColor()) . ' Alert | ' $viewNotification->getWeatherPhenomenon()?->getTitle("en");
  1673.         $searchIdAr $translator->trans('Early Warning System', [], null"ar") . ' | ' $formattedDate ' | ' $translator->trans(ucfirst($viewNotification->getAlertType()?->getColor()) . ' Alert', [], null"ar") . ' | ' $viewNotification->getWeatherPhenomenon()?->getTitle("ar");
  1674.         $viewNotification->setEwsSearchId($searchIdEn"en");
  1675.         $viewNotification->setEwsSearchId($searchIdAr"ar");
  1676.         $viewNotification->save(["versionNote" => "Update"]);
  1677.         $viewNotification->save();
  1678.         // $alert = $this->createNotificationFormat($viewNotification, $translator);
  1679.         if ($published) {
  1680.             // Ensure you use 'php' to execute the command.
  1681.             $jsonUserGroupIds json_encode($userGroupIds);
  1682.             $process = new Process(['php''bin/console''app:send-early-warning-alert-email''--alertId=' $viewNotification->getId(), '--userGroupIds=' $jsonUserGroupIds]);
  1683.             $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
  1684.             try {
  1685.                 $process->mustRun();
  1686.                 $result['success'] = true;
  1687.                 $logger->info("published EwsNotification command executed successfully: " $process->getOutput());
  1688.                 $result['message'] = $process->getOutput();
  1689.             } catch (ProcessFailedException $exception) {
  1690.                 $logger->error("published EwsNotification command failed: " $exception->getMessage());
  1691.                 return ['success' => false'message' => $exception->getMessage()];
  1692.             }
  1693.         }
  1694.         return ["success" => true"message" => $translator->trans("ews_notification_published")];
  1695.     }
  1696.     public function reportEwsNotification($param$translator)
  1697.     {
  1698.         $result = [];
  1699.         $region null;
  1700.         try {
  1701.             $listing = new EwsNotification\Listing();
  1702.             $reportType = isset($param['report_type']) ? $param['report_type'] : null;
  1703.             $regionId = isset($param['region_id']) ? $param['region_id'] : null;
  1704.             if ($regionId) {
  1705.                 $region \Pimcore\Model\DataObject\Region::getByRegionId($regionIdtrue);
  1706.                 if (!$region) {
  1707.                     throw new \Exception("Region not exists");
  1708.                 }
  1709.             }
  1710.             switch ($reportType) {
  1711.                 case 'published_in_week':
  1712.                     $listing->setCondition("o_published = true AND o_creationDate >= " strtotime("-1 week"));
  1713.                     break;
  1714.                 case 'published_in_day':
  1715.                     $listing->setCondition("o_published = true AND o_creationDate >= " strtotime("-1 day"));
  1716.                     break;
  1717.                 case 'published_in_month':
  1718.                     $listing->setCondition("o_published = true AND o_creationDate >= " strtotime("-1 month"));
  1719.                     break;
  1720.                 case 'published_in_year':
  1721.                     $listing->setCondition("o_published = true AND o_creationDate >= " strtotime("-1 year"));
  1722.                     break;
  1723.                 case 'published_in_region':
  1724.                     $listing->setCondition("o_published = true AND region__id = ?", [$region->getId()]);
  1725.                     break;
  1726.                 case 'published_in_draft':
  1727.                     $listing->setCondition("o_published = false");
  1728.                     break;
  1729.                 default:
  1730.                     throw new \Exception("Invalid request");
  1731.                     break;
  1732.             }
  1733.             $result['count'] = $listing->getCount();
  1734.             $notifications $listing->load();
  1735.             if ($notifications) {
  1736.                 foreach ($notifications as $notification) {
  1737.                     $result['data'][] = $this->createNotificationFormat($notification$translator);
  1738.                 }
  1739.             }
  1740.             return $result;
  1741.         } catch (\Exception $ex) {
  1742.             return new \Exception($ex->getMessage());
  1743.         }
  1744.         return $result;
  1745.     }
  1746.     private function sendEmailNotification($users$alert$emailService$templating)
  1747.     {
  1748.         $mailSent null;
  1749.         if ($alert) {
  1750.             $governatesArr $alert['governorates'];
  1751.             $governates = [];
  1752.             if ($governatesArr) {
  1753.                 foreach ($governatesArr as $gov) {
  1754.                     $governates[] = $gov['nameEn'];
  1755.                 }
  1756.             }
  1757.             $data $alert;
  1758.             $data['sender'] = 'National Center for Meteorology';
  1759.             //$subject = $alert['searchEwsIdAr'] ??'Severe Weather Alert - ' . $gov['nameEn'];
  1760.             // $subject = $alert['alertStatusAr'] . ' - ' . $alert['regionAR'];
  1761.             // $subject = 'النظام Ø§Ù„الي Ù„لإنذار Ø§Ù„مبكر :' . ' - ' . $alert['searchEwsIdAr'];
  1762.             $parts explode('|'$alert['searchEwsIdAr']);
  1763.             $excluded implode('|'array_slice($parts1));
  1764.             $subject 'النظام Ø§Ù„الي Ù„لإنذار Ø§Ù„مبكر :'  $excluded;
  1765.             // $html = $templating->render('web2print/_manned_alert_notification_ar.html.twig', $data);
  1766.             //sending an email document (pimcore document)
  1767.             // $emailAlertTemplate = '/email/alert_notification';
  1768.             if ($users) {
  1769.                 foreach ($users as $currentUser) {
  1770.                     if (isset($alert['enableEmailNotification']) && $alert['enableEmailNotification']) {
  1771.                         if ($currentUser->getSendEwsEmail() || is_null($currentUser->getSendEwsEmail())) {
  1772.                             # code...
  1773.                             // $email = $currentUser->getEmail();
  1774.                             // $param = ['user' => $currentUser, 'message' => $html, 'url' => null];
  1775.                             // $mailSent = $emailService->sendMail($param, $email, $emailAlertTemplate, $subject);
  1776.                             // $data['name'] = $user->getName();
  1777.                             // extra param js
  1778.                             $alertObj \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
  1779.                             $alertName $alertObj->getColor() ? $alertObj->getColor() : '';
  1780.                             $alert['user_name'] = $currentUser->getName();
  1781.                             $alert['host'] = API_BASE_URL;
  1782.                             $alert['alertColor'] = $alertName;
  1783.                             $backgroundColor '#fcb82526';
  1784.                             $borderColor '#000000';
  1785.                             $textColor '#000000';
  1786.                             // unsubscribe ews notificaiton token
  1787.                             $tokenURL '';
  1788.                             $token $this->userModel->unSubscribeEwsGenerateToken($currentUser->getEmail());
  1789.                             if (!empty($token)) {
  1790.                                 $tokenURL BASE_URL '/unsubscribe/notification?ews=true&token=' $token;
  1791.                             }
  1792.                             if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
  1793.                                 $alertColorLower strtolower(trim($alert['alertColor']));
  1794.                                 if ($alertColorLower === 'red') {
  1795.                                     $backgroundColor '#f6000017';
  1796.                                     $borderColor '#F60000';
  1797.                                     $textColor '#F60000';
  1798.                                 } elseif ($alertColorLower === 'orange') {
  1799.                                     $backgroundColor '#ff66001f';
  1800.                                     $borderColor '#FF6600';
  1801.                                     $textColor '#FF6600';
  1802.                                 } elseif ($alertColorLower === 'yellow') {
  1803.                                     $backgroundColor '#fcb82526';
  1804.                                     $borderColor '#FCB825';
  1805.                                     $textColor '#FCB825';
  1806.                                 }
  1807.                             }
  1808.                             $purpose EWS_MESSAGE;
  1809.                             $alert['backgroundColor'] = $backgroundColor;
  1810.                             $alert['borderColor'] = $borderColor;
  1811.                             $alert['textColor'] = $textColor;
  1812.                             $alert['tokenURL'] = $tokenURL;
  1813.                             $alert['mannedAlertDatailUrl'] = null;
  1814.                             $html $templating->render('web2print/_manned_alert_notification_ar.html.twig'$alert);
  1815.                             $mailSent $this->c2Service->sendNotificationEmail($_ENV['EWS_MAIL_TEMPLATE'], $alert['id'], $currentUser->getId(), $html$subject$purpose);
  1816.                             // $this->c2Service->sendMannedAlertEmails($html,$currentUser->getId(),$alert['id']);
  1817.                             // $mailSent=$this->c2Service->sendMannedAlertEmails($html,$currentUser->getId(),$alert['id'],$subject);
  1818.                             if ($mailSent) {
  1819.                                 $status "sent";
  1820.                                 $this->saveEmailStatus($currentUser->getEmail(), $currentUser->getName(), $alert$status);
  1821.                             } else {
  1822.                                 $status "not sent";
  1823.                                 $this->saveEmailStatus($currentUser->getEmail(), $currentUser->getName(), $alert$status);
  1824.                             }
  1825.                         }
  1826.                     }
  1827.                 }
  1828.             }
  1829.         }
  1830.         return $mailSent;
  1831.     }
  1832.     private function sendExcelEmailNotification($userGroupIds$alert$emailService$templating)
  1833.     {
  1834.         $mailSent null;
  1835.         if ($alert) {
  1836.             $governatesArr $alert['governorates'];
  1837.             $governates = [];
  1838.             if ($governatesArr) {
  1839.                 foreach ($governatesArr as $gov) {
  1840.                     $governates[] = $gov['nameEn'];
  1841.                 }
  1842.             }
  1843.             $data $alert;
  1844.             $data['sender'] = 'National Center for Meteorology';
  1845.             // $subject = $alert['searchEwsIdAr'] ??'Severe Weather Alert - ' . $gov['nameEn'];
  1846.             //$subject = $alert['alertStatusAr'] . ' - ' . $alert['regionAR'];
  1847.             // $subject = 'النظام Ø§Ù„الي Ù„لإنذار Ø§Ù„مبكر :' . ' - ' . $alert['searchEwsIdAr'];
  1848.             $parts explode('|'$alert['searchEwsIdAr']);
  1849.             $excluded implode('|'array_slice($parts1));
  1850.             $subject 'النظام Ø§Ù„الي Ù„لإنذار Ø§Ù„مبكر :'  $excluded;
  1851.             if ($userGroupIds) {
  1852.                 foreach ($userGroupIds as $userGroupId) {
  1853.                     if ($userGroupId) {
  1854.                         $userGroup \Pimcore\Model\DataObject\EwsAndReportUserGroup::getById($userGroupIdtrue);
  1855.                         if ($userGroup instanceof \Pimcore\Model\DataObject\EwsAndReportUserGroup) {
  1856.                             foreach (json_decode($userGroup->getJsonData()) as $currentUser) {
  1857.                                 if (isset($currentUser->firstName) && isset($currentUser->lastName) && isset($currentUser->email)) {
  1858.                                     // extra param js
  1859.                                     $alertObj \Pimcore\Model\DataObject\AlertType::getByAlertTypeId($alert['alertType'], true);
  1860.                                     $alertName $alertObj->getColor() ? $alertObj->getColor() : '';
  1861.                                     $alert['user_name'] = $currentUser->firstName ' ' $currentUser->lastName;
  1862.                                     $alert['host'] = API_BASE_URL;
  1863.                                     $alert['alertColor'] = $alertName;
  1864.                                     $backgroundColor '#fcb82526';
  1865.                                     $borderColor '#000000';
  1866.                                     $textColor '#000000';
  1867.                                     if (isset($alert['alertColor']) && !empty(trim($alert['alertColor']))) {
  1868.                                         $alertColorLower strtolower(trim($alert['alertColor']));
  1869.                                         if ($alertColorLower === 'red') {
  1870.                                             $backgroundColor '#f6000017';
  1871.                                             $borderColor '#F60000';
  1872.                                             $textColor '#F60000';
  1873.                                         } elseif ($alertColorLower === 'orange') {
  1874.                                             $backgroundColor '#ff66001f';
  1875.                                             $borderColor '#FF6600';
  1876.                                             $textColor '#FF6600';
  1877.                                         } elseif ($alertColorLower === 'yellow') {
  1878.                                             $backgroundColor '#fcb82526';
  1879.                                             $borderColor '#FCB825';
  1880.                                             $textColor '#FCB825';
  1881.                                         }
  1882.                                     }
  1883.                                     $alert['backgroundColor'] = $backgroundColor;
  1884.                                     $alert['borderColor'] = $borderColor;
  1885.                                     $alert['textColor'] = $textColor;
  1886.                                     $alert['tokenURL'] = null;
  1887.                                     $alert['mannedAlertDatailUrl'] = null;
  1888.                                     $html $templating->render('web2print/_manned_alert_notification_ar.html.twig'$alert);
  1889.                                     // $email = $currentUser->email;
  1890.                                     // $param = ['user' => $currentUser, 'message' => $html, 'url' => null];
  1891.                                     // $mailSent = $emailService->sendMail($param, "abdul.muqeet@centric.ae", '/email/alert_notification', $subject);
  1892.                                     $purpose EWS_MESSAGE;
  1893.                                     $mailSent $this->c2Service->sendDefaultEmail($_ENV['EWS_MAIL_TEMPLATE'], $alert['id'], $currentUser->email$html$subject$purpose);
  1894.                                     if ($mailSent) {
  1895.                                         $status "sent";
  1896.                                         $this->saveEmailStatus($currentUser->email$currentUser->firstName ' ' $currentUser->lastName$alert$status);
  1897.                                     } else {
  1898.                                         $status "not sent";
  1899.                                         $this->saveEmailStatus($currentUser->email$currentUser->firstName ' ' $currentUser->lastName$alert$status);
  1900.                                     }
  1901.                                 }
  1902.                             }
  1903.                         }
  1904.                     }
  1905.                 }
  1906.             }
  1907.         }
  1908.         return $mailSent;
  1909.     }
  1910.     private function saveEmailStatus($userEmail$userName$alert$emailStatus)
  1911.     {
  1912.         // Get all governorates names in string seprated by ,
  1913.         $nameEnArray array_column($alert["governorates"], "nameEn");
  1914.         $nameEnString implode(", "$nameEnArray);
  1915.         $nameArArray array_column($alert["governorates"], "nameAr");
  1916.         $nameArString implode(", "$nameArArray);
  1917.         $ewsEmailStatus = new FetchSentEwsEmail();
  1918.         $ewsEmailStatus->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("/Other/FetchSentEwsEmail/"));
  1919.         $ewsEmailStatus->setKey(\Pimcore\Model\Element\Service::getValidKey($userEmail "-" strtotime("now") . "-" rand(110000), 'object'));
  1920.         $ewsEmailStatus->setEwsId($alert['id']);
  1921.         $ewsEmailStatus->setUserName($userName);
  1922.         $ewsEmailStatus->setEmail($userEmail);
  1923.         //$ewsEmailStatus->setLocationName($locationName);
  1924.         $ewsEmailStatus->setAlertType($alert['alertTypeEn'], 'en');
  1925.         $ewsEmailStatus->setAlertType($alert['alertTypeAr'], 'ar');
  1926.         $ewsEmailStatus->setAlertStatus($alert['alertStatusEn'], 'en');
  1927.         $ewsEmailStatus->setAlertStatus($alert['alertStatusAr'], 'ar');
  1928.         $ewsEmailStatus->setRegionName($alert['regionEn'], 'en');
  1929.         $ewsEmailStatus->setRegionName($alert['regionAR'], 'ar');
  1930.         $ewsEmailStatus->setGovernorateNames($nameEnString'en');
  1931.         $ewsEmailStatus->setGovernorateNames($nameArString'ar');
  1932.         $ewsEmailStatus->setStatus($emailStatus);
  1933.         $ewsEmailStatus->setPublished(true);
  1934.         $ewsEmailStatus->save();
  1935.         return $ewsEmailStatus;
  1936.     }
  1937.     public function getEwsNotificationEmailStatus($params$paginator$translator)
  1938.     {
  1939.         $result = [];
  1940.         try {
  1941.             $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  1942.             $page = isset($params['page']) ? $params['page'] : 1;
  1943.             $notificationId $params["id"] ? $params["id"] : null;
  1944.             $listing = new FetchSentEwsEmail\Listing();
  1945.             $listing->setCondition("ewsId = ? ", [$notificationId]);
  1946.             $paginator $paginator->paginate(
  1947.                 $listing,
  1948.                 $page,
  1949.                 $pageSize
  1950.             );
  1951.             if ($paginator->count() > 0) {
  1952.                 foreach ($paginator as $EwsNotificationEmail) {
  1953.                     $result[] = [
  1954.                         "ewsId" => $EwsNotificationEmail->getEwsId(),
  1955.                         "userName" => $EwsNotificationEmail->getUserName(),
  1956.                         "Email" => $EwsNotificationEmail->getEmail(),
  1957.                         "locationName" => $EwsNotificationEmail->getLocationName(),
  1958.                         "alertType" => $EwsNotificationEmail->getAlertType('en'),
  1959.                         "alertTypeAr" => $EwsNotificationEmail->getAlertType('ar'),
  1960.                         "alertStatus" => $EwsNotificationEmail->getAlertStatus('en'),
  1961.                         "alertStatusAr" => $EwsNotificationEmail->getAlertStatus('ar'),
  1962.                         "regionName" => $EwsNotificationEmail->getRegionName('en'),
  1963.                         "regionNameAr" => $EwsNotificationEmail->getRegionName('ar'),
  1964.                         "governorateNames" => explode(","$EwsNotificationEmail->getGovernorateNames('en')),
  1965.                         "governorateNamesAr" => explode(","$EwsNotificationEmail->getGovernorateNames('ar')),
  1966.                         "emailStatus" => $EwsNotificationEmail->getStatus(),
  1967.                         "emailStatusAr" => $translator->trans($EwsNotificationEmail->getStatus(), [], null"ar"),
  1968.                     ];
  1969.                 }
  1970.             }
  1971.             return ["success" => TRUE"data" => $result"paginationVariables" => $paginator->getPaginationData()];
  1972.         } catch (\Exception $ex) {
  1973.             return new \Exception($ex->getMessage());
  1974.         }
  1975.         return $result;
  1976.     }
  1977.     public function getOtherLocations()
  1978.     {
  1979.         $response = [];
  1980.         $otherLocations = new DataObject\OtherLocation\Listing();
  1981.         $otherLocations $otherLocations->load();
  1982.         if ($otherLocations) {
  1983.             foreach ($otherLocations as $otherLocation) {
  1984.                 $response[] = [
  1985.                     "id" => $otherLocation->getOtherLocationId(),
  1986.                     "nameEn" => $otherLocation->getName('en'),
  1987.                     "nameAr" => $otherLocation->getName('ar')
  1988.                 ];
  1989.             }
  1990.         }
  1991.         return ["success" => true"data" => $response];
  1992.     }
  1993.     public function getEwsNotificationByByRegionName($regionName)
  1994.     {
  1995.         $db Db::get();
  1996.         $selectedLocalities $db->fetchAll("SELECT * FROM `object_collection_AddressComponents_location` WHERE (`addressKey` = 'locality' || `addressKey` = 'administrative_area_level_1') and (TRIM(REPLACE(`addressValue`,'Province','')) = '" $regionName "')");
  1997.         return $selectedLocalities;
  1998.     }
  1999.     public function ewsAnalytics($params$connection$lang): array
  2000.     {
  2001.         $response = [];
  2002.         $status = isset($params['status']) ? $params['status'] : "";
  2003.         $isManned null;
  2004.         if (isset($params['isManned']) && $params['isManned'] == true) {
  2005.             $isManned true;
  2006.         } elseif (isset($params['isManned']) && $params['isManned'] == false) {
  2007.             $isManned false;
  2008.         }
  2009.         if (isset($params['region']) && !empty($params['region'])) {
  2010.             $region Region::getByRegionId($params['region'], true);
  2011.             $response[] = $this->ewsAnalyticsCount($region$status$connection$lang$isManned);
  2012.         } else {
  2013.             $regions = new Region\Listing();
  2014.             foreach ($regions as $region) {
  2015.                 $response[] = $this->ewsAnalyticsCount($region$status$connection$lang$isManned);
  2016.             }
  2017.         }
  2018.         return $response;
  2019.     }
  2020.     public function ewsAnalyticsCount($region$status$connection$lang$isManned)
  2021.     {
  2022.         $regionNameEn $region->getName("en");
  2023.         $regionNameAr $region->getName("ar");
  2024.         $statuses = ["active""archived""expired"];
  2025.         $count = ['regionEn' => $regionNameEn"regionAr" => $regionNameAr];
  2026.         if (in_array($status$statuses)) {
  2027.             $count[$status] = $this->getStatusData($region$status$connection$isManned);
  2028.         } else {
  2029.             foreach ($statuses as $s) {
  2030.                 $count[$s] = $this->getStatusData($region$s$connection$isManned);
  2031.             }
  2032.         }
  2033.         return $count;
  2034.     }
  2035.     public function getStatusData($region$status$connection$isManned)
  2036.     {
  2037.         $totalNotifications $this->statusCount($region$status$isManned);
  2038.         $alertTypeCount $this->alertCount($region$status$connection$isManned);
  2039.         return [
  2040.             'total_notifications' => $totalNotifications,
  2041.             'alert_type_count' => $alertTypeCount,
  2042.         ];
  2043.     }
  2044.     public function alertCount($region$status$connection$isManned)
  2045.     {
  2046.         $currentTimestamp time(); // Current UNIX timestamp
  2047.         $twentyFourHoursAgoTimestamp strtotime('-24 hours'); // 24 hours ago timestamp
  2048.         $claim_report_sql $connection->createQueryBuilder();
  2049.         $claim_report_sql
  2050.             ->select('oa.Color AS color''COUNT(oq.oo_id) AS count')
  2051.             ->from('object_ews_notification''oq')
  2052.             ->join('oq''object_query_alert_type''oa''oq.alertType__id = oa.oo_id')
  2053.             ->andWhere('oq.region__id = :regionId')
  2054.             ->andWhere('oq.status = :status');
  2055.         if ($isManned !== null && $isManned == true) {
  2056.             $claim_report_sql->andWhere('oq.isManned = 1');
  2057.         } elseif ($isManned !== null && $isManned == false) {
  2058.             $claim_report_sql->andWhere('oq.isManned = 0');
  2059.         }
  2060.         $claim_report_sql->andWhere('oq.o_published = 1'); // added new line
  2061.         // Initialize parameters array
  2062.         $params = [
  2063.             'regionId' => $region->getId(),
  2064.             'status' => $status,
  2065.         ];
  2066.         // Add conditions based on status
  2067.         if ($status == "active") {
  2068.             $claim_report_sql->andWhere('oq.endDate > :currentTimestamp');
  2069.             $params['currentTimestamp'] = $currentTimestamp;
  2070.         } else if ($status == "expired") {
  2071.             $claim_report_sql->andWhere('oq.endDate < :currentTimestamp AND oq.endDate > :twentyFourHoursAgoTimestamp');
  2072.             $params['currentTimestamp'] = $currentTimestamp;
  2073.             $params['twentyFourHoursAgoTimestamp'] = $twentyFourHoursAgoTimestamp;
  2074.         } else if ($status == "archived") {
  2075.             $claim_report_sql->andWhere('oq.endDate < :twentyFourHoursAgoTimestamp');
  2076.             $params['twentyFourHoursAgoTimestamp'] = $twentyFourHoursAgoTimestamp;
  2077.         }
  2078.         // Set all parameters at once
  2079.         $claim_report_sql->setParameters($params);
  2080.         $claim_report_sql->groupBy('color');
  2081.         $claimReportstmt $claim_report_sql->execute();
  2082.         $results $claimReportstmt->fetchAllAssociative();
  2083.         // Fetch all possible colors
  2084.         $alertTypes = new AlertType\Listing();
  2085.         $allColors = [];
  2086.         foreach ($alertTypes as $alertType) {
  2087.             if ($alertType) {
  2088.                 $allColors[] = $alertType->getColor();
  2089.             }
  2090.         }
  2091.         if (empty($allColors)) {
  2092.             $allColors = ["yellow""orange""red"];
  2093.         }
  2094.         // Create an associative array to store counts by color
  2095.         $countsByColor = [];
  2096.         foreach ($results as $result) {
  2097.             $countsByColor[$result['color']] = $result['count'];
  2098.         }
  2099.         // Merge counts for existing colors with counts for all colors, including those with count 0
  2100.         $finalResult = [];
  2101.         foreach ($allColors as $color) {
  2102.             $finalResult[] = [
  2103.                 "color" => $color,
  2104.                 "count" => isset($countsByColor[$color]) ? $countsByColor[$color] : 0
  2105.             ];
  2106.         }
  2107.         return $finalResult;
  2108.     }
  2109.     public function statusCount($region$status$isManned)
  2110.     {
  2111.         $notifications = new EwsNotification\Listing();
  2112.         $currentTimestamp time(); // Get the current UNIX timestamp
  2113.         $twentyFourHoursAgoTimestamp strtotime('-24 hours'); // 24 hours ago timestamp
  2114.         $conditions "region__id = ? AND status = ?";
  2115.         $params = [$region->getId(), $status];
  2116.         if ($status == "active") {
  2117.             $conditions .= " AND endDate > ?";
  2118.             $params[] = $currentTimestamp;
  2119.         } else if ($status == "expired") {
  2120.             $conditions .= " AND endDate < ? AND endDate > ?";
  2121.             $params[] = $currentTimestamp;
  2122.             $params[] = $twentyFourHoursAgoTimestamp;
  2123.         } else if ($status == "archived") {
  2124.             $conditions .= " AND endDate < ?";
  2125.             $params[] = $twentyFourHoursAgoTimestamp;
  2126.         }
  2127.         $notifications->addConditionParam($conditions$params);
  2128.         // Add condition for manned notifications
  2129.         if ($isManned !== null) {
  2130.             $notifications->addConditionParam("isManned = ?", [$isManned]);
  2131.         }
  2132.         return $notifications->count();
  2133.     }
  2134.     public function searchEwsNotification($params$lang$paginator$translator): array
  2135.     {
  2136.         $response = [];
  2137.         $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  2138.         $page = isset($params['page']) ? $params['page'] : 1;
  2139.         $notificationList = new DataObject\EwsNotification\Listing();
  2140.         $notificationList->setUnpublished(true);
  2141.         $notificationList->filterByPublished(true);
  2142.         if (isset($params['isManned']) && $params['isManned'] == true) {
  2143.             $notificationList->addConditionParam("isManned = 1");
  2144.         } elseif (isset($params['isManned']) && $params['isManned'] == false) {
  2145.             $notificationList->addConditionParam("isManned = 0");
  2146.         }
  2147.         if (isset($params['id']) && !empty($params['id'])) {
  2148.             $idz $params['id'];
  2149.             $notificationList->addConditionParam("oo_id IN (?)", [$idz]);
  2150.         }
  2151.         if (isset($params['alertAction']) && !empty($params['alertAction'])) {
  2152.             $alertActionIds = [];
  2153.             $alertActionList = new DataObject\AlertAction\Listing();
  2154.             $alertActionList->addConditionParam("alertActionId IN (?)", [$params['alertAction']]);
  2155.             foreach ($alertActionList as $alertAction) {
  2156.                 $alertActionIds[] = $alertAction->getId();
  2157.             }
  2158.             $alertActionids implode(","$alertActionIds);
  2159.             $notificationList->addConditionParam("alertAction REGEXP CONCAT('(^|,)(', REPLACE('$alertActionids',',', '|'), ')(,|$)')");
  2160.         }
  2161.         if (isset($params['alertType']) && !empty($params['alertType'])) {
  2162.             $alertTypeIds = [];
  2163.             $alertTypeList = new DataObject\AlertType\Listing();
  2164.             $alertTypeList->addConditionParam("alertTypeId IN (?)", [$params['alertType']]);
  2165.             foreach ($alertTypeList as $alertType) {
  2166.                 $alertTypeIds[] = $alertType->getId();
  2167.             }
  2168.             $notificationList->addConditionParam("alertType__id IN (?)", [$alertTypeIds]);
  2169.         }
  2170.         // if (isset($params['phenomena']) && !empty($params['phenomena'])) {
  2171.         //     $phenomenaIds = [];
  2172.         //     $phenomenaList = new DataObject\PhenomenaList\Listing();
  2173.         //     $phenomenaList->addConditionParam("phenomenalistid IN (?)", [$params['phenomena']]);
  2174.         //     foreach ($phenomenaList as $phenomena) {
  2175.         //         $phenomenaIds[] = $phenomena->getId();
  2176.         //     }
  2177.         //     $notificationList->addConditionParam("weatherPhenomenon__id IN (?)", [$phenomenaIds]);
  2178.         // }
  2179.         if (!empty($params['phenomena'])) {
  2180.             $alertStatusSql null;
  2181.             foreach ($params['phenomena'] as $alertStatus) {
  2182.                 $alertStatus \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($alertStatustrue);
  2183.                 if ($alertStatus) {
  2184.                     $alertStatusSql .= "alertStatus__id = " $alertStatus->getId() . " OR ";
  2185.                 }
  2186.             }
  2187.             $notificationList->addConditionParam("(" substr($alertStatusSql0, -3) . ")");
  2188.         }
  2189.         if (isset($params['region']) && !empty($params['region'])) {
  2190.             $regionIds = [];
  2191.             $regionList = new DataObject\Region\Listing();
  2192.             $regionList->addConditionParam("regionId IN (?)", [$params['region']]);
  2193.             foreach ($regionList as $region) {
  2194.                 $regionIds[] = $region->getId();
  2195.             }
  2196.             $notificationList->addConditionParam("region__id IN (?)", [$regionIds]);
  2197.         }
  2198.         if (isset($params['governate']) && !empty($params['governate'])) {
  2199.             $governatesIds = [];
  2200.             $governateList = new DataObject\Governorate\Listing();
  2201.             $governateList->addConditionParam("governoteId IN (?)", [$params['governate']]);
  2202.             foreach ($governateList as $governate) {
  2203.                 $governatesIds[] = $governate->getId();
  2204.             }
  2205.             $governatesIds implode(","$governatesIds);
  2206.             $notificationList->addConditionParam("governorate REGEXP CONCAT('(^|,)(', REPLACE('$governatesIds',',', '|'), ')(,|$)')");
  2207.         }
  2208.         if (isset($params['status'][0]) && !empty($params['status'][0])) {
  2209.             $currentTimestamp time();
  2210.             $twentyFourHoursAgo strtotime('-24 hours');
  2211.             if ($params['status'][0] == "active" && (!isset($params['status'][1]) || empty($params['status'][1]))) {
  2212.                 // Filter notifications with an end date in the future or equal to current time
  2213.                 $notificationList->filterByEndDate($currentTimestamp">=");
  2214.             } else if ($params['status'][0] == "expired" && (!isset($params['status'][1]) || empty($params['status'][1]))) {
  2215.                 // Filter notifications with an end date in the past, but not older than 24 hours
  2216.                 $notificationList->filterByEndDate($currentTimestamp"<");
  2217.                 $notificationList->filterByEndDate($twentyFourHoursAgo">=");
  2218.             } else if ($params['status'][0] == "archived" && (!isset($params['status'][1]) || empty($params['status'][1]))) {
  2219.                 // Filter notifications with an end date older than 24 hours
  2220.                 $notificationList->filterByEndDate($twentyFourHoursAgo"<");
  2221.             } else if (isset($params['status'][1]) && !empty($params['status'][1])) {
  2222.                 if (($params['status'][0] == "active" && $params['status'][1] == "expired") || ($params['status'][0] == "expired" && $params['status'][1] == "active")) {
  2223.                     // Filter notifications that are either active or expired
  2224.                     $notificationList->filterByEndDate($currentTimestamp">=");
  2225.                     $notificationList->filterByEndDate($twentyFourHoursAgo">=");
  2226.                 }
  2227.             }
  2228.         } else {
  2229.             // If no status is provided, return 0 records
  2230.             $notificationList->addConditionParam("1 = 0");
  2231.         }
  2232.         $notificationList->setLocale($lang);
  2233.         if (isset($params['searchId']) && !empty($params['searchId'])) {
  2234.             $notificationList->addConditionParam(
  2235.                 "(ewsSearchId LIKE ?)",
  2236.                 [
  2237.                     '%' $params['searchId'] . '%'
  2238.                 ]
  2239.             );
  2240.         }
  2241.         if (isset($params['alertHazard']) && !empty($params['alertHazard'])) {
  2242.             $alertHazardIds = [];
  2243.             $alertHazardList = new DataObject\AlertHazard\Listing();
  2244.             $alertHazardList->addConditionParam("alertHazardId IN (?)", [$params['alertHazard']]);
  2245.             foreach ($alertHazardList as $alertHazard) {
  2246.                 $alertHazardIds[] = $alertHazard->getId();
  2247.             }
  2248.             $alertHazardIds implode(","$alertHazardIds);
  2249.             $notificationList->addConditionParam("alertHazard REGEXP CONCAT('(^|,)(', REPLACE('$alertHazardIds',',', '|'), ')(,|$)')");
  2250.         }
  2251.         if (isset($params['municipality']) && !empty($params['municipality'])) {
  2252.             $municipalityIds = [];
  2253.             $municipalityList = new DataObject\Municipality\Listing();
  2254.             $municipalityList->addConditionParam("municipalityid IN (?)", [$params['municipality']]);
  2255.             foreach ($municipalityList as $municipality) {
  2256.                 $municipalityIds[] = $municipality->getId();
  2257.             }
  2258.             $municipalityIds implode(","$municipalityIds);
  2259.             $notificationList->addConditionParam("municipality REGEXP CONCAT('(^|,)(', REPLACE('$municipalityIds',',', '|'), ')(,|$)')");
  2260.         }
  2261.         if (isset($params['startDate']) && !empty($params['startDate'])) {
  2262.             $notificationList->filterByStartDate(strtotime($params['startDate']), ">=");
  2263.         }
  2264.         if (isset($params['endDate']) && !empty($params['endDate'])) {
  2265.             $notificationList->filterByEndDate(strtotime($params['endDate']), "<=");
  2266.         }
  2267.         if (isset($params['fromDate']) && isset($params['toDate']) && !empty($params['fromDate']) && !empty($params['toDate'])) {
  2268.             $fromDate = new \DateTime($params['fromDate']);
  2269.             $toDate = new \DateTime($params['toDate']);
  2270.             // Ensure the dates are in the correct format
  2271.             $fromDateStr strtotime($fromDate->format('Y-m-d H:i:s'));
  2272.             $toDateStr strtotime($toDate->format('Y-m-d') . ' 23:59:59');
  2273.             $notificationList->addConditionParam(
  2274.                 "(o_creationDate >= ? AND o_creationDate <= ?)",
  2275.                 [$fromDateStr$toDateStr]
  2276.             );
  2277.         }
  2278.         $notifications $notificationList->load();
  2279.         $sortedData = [];
  2280.         foreach ($notifications as $notification) {
  2281.             $regionEn $notification->getRegion()->getName("en"); // Assuming getRegion() is available
  2282.             $startDate $notification->getStartDate()->format('Y-m-d H:i:s'); // Assuming getStartDate() returns a \DateTime
  2283.             $endDate $notification->getEndDate()->format('Y-m-d H:i:s');
  2284.             $alertStatusEn $notification->getWeatherPhenomenon()?->getTitle("en");
  2285.             $creationDate $notification->getCreationDate(); // Assuming getCreationDate() returns a \DateTime
  2286.             $searchIdEn $notification->getEwsSearchId("en");
  2287.             $searchIdAr $notification->getEwsSearchId("ar");
  2288.             $title $notification->getStartDate() ? $notification->getStartDate()->format("dmY") . '-' $notification->getId() : '';
  2289.             $alertTypeEn $notification->getAlertType()?->getName("en");
  2290.             $fromDate $notification->getStartDate()->format('Y-m-d H:i:s');
  2291.             $toDate $notification->getEndDate()->format('Y-m-d H:i:s');
  2292.             $region $regionEn;
  2293.             $created_at $notification->getCreationDate();
  2294.             $alertStatus $alertStatusEn;
  2295.             $sortedData[] = [
  2296.                 'notification' => $notification,
  2297.                 'regionName' => $regionEn,
  2298.                 'alertStatus' => $alertStatusEn,
  2299.                 'startDate' => $startDate,
  2300.                 'endDate' => $endDate,
  2301.                 'creationDate' => $creationDate// Add creation date to sorting criteria
  2302.                 'searchIdEn' => $searchIdEn,
  2303.                 'searchIdAr' => $searchIdAr,
  2304.                 'title' => $title,
  2305.                 'alertType' => $alertTypeEn,
  2306.                 'fromDate' => $fromDate,
  2307.                 'toDate' => $toDate,
  2308.                 'region' => $region,
  2309.                 'created_at' => $created_at,
  2310.                 'alertStatus' => $alertStatus
  2311.             ];
  2312.         }
  2313.         // Define default sort orders and detect if any sort parameter is provided
  2314.         $sortOrderRegion $params['sortByRegion'] ?? null;
  2315.         $sortOrderStartDate $params['sortByStartDate'] ?? null;
  2316.         $sortOrderEndDate $params['sortByEndDate'] ?? null;
  2317.         $sortOrderAlertStatus $params['sortByAlertStatus'] ?? null;
  2318.         $sortOrderSearchIdEn $params['sortBySearchIdEn'] ?? null;
  2319.         $sortOrderSearchIdAr $params['sortBySearchIdAr'] ?? null;
  2320.         $sortOrderCreatedAt $params['sortByCreated'] ?? null;
  2321.         $sortOrderTitle $params['sortByTitle'] ?? null;
  2322.         $sortOrderAlertType $params['sortByAlertType'] ?? null;
  2323.         $sortOrderFromDate $params['sortByFromDate'] ?? null;
  2324.         $sortOrderToDate $params['sortByToDate'] ?? null;
  2325.         $sortOrderRegionNew $params['sortByRegionNew'] ?? null;
  2326.         $sortOrderCreatedAtNew $params['sortByCreatedAt'] ?? null;
  2327.         $sortOrderAlertStatusNew $params['sortByAlertStatusNew'] ?? null;
  2328.         
  2329.         // Support for orderKey and order parameters (NEW - clean approach)
  2330.         $orderKey $params['orderKey'] ?? null;
  2331.         $order $params['order'] ?? 'asc';
  2332.         
  2333.         // Simple mapping for new fields
  2334.         $newFieldMapping = [
  2335.             'title' => 'sortOrderTitle',
  2336.             'alertType' => 'sortOrderAlertType',
  2337.             'fromDate' => 'sortOrderFromDate'
  2338.             'toDate' => 'sortOrderToDate',
  2339.             'region' => 'sortOrderRegionNew',
  2340.             'created_at' => 'sortOrderCreatedAtNew',
  2341.             'alertStatus' => 'sortOrderAlertStatusNew'
  2342.         ];
  2343.         
  2344.         // Set the appropriate sort order variable
  2345.         if ($orderKey && isset($newFieldMapping[$orderKey])) {
  2346.             $variableName $newFieldMapping[$orderKey];
  2347.             $$variableName $order;
  2348.         }
  2349.         
  2350.         // Check if any sort parameter is provided (OLD + NEW)
  2351.         $anySortParamProvided $sortOrderRegion || $sortOrderStartDate || $sortOrderEndDate || $sortOrderAlertStatus || $sortOrderSearchIdEn || $sortOrderSearchIdAr || $sortOrderTitle || $sortOrderAlertType || $sortOrderFromDate || $sortOrderToDate || $sortOrderRegionNew || $sortOrderCreatedAtNew || $sortOrderAlertStatusNew;
  2352.         usort($sortedData, function ($a$b) use ($sortOrderRegion$sortOrderStartDate$sortOrderEndDate$sortOrderAlertStatus$sortOrderSearchIdEn$sortOrderSearchIdAr$sortOrderCreatedAt$sortOrderTitle$sortOrderAlertType$sortOrderFromDate$sortOrderToDate$sortOrderRegionNew$sortOrderCreatedAtNew$sortOrderAlertStatusNew$anySortParamProvided) {
  2353.             if (!$anySortParamProvided || $sortOrderCreatedAt) {
  2354.                 if ($sortOrderCreatedAt == null) {
  2355.                     $sortOrderCreatedAt "desc";
  2356.                 }
  2357.                 // Default to sorting by creation date if no sort parameter is provided
  2358.                 $compareCreatedAt strcmp($a['creationDate'], $b['creationDate']) * ($sortOrderCreatedAt === 'desc' ? -1);
  2359.                 if ($compareCreatedAt !== 0) return $compareCreatedAt// Assuming 'asc' as default sort order for creation date
  2360.             }
  2361.             // Else, sort based on the provided parameters
  2362.             if ($sortOrderRegion) {
  2363.                 $compareRegion strcmp($a['regionName'], $b['regionName']) * ($sortOrderRegion === 'desc' ? -1);
  2364.                 if ($compareRegion !== 0) return $compareRegion;
  2365.             }
  2366.             if ($sortOrderSearchIdEn) {
  2367.                 $compareSearchIdEn strcmp($a['searchIdEn'], $b['searchIdEn']) * ($sortOrderSearchIdEn === 'desc' ? -1);
  2368.                 if ($compareSearchIdEn !== 0) return $compareSearchIdEn;
  2369.             }
  2370.             if ($sortOrderSearchIdAr) {
  2371.                 $compareSearchIdAr strcmp($a['searchIdAr'], $b['searchIdAr']) * ($sortOrderSearchIdAr === 'desc' ? -1);
  2372.                 if ($compareSearchIdAr !== 0) return $compareSearchIdAr;
  2373.             }
  2374.             if ($sortOrderAlertStatus) {
  2375.                 $compareAlertStatus strcmp($a['alertStatus'], $b['alertStatus']) * ($sortOrderAlertStatus === 'desc' ? -1);
  2376.                 if ($compareAlertStatus !== 0) return $compareAlertStatus;
  2377.             }
  2378.             if ($sortOrderStartDate) {
  2379.                 $compareStartDate strcmp($a['startDate'], $b['startDate']) * ($sortOrderStartDate === 'desc' ? -1);
  2380.                 if ($compareStartDate !== 0) return $compareStartDate;
  2381.             }
  2382.             if ($sortOrderEndDate) {
  2383.                 return strcmp($a['endDate'], $b['endDate']) * ($sortOrderEndDate === 'desc' ? -1);
  2384.             }
  2385.             
  2386.             // New sorting fields (ADDED - keeps old functionality)
  2387.             if ($sortOrderTitle) {
  2388.                 $compareTitle strcmp($a['title'], $b['title']) * ($sortOrderTitle === 'desc' ? -1);
  2389.                 if ($compareTitle !== 0) return $compareTitle;
  2390.             }
  2391.             if ($sortOrderAlertType) {
  2392.                 $compareAlertType strcmp($a['alertType'], $b['alertType']) * ($sortOrderAlertType === 'desc' ? -1);
  2393.                 if ($compareAlertType !== 0) return $compareAlertType;
  2394.             }
  2395.             if ($sortOrderFromDate) {
  2396.                 $compareFromDate strcmp($a['fromDate'], $b['fromDate']) * ($sortOrderFromDate === 'desc' ? -1);
  2397.                 if ($compareFromDate !== 0) return $compareFromDate;
  2398.             }
  2399.             if ($sortOrderToDate) {
  2400.                 $compareToDate strcmp($a['toDate'], $b['toDate']) * ($sortOrderToDate === 'desc' ? -1);
  2401.                 if ($compareToDate !== 0) return $compareToDate;
  2402.             }
  2403.             if ($sortOrderRegionNew) {
  2404.                 $compareRegionNew strcmp($a['region'], $b['region']) * ($sortOrderRegionNew === 'desc' ? -1);
  2405.                 if ($compareRegionNew !== 0) return $compareRegionNew;
  2406.             }
  2407.             if ($sortOrderCreatedAtNew) {
  2408.                 $compareCreatedAtNew strcmp($a['created_at'], $b['created_at']) * ($sortOrderCreatedAtNew === 'desc' ? -1);
  2409.                 if ($compareCreatedAtNew !== 0) return $compareCreatedAtNew;
  2410.             }
  2411.             if ($sortOrderAlertStatusNew) {
  2412.                 $compareAlertStatusNew strcmp($a['alertStatus'], $b['alertStatus']) * ($sortOrderAlertStatusNew === 'desc' ? -1);
  2413.                 if ($compareAlertStatusNew !== 0) return $compareAlertStatusNew;
  2414.             }
  2415.             
  2416.             // If all provided parameters are equal, or no specific sort orders are provided, default to creation date
  2417.             return ($b['creationDate'] ?? 0) - ($a['creationDate'] ?? 0);
  2418.         });
  2419.         $sortedNotifications array_map(function ($item) {
  2420.             return $item['notification'];
  2421.         }, $sortedData);
  2422.         if (isset($params['dashboard']) && !empty($params['dashboard'] && $params['dashboard'] == 'dashboard')) {
  2423.             return ["data" => $notificationList];
  2424.         }
  2425.         // Extract the sorted notifications
  2426.        
  2427.         if ($paginator == null) {
  2428.             // if ($sortedNotifications->count()) {
  2429.             foreach ($sortedNotifications as $notification) {
  2430.                 // if($notification->getPublished())
  2431.                 $response[] = $this->createNotificationFormat($notification$translator);
  2432.             }
  2433.             // }
  2434.             return ["success" => TRUE"data" => $response];
  2435.         }
  2436.         $paginator $paginator->paginate(
  2437.             $sortedNotifications,
  2438.             $page,
  2439.             $pageSize
  2440.         );
  2441.         // if ($sortedNotifications->count()) {
  2442.         foreach ($paginator as $notification) {
  2443.             // if($notification->getPublished())
  2444.             $response[] = $this->createNotificationFormat($notification$translator);
  2445.         }
  2446.         // }
  2447.         return ["data" => $response"paginationVariables" => $paginator->getPaginationData()];
  2448.     }
  2449.     public function archiveNotification($params$translator): array
  2450.     {
  2451.         $id $params['id'] ?? null;
  2452.         if (!$id) {
  2453.             throw new \Exception("EWS id is required");
  2454.         }
  2455.         $ewsNotification \Pimcore\Model\DataObject::getById($id);
  2456.         if (!$ewsNotification instanceof \Pimcore\Model\DataObject\EwsNotification) {
  2457.             // throw new \Exception("Ews notification not found");
  2458.             return ['success' => false'message' => $translator->trans('ews_notification_not_found')];
  2459.         }
  2460.         if (isset($params['status']) && $params['status']) {
  2461.             $ewsNotification->setStatus("archived");
  2462.         }
  2463.         $ewsNotification->save(["versionNote" => "Update"]);
  2464.         return ['success' => true'message' => $translator->trans('archive_ews_notification'), "notification_id" => $ewsNotification->getId()];
  2465.     }
  2466.     public function getId(): ?UuidV4
  2467.     {
  2468.         $uuid UuidV4::v4();
  2469.         return $uuid;
  2470.     }
  2471.     public function getPhenomenaList()
  2472.     {
  2473.         $phenomenas = new \Pimcore\Model\DataObject\PhenomenaList\Listing();
  2474.         $phenomenas->setOrderKey("o_creationDate");
  2475.         $phenomenas->setOrder("desc");
  2476.         $phenomenas->load();
  2477.         $response = [];
  2478.         if (count($phenomenas) > 0) {
  2479.             foreach ($phenomenas as $phenomena) {
  2480.                 $response[] = [
  2481.                     "id" => $phenomena->getPhenomenaListId(),
  2482.                     "nameEN" => $phenomena->getTitle('en'),
  2483.                     "nameAr" => $phenomena->getTitle('ar'),
  2484.                 ];
  2485.             }
  2486.             return ["success" => true"data" => $response];
  2487.         }
  2488.         return ["success" => false"data" => $response];
  2489.     }
  2490.     public function getHazardListByAlertStatusId($statusId$lang "en")
  2491.     {
  2492.         $response = [];
  2493.         $alertSttaus \Pimcore\Model\DataObject\AlertStatus::getByAlertStatusId($statusIdtrue);
  2494.         if ($alertSttaus instanceof \Pimcore\Model\DataObject\AlertStatus) {
  2495.             if ($alertSttaus && $alertSttaus->getAlertHazards()) {
  2496.                 foreach ($alertSttaus->getAlertHazards() as  $value) {
  2497.                     $alertHazardObj $value->getLocalizedfields()->getItems();
  2498.                     $response[] = ["id" => (int)$value->getAlertHazardId(), "nameEn" => $alertHazardObj['en']['name'], "nameAr" => $alertHazardObj['ar']['name']];
  2499.                 }
  2500.             } else {
  2501.                 return ["success" => false"message" => "No Hazard is set"];
  2502.             }
  2503.         } else {
  2504.             return ["success" => false"message" => "Invalid alert status id"];
  2505.         }
  2506.         return ["success" => true"data" => $response];
  2507.     }
  2508.     // public function getHazardListByAlertStatusId($statusId, $lang = "en")
  2509.     // {
  2510.     //     $response = [];
  2511.     //     $alertPhenomena = \Pimcore\Model\DataObject\PhenomenaList::getByPhenomenaListId($statusId, true);
  2512.     //     if ($alertPhenomena instanceof \Pimcore\Model\DataObject\PhenomenaList) {
  2513.     //         if ($alertPhenomena && $alertPhenomena->getAlertHazards()) {
  2514.     //             foreach ($alertPhenomena->getAlertHazards() as  $value) {
  2515.     //                 $alertHazardObj = $value->getLocalizedfields()->getItems();
  2516.     //                 $response[] = ["id" => (int)$value->getAlertHazardId(), "nameEn" => $alertHazardObj['en']['name'], "nameAr" => $alertHazardObj['ar']['name']];
  2517.     //             }
  2518.     //         } else {
  2519.     //             return ["success" => false, "message" => "No Hazard is set"];
  2520.     //         }
  2521.     //     } else {
  2522.     //         return ["success" => false, "message" => "Invalid alert status id"];
  2523.     //     }
  2524.     //     return ["success" => true, "data" => $response];
  2525.     // }
  2526.     public function getOtherGovernoratesByRegion($regionId)
  2527.     {
  2528.         $response = [];
  2529.         $region \Pimcore\Model\DataObject\Region::getByRegionId($regionIdtrue);
  2530.         if (!$region) {
  2531.             throw new \Exception("Region not available");
  2532.         }
  2533.         $otherGovernorates = new DataObject\EwsOtherLocation\Listing();
  2534.         //$otherGovernorates->filterByRegionId($region);
  2535.         $otherGovernorates $otherGovernorates->load();
  2536.         if ($otherGovernorates) {
  2537.             foreach ($otherGovernorates as $governorate) {
  2538.                 $region $governorate->getregionId();
  2539.                 $regionData = [];
  2540.                 if (!empty($region)) {
  2541.                     $regionData = [
  2542.                         "id" => $region->getRegionId(),
  2543.                         "nameEn" => $region->getName('en'),
  2544.                         "nameAr" => $region->getName('ar'),
  2545.                         "longitude" => $region->getLongitude(),
  2546.                         "latitude" => $region->getLongitude()
  2547.                     ];
  2548.                 }
  2549.                 $response[] = [
  2550.                     "id" => $governorate->getgovernoteId(),
  2551.                     "nameEn" => $governorate->getName('en'),
  2552.                     "nameAr" => $governorate->getName('ar'),
  2553.                     "regionId" => $regionData,
  2554.                     "longitude" => $governorate->getLongitude(),
  2555.                     "latitude" => $governorate->getLatitude(),
  2556.                     "isHidden" => $governorate->getisHidden(),
  2557.                     "IsMunicipality" => $governorate->getIsMunicipality(),
  2558.                     "MunicipalityID" => $governorate->getMunicipalityID()
  2559.                 ];
  2560.             }
  2561.         }
  2562.         return ["success" => true"data" => $response];
  2563.     }
  2564.     public function createEwsReportUserGroup($params$translator)
  2565.     {
  2566.         $response = [];
  2567.         $checkGroup EwsAndReportUserGroup::getByName($params['name'], true);
  2568.         if ($checkGroup instanceof EwsAndReportUserGroup) {
  2569.             return ["success" => false"message" => $translator->trans("group_name_already_exists"), "name" => $params['name']];
  2570.         }
  2571.         $ewsReportUserGroup = new DataObject\EwsAndReportUserGroup();
  2572.         $ewsReportUserGroup->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("/Notification/userGroups/" $params['type'] . "/"));
  2573.         $ewsReportUserGroup->setKey(\Pimcore\Model\Element\Service::getValidKey($params['name'] . "-" strtotime("now") . "-" rand(110000), 'object''object'));
  2574.         $ewsReportUserGroup->setName(strip_tags($params['name']));
  2575.         $ewsReportUserGroup->setJsonData(json_encode($params['data']));
  2576.         $ewsReportUserGroup->setGroupType($params['type']);
  2577.         $ewsReportUserGroup->setPublished(true);
  2578.         $ewsReportUserGroup->save();
  2579.         return ["success" => true"message" => $translator->trans("ews_report_user_group_created")];
  2580.     }
  2581.     public function updateEwsReportUserGroup($params$translator)
  2582.     {
  2583.         $response = [];
  2584.         $updateGroup EwsAndReportUserGroup::getById($params['id']);
  2585.         if (!$updateGroup instanceof EwsAndReportUserGroup) {
  2586.             return ["success" => false"message" => $translator->trans('ews_report_user_group_not_found'), "id" => $params['id']];
  2587.         }
  2588.         if (isset($params['name']) && !empty($params['name']) && $updateGroup->getName() != $params['name']) {
  2589.             $checkGroup EwsAndReportUserGroup::getByName($params['name'], true);
  2590.             if ($checkGroup instanceof EwsAndReportUserGroup) {
  2591.                 return ["success" => false"message" => $translator->trans("group_name_already_exists"), "name" => $params['name']];
  2592.             }
  2593.             $updateGroup->setName(strip_tags($params['name']));
  2594.             $updateGroup->setKey(\Pimcore\Model\Element\Service::getValidKey($params['name'] . "-" strtotime("now") . "-" rand(110000), 'object''object'));
  2595.         }
  2596.         if (isset($params['data']) && !empty($params['data'])) {
  2597.             $updateGroup->setJsonData(json_encode($params['data']));
  2598.         }
  2599.         if (isset($params['type']) && !empty($params['type'])) {
  2600.             $updateGroup->setGroupType($params['type']);
  2601.             $updateGroup->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("/Notification/userGroups/" $params['type'] . "/"));
  2602.         }
  2603.         $updateGroup->setJsonData(json_encode($params['data']));
  2604.         $updateGroup->setGroupType($params['type']);
  2605.         $updateGroup->setPublished(true);
  2606.         $updateGroup->save();
  2607.         return ["success" => true"message" => $translator->trans("ews_report_user_group_updated")];
  2608.     }
  2609.     public function deleteEwsReportUserGroup($params$translator)
  2610.     {
  2611.         $response = [];
  2612.         $deleteGroup EwsAndReportUserGroup::getById($params['id']);
  2613.         if (!$deleteGroup instanceof EwsAndReportUserGroup) {
  2614.             return ["success" => false"message" => $translator->trans('ews_report_user_group_not_found'), "id" => $params['id']];
  2615.         }
  2616.         $deleteGroup->delete();
  2617.         return ["success" => true"message" => $translator->trans("ews_report_user_group_deleted")];
  2618.     }
  2619.     public function listEwsReportUserGroup($params$paginator$translator)
  2620.     {
  2621.         $data = [];
  2622.         $listing = new EwsAndReportUserGroup\Listing();
  2623.     
  2624.         // Allowed sorting keys
  2625.         $allowedOrderKeys = ['name''type''email_count''oo_id'];
  2626.         $allowedOrderDirections = ['asc''desc'];
  2627.     
  2628.         $orderKey $params['orderKey'] ?? 'oo_id';
  2629.         $orderDirection strtolower($params['order'] ?? 'desc');
  2630.     
  2631.         if (in_array($orderKey$allowedOrderKeys) && in_array($orderDirection$allowedOrderDirections)) {
  2632.             $fieldMapping = [
  2633.                 'name' => 'name',
  2634.                 'type' => 'groupType',
  2635.                 'oo_id' => 'oo_id'
  2636.             ];
  2637.     
  2638.             // Normal sorting keys (done in SQL)
  2639.             if (isset($fieldMapping[$orderKey])) {
  2640.                 $listing->setOrderKey($fieldMapping[$orderKey]);
  2641.                 $listing->setOrder(strtoupper($orderDirection));
  2642.             }
  2643.         } else {
  2644.             // Default sorting
  2645.             $orderKey 'oo_id';
  2646.             $orderDirection 'desc';
  2647.             $listing->setOrderKey('oo_id');
  2648.             $listing->setOrder('DESC');
  2649.         }
  2650.     
  2651.         if (isset($params['type']) && !empty($params['type'])) {
  2652.             $listing->addConditionParam("groupType = ?", [$params['type']]);
  2653.         }
  2654.         if (isset($params['search']) && !empty($params['search'])) {
  2655.             $listing->addConditionParam("name LIKE ? ", ['%' $params['search'] . '%']);
  2656.         }
  2657.         
  2658.     
  2659.         $pageSize = isset($params['page_size']) ? $params['page_size'] : LIMIT_PER_PAGE;
  2660.         $page = isset($params['page']) ? $params['page'] : 1;
  2661.     
  2662.         $paginator $paginator->paginate(
  2663.             $listing,
  2664.             $page,
  2665.             $pageSize
  2666.         );
  2667.     
  2668.         // Convert paginator to array
  2669.         $groups iterator_to_array($paginator);
  2670.     
  2671.         // Handle email_count sorting manually in PHP
  2672.         if ($orderKey === 'email_count') {
  2673.             usort($groups, function ($a$b) use ($orderDirection) {
  2674.                 $lenA count(json_decode($a->getJsonData(), true) ?? []);
  2675.                 $lenB count(json_decode($b->getJsonData(), true) ?? []);
  2676.                 return $orderDirection === 'asc' $lenA <=> $lenB $lenB <=> $lenA;
  2677.             });
  2678.         }
  2679.     
  2680.         // Prepare output data
  2681.         foreach ($groups as $group) {
  2682.             $jsonData json_decode($group->getJsonData(), true) ?? [];
  2683.             $data[] = [
  2684.                 "id" => $group->getId(),
  2685.                 "name" => $group->getName(),
  2686.                 "type" => $group->getGroupType(),
  2687.                 "email_count" => count($jsonData),
  2688.                 "data" => $jsonData
  2689.             ];
  2690.         }
  2691.         if (count($data) > 0) {
  2692.             return ["success" => true"data" => $data"paginationVariables" => $paginator->getPaginationData()];
  2693.         } else {
  2694.             return ["success" => false"message" => $translator->trans('no_ews_report_user_group_found')];
  2695.         }
  2696.     }
  2697.     public function getSortCriteria()
  2698.     {
  2699.         // This is a placeholder; you'll need to adapt this based on how you can access the region's name or other criteria
  2700.         return $this->getRegion()->getName();
  2701.     }
  2702.     public function getCenters($governorateId null$lang 'en')
  2703.     {
  2704.         $response = [];
  2705.         $districts = new DataObject\District\Listing();
  2706.         if (is_array($governorateId)) {
  2707.             $govIdsArr = [];
  2708.             foreach ($governorateId as $govId) {
  2709.                 $governorate \Pimcore\Model\DataObject\Governorate::getByGovernoteId($govIdtrue);
  2710.                 if ($governorate) {
  2711.                     array_push($govIdsArr$governorate->getId());
  2712.                 }
  2713.             }
  2714.             $districts->setCondition("governorate__id IN (" implode(", "$govIdsArr) . ")");
  2715.         } else {
  2716.             if ($governorateId) {
  2717.                 $governorate \Pimcore\Model\DataObject\Governorate::getByGovernoteId($governorateIdtrue);
  2718.                 $districts->setCondition("governorate__id = ?", [$governorate->getId()]);
  2719.             }
  2720.         }
  2721.         $districts $districts->load();
  2722.         if ($districts) {
  2723.             foreach ($districts as $district) {
  2724.                 $response[] = [
  2725.                     "id" => $district->getObjectId(),
  2726.                     "nameEn" => $district->getName('en'),
  2727.                     "nameAr" => $district->getName('ar'),
  2728.                     "longitude" => $district->getLongitude(),
  2729.                     "latitude" => $district->getLatitude(),
  2730.                     "governate" => $district->getGovernorate()->getGovernoteId()
  2731.                 ];
  2732.             }
  2733.         }
  2734.         // Determine sorting field based on language
  2735.         $sortField 'nameEn'// Default sorting by English
  2736.         if (isset($lang) && strtolower($lang) === 'ar') {
  2737.             $sortField 'nameAr'// Sorting by Arabic
  2738.         }
  2739.         // Sort manually using usort()
  2740.         usort($response, function ($a$b) use ($sortField) {
  2741.             return strcmp($a[$sortField], $b[$sortField]);
  2742.         });
  2743.         return ["success" => true"data" => $response];
  2744.     }
  2745. }