src/Controller/ReportController.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use Carbon\Carbon;
  5. use Knp\Snappy\Pdf;
  6. use App\Model\UserModel;
  7. use Pimcore\Model\Asset;
  8. use App\Service\RedisCache;
  9. use App\Model\ReportLogModel;
  10. use App\Service\EmailService;
  11. use App\Service\ReportModerationEmailService;
  12. use App\Service\ReportService;
  13. use App\Service\UserPermission;
  14. use App\Model\OrganizationModel;
  15. use Pimcore\Log\ApplicationLogger;
  16. use App\Service\NotificationService;
  17. use Pimcore\Model\DataObject\Report;
  18. use Pimcore\Model\DataObject\ReportType;
  19. use Pimcore\Model\DataObject\Customer;
  20. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  21. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  22. use PhpOffice\PhpSpreadsheet\Style\Fill;
  23. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  24. use App\Service\MeteomaticsWeatherService;
  25. use App\Service\MarineReportService;
  26. use Pimcore\Controller\FrontendController;
  27. use Knp\Component\Pager\PaginatorInterface;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\Routing\Annotation\Route;
  31. use Symfony\Component\HttpFoundation\JsonResponse;
  32. use Symfony\Contracts\Translation\TranslatorInterface;
  33. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  34. use Symfony\Component\Security\Core\User\UserInterface;
  35. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  36. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  37. use Pimcore\Model\DataObject\EwsNotification;
  38. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  39. use App\Model\EwsNotificationModel;
  40. use Symfony\Contracts\HttpClient\HttpClientInterface;
  41. /**
  42.  * Matches 
  43.  *
  44.  * @Route("/api/ncm/report")
  45.  */
  46. class ReportController extends FrontendController
  47. {
  48.     private $organizationModel;
  49.     private $userModel;
  50.     private $lang;
  51.     private $reportModel;
  52.     public function __construct(
  53.         private TokenStorageInterface $tokenStorageInterface,
  54.         private JWTTokenManagerInterface $jwtManager,
  55.         private UserPermission $userPermission,
  56.         protected TranslatorInterface $translator,
  57.         private ApplicationLogger $logger,
  58.         private RedisCache $redisCache,
  59.         private MeteomaticsWeatherService $meteomaticsWeatherService,
  60.         private Pdf $snappy,
  61.         private ReportService $reportService,
  62.         private NotificationService $notificationService,
  63.         private EmailService $emailService,
  64.         private ReportModerationEmailService $reportModerationEmailService,
  65.         private HttpClientInterface $httpClient,
  66.         private MarineReportService $marineReportService
  67.     ) {
  68.         $this->reportModel = new ReportLogModel();
  69.         // header('Content-Type: application/json; charset=UTF-8');
  70.         //header("Access-Control-Allow-Origin: *");
  71.     }
  72.     /**
  73.      * @Route("/weather_forecast_report", name="api_ncm_report_weather_forecast_report", methods={"POST"})
  74.      */
  75.     public function weatherForecastReport(Request $requestUserInterface $user): JsonResponse
  76.     {
  77.         $response = [];
  78.         $params json_decode($request->getContent(), true);
  79.         $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  80.         if (!isset($params['format'])) {
  81.             throw new \InvalidArgumentException('Missing "format" parameter');
  82.         }
  83.         if ($params['format'] == "json") {
  84.             if (
  85.                 !isset($params['startdate']) ||
  86.                 !isset($params['enddate']) ||
  87.                 !isset($params['resolution']) ||
  88.                 !isset($params['parameters']) ||
  89.                 !isset($params['lat']) ||
  90.                 !isset($params['lon']) ||
  91.                 !isset($params['format'])
  92.             ) {
  93.                 throw new \Exception('Missing required parameters');
  94.             }
  95.             //$hour = $params['hour'];
  96.             $format $params['format'];
  97.             $startDate $params['startdate'];
  98.             $endDate $params['enddate'];
  99.             $resolution $params['resolution'];
  100.             $parameters $params['parameters'];
  101.             $model $params['model'];
  102.             $lat $params['lat'];
  103.             $lon $params['lon'];
  104.             $response $this->reportService->getWeatherForecastReport(
  105.                 $startDate,
  106.                 $endDate,
  107.                 $resolution,
  108.                 $parameters,
  109.                 $model,
  110.                 $lat,
  111.                 $lon,
  112.                 $format,
  113.                 $this->translator
  114.             );
  115.         }
  116.         return $this->json($response);
  117.     }
  118.     /**
  119.      * @Route("/special_report", name="api_ncm_report_special_report", methods={"POST"})
  120.      */
  121.     public function specialReport(Request $requestUserInterface $user): JsonResponse
  122.     {
  123.         $response = [];
  124.         $params json_decode($request->getContent(), true);
  125.         $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  126.         if (!isset($params['format'])) {
  127.             throw new \InvalidArgumentException('Missing "format" parameter');
  128.         }
  129.         if ($params['format'] == "json") {
  130.             if (
  131.                 !isset($params['startdate']) ||
  132.                 !isset($params['enddate']) ||
  133.                 !isset($params['resolution']) ||
  134.                 !isset($params['parameters']) ||
  135.                 !isset($params['lat']) ||
  136.                 !isset($params['lon']) ||
  137.                 !isset($params['format'])
  138.             ) {
  139.                 throw new \Exception('Missing required parameters');
  140.             }
  141.             //$hour = $params['hour'];
  142.             $format $params['format'];
  143.             $startDate $params['startdate'];
  144.             $endDate $params['enddate'];
  145.             $resolution $params['resolution'];
  146.             $parameters $params['parameters'];
  147.             $model $params['model'];
  148.             $lat $params['lat'];
  149.             $lon $params['lon'];
  150.             $response $this->reportService->getSpecialReport(
  151.                 $startDate,
  152.                 $endDate,
  153.                 $resolution,
  154.                 $parameters,
  155.                 $model,
  156.                 $lat,
  157.                 $lon,
  158.                 $format,
  159.                 $this->translator
  160.             );
  161.         }
  162.         return $this->json($response);
  163.     }
  164.     /**
  165.      * @Route("/save_data", name="api_ncm_report_save_data", methods={"POST"})
  166.      */
  167.     public function saveData(Request $requestUserInterface $user): JsonResponse
  168.     {
  169.         $response = [];
  170.         try {
  171.             $params json_decode($request->getContent(), true);
  172.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  173.             if (
  174.                 !isset($params['startdate']) ||
  175.                 !isset($params['enddate']) ||
  176.                 !isset($params['lat']) ||
  177.                 !isset($params['lon']) ||
  178.                 !isset($params['type_of_report']) ||
  179.                 !isset($params['key']) ||
  180.                 !isset($params['data'])
  181.             ) {
  182.                 throw new \Exception('Missing required parameters');
  183.             }
  184.             $startDate $params['startdate'];
  185.             $endDate $params['enddate'];
  186.             $typeOfReport $params['type_of_report'];
  187.             $key $params['key'];
  188.             $lat $params['lat'];
  189.             $lon $params['lon'];
  190.             $data $params['data'];
  191.             $response $this->reportService->saveData($key$typeOfReport$startDate$endDate$lat$lon$data);
  192.         } catch (\Exception $ex) {
  193.             $response = ["success" => false"message" => $ex->getMessage()];
  194.         }
  195.         return $this->json($response);
  196.     }
  197.     /**
  198.      * @Route("/generate-report", name="api_ncm_report_generate_report", methods={"POST"})
  199.      */
  200.     public function generateReport(Request $request): JsonResponse
  201.     {
  202.         try {
  203.             $response = [];
  204.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  205.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  206.                 return $this->json($permissions401);
  207.             } elseif ($permissions['success'] === false) {
  208.                 return $this->json($permissions);
  209.             }
  210.             $params json_decode($request->getContent(), true);
  211.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  212.             if (
  213.                 !isset($params['from_date']) ||
  214.                 !isset($params['to_date']) ||
  215.                 !isset($params['parameters_24h']) ||
  216.                 !isset($params['parameters_12h'])  ||
  217.                 !isset($params['is_governate'])  ||
  218.                 !isset($params['locations'])
  219.             ) {
  220.                 throw new \Exception('Missing required parameters');
  221.             }
  222.             if (!is_array($params['parameters_12h'])) {
  223.                 throw new \Exception('Parameters 12 h should be array');
  224.             }
  225.             if (!is_array($params['parameters_24h'])) {
  226.                 throw new \Exception('Parameters 24 h should be array');
  227.             }
  228.             if (empty($params['locations'] || !is_array($params['locations']))) {
  229.                 throw new \Exception('Locations should be non empty array');
  230.             }
  231.             $model = isset($params['model']) ? $params['model'] : 'mix';
  232.             $redisKey md5('generate_city_report-' $params['from_date'] . '-' $params['to_date'] . implode('_'$params['locations'])) . '-' implode('_'$params['parameters_12h']) . '-' implode('_'$params['parameters_24h']) . '-' $model;
  233.             $data $this->redisCache->get($redisKey);
  234.             if (!$data) {
  235.                 // if governorate is true then get the cities from governorate else get the cities from city
  236.                 if ($params['is_governate']) {
  237.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  238.                     $cities->setOrderKey('orderId');
  239.                     $cities->setOrder('asc');
  240.                     if (!empty($params['locations'])) {
  241.                         $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  242.                     }
  243.                 } else {
  244.                     $cities = new \Pimcore\Model\DataObject\City\Listing();
  245.                     $cities->setOrderKey('orderId');
  246.                     $cities->setOrder('asc');
  247.                     if (!empty($params['locations'])) {
  248.                         $cities->setCondition('o_id IN (?)', [$params['locations']]);
  249.                     }
  250.                 }
  251.                 $cities->load();
  252.                 if ($cities->getCount() > 0) {
  253.                     $params['coordinates'] = []; // Initialize an empty array for coordinates
  254.                     $result = [];
  255.                     $citiesArr = [];
  256.                     foreach ($cities as $city) {
  257.                         $params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
  258.                         // Append the coordinates for each city
  259.                         $long number_format($city->getLongitude(), 6'.''');
  260.                         $lat number_format($city->getLatitude(), 6'.''');
  261.                         // if governorate is true then get the cities from governorate else get the cities from city
  262.                         if ($params['is_governate']) {
  263.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  264.                             $citiesArr[$lat '|' $long]["en"] =  $city->getName("en");
  265.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getName("ar");
  266.                         } else {
  267.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  268.                             $citiesArr[$lat '|' $long]["en"] =  $city->getCityName("en");
  269.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getCityName("ar");
  270.                         }
  271.                     }
  272.                     $result $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model$params['parameters_12h'], $params['parameters_24h'], $this->translator$citiesArr$params);
  273.                     $response[] = $result;
  274.                     $jsonResponse = ['success' => true'data' => $response];
  275.                     $this->redisCache->set($redisKey$jsonResponseREDIS_CACHE_TIME);
  276.                     return $this->json($jsonResponse);
  277.                 } else {
  278.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  279.                 }
  280.             } else {
  281.                 return $this->json($data);
  282.             }
  283.         } catch (\Exception $ex) {
  284.             // throw new \Exception($ex);
  285.             // $this->logger->error($ex->getMessage());
  286.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  287.         }
  288.     }
  289.     /**
  290.      * @Route("/create-arabian-gulf-report", name="api_ncm_report_create_arabian_gulf_report", methods={"POST"})
  291.      */
  292.     public function createArabianGulfReport(Request $request): JsonResponse
  293.     {
  294.         try {
  295.             $response = [];
  296.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  297.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  298.                 return $this->json($permissions401);
  299.             } elseif ($permissions['success'] === false) {
  300.                 return $this->json($permissions);
  301.             }
  302.             $params json_decode($request->getContent(), true);
  303.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  304.             if (
  305.                 !isset($params['from_date']) ||
  306.                 !isset($params['to_date']) ||
  307.                 !isset($params['parameters_24h']) ||
  308.                 !isset($params['parameters_12h'])  ||
  309.                 !isset($params['is_governate'])  ||
  310.                 !isset($params['locations'])
  311.             ) {
  312.                 throw new \Exception('Missing required parameters');
  313.             }
  314.             if (!is_array($params['parameters_12h'])) {
  315.                 throw new \Exception('Parameters 12 h should be array');
  316.             }
  317.             if (!is_array($params['parameters_24h'])) {
  318.                 throw new \Exception('Parameters 24 h should be array');
  319.             }
  320.             if (empty($params['locations'] || !is_array($params['locations']))) {
  321.                 throw new \Exception('Locations should be non empty array');
  322.             }
  323.             $model = isset($params['model']) ? $params['model'] : 'mix';
  324.             $redisKey md5('generate_city_report-' $params['from_date'] . '-' $params['to_date'] . implode('_'$params['locations'])) . '-' implode('_'$params['parameters_12h']) . '-' implode('_'$params['parameters_24h']) . '-' $model;
  325.             $data $this->redisCache->get($redisKey);
  326.             if (!$data) {
  327.                 // if governorate is true then get the cities from governorate else get the cities from city
  328.                 if ($params['is_governate']) {
  329.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  330.                     $cities->setOrderKey('orderId');
  331.                     $cities->setOrder('asc');
  332.                     if (!empty($params['locations'])) {
  333.                         $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  334.                     }
  335.                 } else {
  336.                     $cities = new \Pimcore\Model\DataObject\City\Listing();
  337.                     $cities->setOrderKey('orderId');
  338.                     $cities->setOrder('asc');
  339.                     if (!empty($params['locations'])) {
  340.                         $cities->setCondition('o_id IN (?)', [$params['locations']]);
  341.                     }
  342.                 }
  343.                 $cities->load();
  344.                 if ($cities->getCount() > 0) {
  345.                     $params['coordinates'] = []; // Initialize an empty array for coordinates
  346.                     $result = [];
  347.                     $citiesArr = [];
  348.                     foreach ($cities as $city) {
  349.                         $params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
  350.                         // Append the coordinates for each city
  351.                         $long number_format($city->getLongitude(), 6'.''');
  352.                         $lat number_format($city->getLatitude(), 6'.''');
  353.                         // if governorate is true then get the cities from governorate else get the cities from city
  354.                         if ($params['is_governate']) {
  355.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  356.                             $citiesArr[$lat '|' $long]["en"] =  $city->getName("en");
  357.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getName("ar");
  358.                         } else {
  359.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  360.                             $citiesArr[$lat '|' $long]["en"] =  $city->getCityName("en");
  361.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getCityName("ar");
  362.                         }
  363.                     }
  364.                     $result $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model$params['parameters_12h'], $params['parameters_24h'], $this->translator$citiesArr$params);
  365.                     $response[] = $result;
  366.                     $jsonResponse = ['success' => true'data' => $response];
  367.                     $this->redisCache->set($redisKey$jsonResponseREDIS_CACHE_TIME);
  368.                     return $this->json($jsonResponse);
  369.                 } else {
  370.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  371.                 }
  372.             } else {
  373.                 return $this->json($data);
  374.             }
  375.         } catch (\Exception $ex) {
  376.             // throw new \Exception($ex);
  377.             // $this->logger->error($ex->getMessage());
  378.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  379.         }
  380.     }
  381.     /**
  382.      * @Route("/create-today-weather-report", name="api_ncm_report_create_today_weather_report", methods={"POST"})
  383.      */
  384.     public function createTodayWeatherReport(Request $request): JsonResponse
  385.     {
  386.         try {
  387.             $response = [];
  388.             // $permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
  389.             // if (isset($permissions['code']) && $permissions['code'] === 401) {
  390.             //     return $this->json($permissions, 401);
  391.             // } elseif ($permissions['success'] === false) {
  392.             //     return $this->json($permissions);
  393.             // }
  394.             $params json_decode($request->getContent(), true);
  395.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  396.             if (
  397.                 !isset($params['from_date']) ||
  398.                 !isset($params['to_date']) ||
  399.                 !isset($params['parameters_24h']) ||
  400.                 !isset($params['parameters_12h'])  ||
  401.                 !isset($params['is_governate'])  ||
  402.                 !isset($params['locations'])
  403.             ) {
  404.                 throw new \Exception('Missing required parameters');
  405.             }
  406.             if (!is_array($params['parameters_12h'])) {
  407.                 throw new \Exception('Parameters 12 h should be array');
  408.             }
  409.             if (!is_array($params['parameters_24h'])) {
  410.                 throw new \Exception('Parameters 24 h should be array');
  411.             }
  412.             if (empty($params['locations'] || !is_array($params['locations']))) {
  413.                 throw new \Exception('Locations should be non empty array');
  414.             }
  415.             $model = isset($params['model']) ? $params['model'] : 'mix';
  416.             $redisKey md5('generate_city_report-' $params['from_date'] . '-' $params['to_date'] . implode('_'$params['locations'])) . '-' implode('_'$params['parameters_12h']) . '-' implode('_'$params['parameters_24h']) . '-' $model;
  417.             $data $this->redisCache->get($redisKey);
  418.             if (!$data) {
  419.                 // if governorate is true then get the cities from governorate else get the cities from city
  420.                 if ($params['is_governate']) {
  421.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  422.                     $cities->setOrderKey('orderId');
  423.                     $cities->setOrder('asc');
  424.                     if (!empty($params['locations'])) {
  425.                         $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  426.                     }
  427.                 } else {
  428.                     $cities = new \Pimcore\Model\DataObject\City\Listing();
  429.                     $cities->setOrderKey('orderId');
  430.                     $cities->setOrder('asc');
  431.                     if (!empty($params['locations'])) {
  432.                         $cities->setCondition('o_id IN (?)', [$params['locations']]);
  433.                     }
  434.                 }
  435.                 $cities->load();
  436.                 if ($cities->getCount() > 0) {
  437.                     $params['coordinates'] = []; // Initialize an empty array for coordinates
  438.                     $result = [];
  439.                     $citiesArr = [];
  440.                     foreach ($cities as $city) {
  441.                         $params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
  442.                         // Append the coordinates for each city
  443.                         $long number_format($city->getLongitude(), 6'.''');
  444.                         $lat number_format($city->getLatitude(), 6'.''');
  445.                         // if governorate is true then get the cities from governorate else get the cities from city
  446.                         if ($params['is_governate']) {
  447.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  448.                             $citiesArr[$lat '|' $long]["en"] =  $city->getName("en");
  449.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getName("ar");
  450.                         } else {
  451.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  452.                             $citiesArr[$lat '|' $long]["en"] =  $city->getCityName("en");
  453.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getCityName("ar");
  454.                         }
  455.                     }
  456.                     $result $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model$params['parameters_12h'], $params['parameters_24h'], $this->translator$citiesArr$params);
  457.                     $response[] = $result;
  458.                     $jsonResponse = ['success' => true'data' => $response];
  459.                     $this->redisCache->set($redisKey$jsonResponseREDIS_CACHE_TIME);
  460.                     return $this->json($jsonResponse);
  461.                 } else {
  462.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  463.                 }
  464.             } else {
  465.                 return $this->json($data);
  466.             }
  467.         } catch (\Exception $ex) {
  468.             // throw new \Exception($ex);
  469.             // $this->logger->error($ex->getMessage());
  470.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  471.         }
  472.     }
  473.     /**
  474.      * @Route("/create-red-sea-report", name="api_ncm_report_create_red_sea_report", methods={"POST"})
  475.      */
  476.     public function createRedSeaReport(Request $request): JsonResponse
  477.     {
  478.         try {
  479.             $response = [];
  480.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  481.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  482.                 return $this->json($permissions401);
  483.             } elseif ($permissions['success'] === false) {
  484.                 return $this->json($permissions);
  485.             }
  486.             $params json_decode($request->getContent(), true);
  487.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  488.             if (
  489.                 !isset($params['from_date']) ||
  490.                 !isset($params['to_date']) ||
  491.                 !isset($params['parameters_24h']) ||
  492.                 !isset($params['parameters_12h'])  ||
  493.                 !isset($params['is_governate'])  ||
  494.                 !isset($params['locations'])
  495.             ) {
  496.                 throw new \Exception('Missing required parameters');
  497.             }
  498.             if (!is_array($params['parameters_12h'])) {
  499.                 throw new \Exception('Parameters 12 h should be array');
  500.             }
  501.             if (!is_array($params['parameters_24h'])) {
  502.                 throw new \Exception('Parameters 24 h should be array');
  503.             }
  504.             if (empty($params['locations'] || !is_array($params['locations']))) {
  505.                 throw new \Exception('Locations should be non empty array');
  506.             }
  507.             $model = isset($params['model']) ? $params['model'] : 'mix';
  508.             $redisKey md5('generate_city_report-' $params['from_date'] . '-' $params['to_date'] . implode('_'$params['locations'])) . '-' implode('_'$params['parameters_12h']) . '-' implode('_'$params['parameters_24h']) . '-' $model;
  509.             $data $this->redisCache->get($redisKey);
  510.             if (!$data) {
  511.                 // if governorate is true then get the cities from governorate else get the cities from city
  512.                 if ($params['is_governate']) {
  513.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  514.                     $cities->setOrderKey('orderId');
  515.                     $cities->setOrder('asc');
  516.                     if (!empty($params['locations'])) {
  517.                         $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  518.                     }
  519.                 } else {
  520.                     $cities = new \Pimcore\Model\DataObject\City\Listing();
  521.                     $cities->setOrderKey('orderId');
  522.                     $cities->setOrder('asc');
  523.                     if (!empty($params['locations'])) {
  524.                         $cities->setCondition('o_id IN (?)', [$params['locations']]);
  525.                     }
  526.                 }
  527.                 $cities->load();
  528.                 if ($cities->getCount() > 0) {
  529.                     $params['coordinates'] = []; // Initialize an empty array for coordinates
  530.                     $result = [];
  531.                     $citiesArr = [];
  532.                     foreach ($cities as $city) {
  533.                         $params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
  534.                         // Append the coordinates for each city
  535.                         $long number_format($city->getLongitude(), 6'.''');
  536.                         $lat number_format($city->getLatitude(), 6'.''');
  537.                         // if governorate is true then get the cities from governorate else get the cities from city
  538.                         if ($params['is_governate']) {
  539.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  540.                             $citiesArr[$lat '|' $long]["en"] =  $city->getName("en");
  541.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getName("ar");
  542.                         } else {
  543.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  544.                             $citiesArr[$lat '|' $long]["en"] =  $city->getCityName("en");
  545.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getCityName("ar");
  546.                         }
  547.                     }
  548.                     $result $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model$params['parameters_12h'], $params['parameters_24h'], $this->translator$citiesArr$params);
  549.                     $response[] = $result;
  550.                     $jsonResponse = ['success' => true'data' => $response];
  551.                     $this->redisCache->set($redisKey$jsonResponseREDIS_CACHE_TIME);
  552.                     return $this->json($jsonResponse);
  553.                 } else {
  554.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  555.                 }
  556.             } else {
  557.                 return $this->json($data);
  558.             }
  559.         } catch (\Exception $ex) {
  560.             // throw new \Exception($ex);
  561.             // $this->logger->error($ex->getMessage());
  562.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  563.         }
  564.     }
  565.     /**
  566.      * @Route("/create-custom-weather-report", name="api_ncm_report_create_custom_weather_report", methods={"POST"})
  567.      */
  568.     public function createCustomWeatherReport(Request $request): JsonResponse
  569.     {
  570.         try {
  571.             $response = [];
  572.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  573.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  574.                 return $this->json($permissions401);
  575.             } elseif ($permissions['success'] === false) {
  576.                 return $this->json($permissions);
  577.             }
  578.             $params json_decode($request->getContent(), true);
  579.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  580.             if (
  581.                 !isset($params['from_date']) ||
  582.                 !isset($params['to_date']) ||
  583.                 !isset($params['parameters_24h']) ||
  584.                 !isset($params['parameters_12h'])  ||
  585.                 !isset($params['is_governate'])  ||
  586.                 !isset($params['locations'])
  587.             ) {
  588.                 throw new \Exception('Missing required parameters');
  589.             }
  590.             if (!is_array($params['parameters_12h'])) {
  591.                 throw new \Exception('Parameters 12 h should be array');
  592.             }
  593.             if (!is_array($params['parameters_24h'])) {
  594.                 throw new \Exception('Parameters 24 h should be array');
  595.             }
  596.             if (empty($params['locations'] || !is_array($params['locations']))) {
  597.                 throw new \Exception('Locations should be non empty array');
  598.             }
  599.             $model = isset($params['model']) ? $params['model'] : 'mix';
  600.             $redisKey md5('generate_city_report-' $params['from_date'] . '-' $params['to_date'] . implode('_'$params['locations'])) . '-' implode('_'$params['parameters_12h']) . '-' implode('_'$params['parameters_24h']) . '-' $model;
  601.             $data $this->redisCache->get($redisKey);
  602.             if (!$data) {
  603.                 // if governorate is true then get the cities from governorate else get the cities from city
  604.                 if ($params['is_governate']) {
  605.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  606.                     $cities->setOrderKey('orderId');
  607.                     $cities->setOrder('asc');
  608.                     if (!empty($params['locations'])) {
  609.                         $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  610.                     }
  611.                 } else {
  612.                     $cities = new \Pimcore\Model\DataObject\City\Listing();
  613.                     $cities->setOrderKey('orderId');
  614.                     $cities->setOrder('asc');
  615.                     if (!empty($params['locations'])) {
  616.                         $cities->setCondition('o_id IN (?)', [$params['locations']]);
  617.                     }
  618.                 }
  619.                 $cities->load();
  620.                 if ($cities->getCount() > 0) {
  621.                     $params['coordinates'] = []; // Initialize an empty array for coordinates
  622.                     $result = [];
  623.                     $citiesArr = [];
  624.                     foreach ($cities as $city) {
  625.                         $params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
  626.                         // Append the coordinates for each city
  627.                         $long number_format($city->getLongitude(), 6'.''');
  628.                         $lat number_format($city->getLatitude(), 6'.''');
  629.                         // if governorate is true then get the cities from governorate else get the cities from city
  630.                         if ($params['is_governate']) {
  631.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  632.                             $citiesArr[$lat '|' $long]["en"] =  $city->getName("en");
  633.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getName("ar");
  634.                         } else {
  635.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  636.                             $citiesArr[$lat '|' $long]["en"] =  $city->getCityName("en");
  637.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getCityName("ar");
  638.                         }
  639.                     }
  640.                     $result $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model$params['parameters_12h'], $params['parameters_24h'], $this->translator$citiesArr$params);
  641.                     $response[] = $result;
  642.                     $jsonResponse = ['success' => true'data' => $response];
  643.                     $this->redisCache->set($redisKey$jsonResponseREDIS_CACHE_TIME);
  644.                     return $this->json($jsonResponse);
  645.                 } else {
  646.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  647.                 }
  648.             } else {
  649.                 return $this->json($data);
  650.             }
  651.         } catch (\Exception $ex) {
  652.             // throw new \Exception($ex);
  653.             // $this->logger->error($ex->getMessage());
  654.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  655.         }
  656.     }
  657.     /**
  658.      * @Route("/create-mashaer-weather-report", name="api_ncm_report_create_mashaer_weather_report", methods={"POST"})
  659.      */
  660.     public function createMashaerWeatherReport(Request $request): JsonResponse
  661.     {
  662.         try {
  663.             $response = [];
  664.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  665.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  666.                 return $this->json($permissions401);
  667.             } elseif ($permissions['success'] === false) {
  668.                 return $this->json($permissions);
  669.             }
  670.             $params json_decode($request->getContent(), true);
  671.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  672.             if (
  673.                 !isset($params['from_date']) ||
  674.                 !isset($params['to_date']) ||
  675.                 !isset($params['parameters_24h']) ||
  676.                 !isset($params['parameters_12h'])  ||
  677.                 !isset($params['is_governate'])  ||
  678.                 !isset($params['locations'])
  679.             ) {
  680.                 throw new \Exception('Missing required parameters');
  681.             }
  682.             if (!is_array($params['parameters_12h'])) {
  683.                 throw new \Exception('Parameters 12 h should be array');
  684.             }
  685.             if (!is_array($params['parameters_24h'])) {
  686.                 throw new \Exception('Parameters 24 h should be array');
  687.             }
  688.             if (empty($params['locations'] || !is_array($params['locations']))) {
  689.                 throw new \Exception('Locations should be non empty array');
  690.             }
  691.             $model = isset($params['model']) ? $params['model'] : 'mix';
  692.             $redisKey md5('generate_city_report-' $params['from_date'] . '-' $params['to_date'] . implode('_'$params['locations'])) . '-' implode('_'$params['parameters_12h']) . '-' implode('_'$params['parameters_24h']) . '-' $model;
  693.             $data $this->redisCache->get($redisKey);
  694.             if (!$data) {
  695.                 // if governorate is true then get the cities from governorate else get the cities from city
  696.                 if ($params['is_governate']) {
  697.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  698.                     $cities->setOrderKey('orderId');
  699.                     $cities->setOrder('asc');
  700.                     if (!empty($params['locations'])) {
  701.                         $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  702.                     }
  703.                 } else {
  704.                     $cities = new \Pimcore\Model\DataObject\City\Listing();
  705.                     $cities->setOrderKey('orderId');
  706.                     $cities->setOrder('asc');
  707.                     if (!empty($params['locations'])) {
  708.                         $cities->setCondition('o_id IN (?)', [$params['locations']]);
  709.                     }
  710.                 }
  711.                 $cities->load();
  712.                 if ($cities->getCount() > 0) {
  713.                     $params['coordinates'] = []; // Initialize an empty array for coordinates
  714.                     $result = [];
  715.                     $citiesArr = [];
  716.                     foreach ($cities as $city) {
  717.                         $params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
  718.                         // Append the coordinates for each city
  719.                         $long number_format($city->getLongitude(), 6'.''');
  720.                         $lat number_format($city->getLatitude(), 6'.''');
  721.                         // if governorate is true then get the cities from governorate else get the cities from city
  722.                         if ($params['is_governate']) {
  723.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  724.                             $citiesArr[$lat '|' $long]["en"] =  $city->getName("en");
  725.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getName("ar");
  726.                         } else {
  727.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  728.                             $citiesArr[$lat '|' $long]["en"] =  $city->getCityName("en");
  729.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getCityName("ar");
  730.                         }
  731.                     }
  732.                     $result $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model$params['parameters_12h'], $params['parameters_24h'], $this->translator$citiesArr$params);
  733.                     $response[] = $result;
  734.                     $jsonResponse = ['success' => true'data' => $response];
  735.                     $this->redisCache->set($redisKey$jsonResponseREDIS_CACHE_TIME);
  736.                     return $this->json($jsonResponse);
  737.                 } else {
  738.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  739.                 }
  740.             } else {
  741.                 return $this->json($data);
  742.             }
  743.         } catch (\Exception $ex) {
  744.             // throw new \Exception($ex);
  745.             // $this->logger->error($ex->getMessage());
  746.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  747.         }
  748.     }
  749.     /**
  750.      * @Route("/create-10-day-forecast-report", name="api_ncm_report_create_10_day_forecast_report", methods={"POST"})
  751.      */
  752.     public function create10DayForecastReport(Request $request): JsonResponse
  753.     {
  754.         try {
  755.             $response = [];
  756.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  757.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  758.                 return $this->json($permissions401);
  759.             } elseif ($permissions['success'] === false) {
  760.                 return $this->json($permissions);
  761.             }
  762.             $params json_decode($request->getContent(), true);
  763.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  764.             if (
  765.                 !isset($params['from_date']) ||
  766.                 !isset($params['to_date']) ||
  767.                 !isset($params['parameters_24h']) ||
  768.                 !isset($params['parameters_12h'])  ||
  769.                 !isset($params['is_governate'])  ||
  770.                 !isset($params['locations'])
  771.             ) {
  772.                 throw new \Exception('Missing required parameters');
  773.             }
  774.             if (!is_array($params['parameters_12h'])) {
  775.                 throw new \Exception('Parameters 12 h should be array');
  776.             }
  777.             if (!is_array($params['parameters_24h'])) {
  778.                 throw new \Exception('Parameters 24 h should be array');
  779.             }
  780.             if (empty($params['locations'] || !is_array($params['locations']))) {
  781.                 throw new \Exception('Locations should be non empty array');
  782.             }
  783.             $model = isset($params['model']) ? $params['model'] : 'mix';
  784.             $redisKey md5('generate_city_report-' $params['from_date'] . '-' $params['to_date'] . implode('_'$params['locations'])) . '-' implode('_'$params['parameters_12h']) . '-' implode('_'$params['parameters_24h']) . '-' $model;
  785.             $data $this->redisCache->get($redisKey);
  786.             if (!$data) {
  787.                 // if governorate is true then get the cities from governorate else get the cities from city
  788.                 if ($params['is_governate']) {
  789.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  790.                     $cities->setOrderKey('orderId');
  791.                     $cities->setOrder('asc');
  792.                     if (!empty($params['locations'])) {
  793.                         $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  794.                     }
  795.                 } else {
  796.                     $cities = new \Pimcore\Model\DataObject\City\Listing();
  797.                     $cities->setOrderKey('orderId');
  798.                     $cities->setOrder('asc');
  799.                     if (!empty($params['locations'])) {
  800.                         $cities->setCondition('o_id IN (?)', [$params['locations']]);
  801.                     }
  802.                 }
  803.                 $cities->load();
  804.                 if ($cities->getCount() > 0) {
  805.                     $params['coordinates'] = []; // Initialize an empty array for coordinates
  806.                     $result = [];
  807.                     $citiesArr = [];
  808.                     foreach ($cities as $city) {
  809.                         $params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
  810.                         // Append the coordinates for each city
  811.                         $long number_format($city->getLongitude(), 6'.''');
  812.                         $lat number_format($city->getLatitude(), 6'.''');
  813.                         // if governorate is true then get the cities from governorate else get the cities from city
  814.                         if ($params['is_governate']) {
  815.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  816.                             $citiesArr[$lat '|' $long]["en"] =  $city->getName("en");
  817.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getName("ar");
  818.                         } else {
  819.                             $citiesArr[$lat '|' $long]["id"] =  $city->getId();
  820.                             $citiesArr[$lat '|' $long]["en"] =  $city->getCityName("en");
  821.                             $citiesArr[$lat '|' $long]["ar"] =  $city->getCityName("ar");
  822.                         }
  823.                     }
  824.                     $result $this->meteomaticsWeatherService->getAdminReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $model$params['parameters_12h'], $params['parameters_24h'], $this->translator$citiesArr$params);
  825.                     $response[] = $result;
  826.                     $jsonResponse = ['success' => true'data' => $response];
  827.                     $this->redisCache->set($redisKey$jsonResponseREDIS_CACHE_TIME);
  828.                     return $this->json($jsonResponse);
  829.                 } else {
  830.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  831.                 }
  832.             } else {
  833.                 return $this->json($data);
  834.             }
  835.         } catch (\Exception $ex) {
  836.             // throw new \Exception($ex);
  837.             // $this->logger->error($ex->getMessage());
  838.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  839.         }
  840.     }
  841.     /**
  842.      * @Route("/create-report", name="api_ncm_report_create_report", methods={"POST"})
  843.      */
  844.     public function createReport(Request $requestUserInterface $user)
  845.     {
  846.         try {
  847.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  848.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  849.                 return $this->json($permissions401);
  850.             } elseif ($permissions['success'] === false) {
  851.                 return $this->json($permissions);
  852.             }
  853.             $params  json_decode($request->getContent(), true);
  854.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  855.             // Perform parameter validation here
  856.             // || !isset($params['locations'])
  857.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
  858.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  859.             }
  860.             if (isset($params['organizations'])) {
  861.                 if (!is_array($params['organizations'])) {
  862.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  863.                 }
  864.             }
  865.             if (isset($params['channels'])) {
  866.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  867.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  868.                 }
  869.                 if (in_array('email'$params['channels'])) {
  870.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  871.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  872.                     }
  873.                 }
  874.                 if (in_array('twitter'$params['channels'])) {
  875.                     if (!isset($params['xCaption']) || empty($params['xCaption'])) {
  876.                         throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
  877.                     }
  878.                 }
  879.             }
  880.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  881.             return $this->json($result);
  882.         } catch (\Exception $ex) {
  883.             $this->logger->error($ex->getMessage());
  884.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  885.         }
  886.     }
  887.     /**
  888.      * @Route("/publish-arabian-gulf-report", name="api_ncm_report_publish_arabian_gulf", methods={"POST"})
  889.      */
  890.     public function publishArabianGulfReport(Request $requestUserInterface $user)
  891.     {
  892.         try {
  893.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  894.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  895.                 return $this->json($permissions401);
  896.             } elseif ($permissions['success'] === false) {
  897.                 return $this->json($permissions);
  898.             }
  899.             $params  json_decode($request->getContent(), true);
  900.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  901.             // Perform parameter validation here
  902.             // || !isset($params['locations'])
  903.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
  904.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  905.             }
  906.             if (isset($params['organizations'])) {
  907.                 if (!is_array($params['organizations'])) {
  908.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  909.                 }
  910.             }
  911.             if (isset($params['channels'])) {
  912.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  913.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  914.                 }
  915.                 if (in_array('email'$params['channels'])) {
  916.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  917.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  918.                     }
  919.                 }
  920.                 if (in_array('twitter'$params['channels'])) {
  921.                     if (!isset($params['xCaption']) || empty($params['xCaption'])) {
  922.                         throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
  923.                     }
  924.                 }
  925.             }
  926.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  927.             return $this->json($this->finalizeModerationPublishResult($result$user));
  928.         } catch (\Exception $ex) {
  929.             $this->logger->error($ex->getMessage());
  930.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  931.         }
  932.     }
  933.     /**
  934.      * @Route("/publish-today-weather-report", name="api_ncm_report_publish_today_weather_report", methods={"POST"})
  935.      */
  936.     public function publishTodayWeatherReport(Request $requestUserInterface $user)
  937.     {
  938.         try {
  939.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  940.             // if (isset($permissions['code']) && $permissions['code'] === 401) {
  941.             //     return $this->json($permissions, 401);
  942.             // } elseif ($permissions['success'] === false) {
  943.             //     return $this->json($permissions);
  944.             // }
  945.             $params  json_decode($request->getContent(), true);
  946.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  947.             // Perform parameter validation here
  948.             // || !isset($params['locations'])
  949.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['imageEn']) || !isset($params['imageAr'])) {
  950.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  951.             }
  952.             if (isset($params['organizations'])) {
  953.                 if (!is_array($params['organizations'])) {
  954.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  955.                 }
  956.             }
  957.             if (isset($params['channels'])) {
  958.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  959.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  960.                 }
  961.                 if (in_array('email'$params['channels'])) {
  962.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  963.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  964.                     }
  965.                 }
  966.                 if (in_array('twitter'$params['channels'])) {
  967.                     if (!isset($params['xCaption']) || empty($params['xCaption'])) {
  968.                         throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
  969.                     }
  970.                 }
  971.             }
  972.             $result $this->reportModel->createTodayWeatherReport($user$params$this->translator$this->logger);
  973.             return $this->json($result);
  974.         } catch (\Exception $ex) {
  975.             $this->logger->error($ex->getMessage());
  976.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  977.         }
  978.     }
  979.     /**
  980.      * Marine report payload (preferred): redSeaWind, redSeaWaveHight, redSeaStatus, arabianGulfWind, arabianGulfWaveHight, arabianGulfSeaStatus (non-empty strings).
  981.      * Alternate: redSea, arabianGulf objects (WindAr/WaveHightAr/SeaStatusAr or windSpeed, windDirection, waveHeight, visibility, weather).
  982.      * Optional weatherDate (UTC); display { dayNameArabic, gregorian, hijri } is built server-side via MarineReportService::buildDateDisplay (or "now" in Riyadh when omitted).
  983.      * Required infographicImageBase64: client image (PNG/JPEG/GIF/WebP), plain base64 or data:image/...;base64,.
  984.      * Optional apiUrl, lang, Authorization (JWT in body when validateAPI is enabled).
  985.      *
  986.      * @Route("/publish-marine-report", name="api_ncm_report_publish_marine_report", methods={"POST"})
  987.      */
  988.     public function publishMarineReport(Request $requestUserInterface $user): JsonResponse
  989.     {
  990.         try {
  991.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  992.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  993.                 return $this->json($permissions401);
  994.             }
  995.             if (($permissions['success'] ?? false) === false) {
  996.                 return $this->json($permissions);
  997.             }
  998.             $params json_decode($request->getContent(), true);
  999.             if (!\is_array($params)) {
  1000.                 return $this->json(['success' => false'message' => $this->translator->trans('missing_required_parameters')]);
  1001.             }
  1002.             $this->translator->setlocale($params['lang'] ?? DEFAULT_LOCALE);
  1003.             $flatMarineKeys = [
  1004.                 'redSeaWind',
  1005.                 'redSeaWaveHight',
  1006.                 'redSeaStatus',
  1007.                 'arabianGulfWind',
  1008.                 'arabianGulfWaveHight',
  1009.                 'arabianGulfSeaStatus',
  1010.                 'infographicImageBase64',
  1011.                 'twitterDescription',
  1012.             ];
  1013.             $useFlatPayload true;
  1014.             foreach ($flatMarineKeys as $key) {
  1015.                 if (!isset($params[$key]) || trim((string) $params[$key]) === '') {
  1016.                     $useFlatPayload false;
  1017.                     break;
  1018.                 }
  1019.             }
  1020.             if ($useFlatPayload) {
  1021.                 $redSea $this->marineReportService->normalizeMarineRegionForInfographic([
  1022.                     'WindAr' => trim((string) $params['redSeaWind']),
  1023.                     'WaveHightAr' => trim((string) $params['redSeaWaveHight']),
  1024.                     'SeaStatusAr' => trim((string) $params['redSeaStatus']),
  1025.                 ]);
  1026.                 $gulf $this->marineReportService->normalizeMarineRegionForInfographic([
  1027.                     'WindAr' => trim((string) $params['arabianGulfWind']),
  1028.                     'WaveHightAr' => trim((string) $params['arabianGulfWaveHight']),
  1029.                     'SeaStatusAr' => trim((string) $params['arabianGulfSeaStatus']),
  1030.                 ]);
  1031.             }
  1032.             if (!$this->marineReportService->regionHasContent($redSea) && !$this->marineReportService->regionHasContent($gulf)) {
  1033.                 return $this->json([
  1034.                     'success' => true,
  1035.                     'message' => $this->translator->trans('marine_report_skipped_empty'),
  1036.                     'data' => null,
  1037.                 ]);
  1038.             }
  1039.             $clientInfographicB64 null;
  1040.             if (isset($params['infographicImageBase64']) && trim((string) $params['infographicImageBase64']) !== '') {
  1041.                 $clientInfographicB64 trim((string) $params['infographicImageBase64']);
  1042.             }
  1043.             if ($clientInfographicB64 === null) {
  1044.                 return $this->json(['success' => false'message' => $this->translator->trans('missing_required_parameters')]);
  1045.             }
  1046.             $decodedImage $this->reportModel->decodeImageBase64String($clientInfographicB64);
  1047.             if ($decodedImage === false || @getimagesizefromstring($decodedImage) === false) {
  1048.                 return $this->json(['success' => false'message' => $this->translator->trans('marine_report_invalid_image')]);
  1049.             }
  1050.             $result $this->reportModel->createMarineReport($user, [
  1051.                 'redSea' => $redSea,
  1052.                 'gulf' => $gulf,
  1053.                 'weatherDate' => $params['weatherDate'] ?? null,
  1054.                 'infographicImageBase64' => $decodedImage,
  1055.                 'twitterDescription' => $params['twitterDescription'] ?? '',
  1056.             ], $this->translator$this->marineReportService);
  1057.             return $this->json($result);
  1058.         } catch (\Exception $ex) {
  1059.             $this->logger->error($ex->getMessage());
  1060.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1061.         }
  1062.     }
  1063.     /**
  1064.      * Fetches upstream marine-reports JSON, then responds with { redSea, arabianGulf, display, apiUrl } (same shape as publish-marine-report body).
  1065.      * Upstream may be a list of rows or already that object. Forwards query string to upstream (except lang). Optional ?lang= for error messages.
  1066.      *
  1067.      * @Route("/get-marine-reports", name="api_ncm_report_get_marine_reports", methods={"POST"})
  1068.      */
  1069.     public function getMarineReports(Request $requestUserInterface $user): JsonResponse
  1070.     {
  1071.         try {
  1072.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1073.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1074.                 return $this->json($permissions401);
  1075.             }
  1076.             if (($permissions['success'] ?? false) === false) {
  1077.                 return $this->json($permissions);
  1078.             }
  1079.             $this->translator->setlocale($request->query->get('lang') ?: DEFAULT_LOCALE);
  1080.             $url NCM_PUBLIC_PORTAL_URL 'api/ncm/internal/marine-reports';
  1081.             $forwardQuery $request->query->all();
  1082.             unset($forwardQuery['lang']);
  1083.             if ($forwardQuery !== []) {
  1084.                 $url .= (str_contains($url'?') ? '&' '?') . http_build_query($forwardQuery);
  1085.             }
  1086.             $response $this->httpClient->request('GET'$url, [
  1087.                 'timeout' => 120,
  1088.                 'headers' => ['Accept' => 'application/json'],
  1089.             ]);
  1090.             $status $response->getStatusCode();
  1091.             $body $response->getContent(false);
  1092.             if ($status 200 || $status >= 300) {
  1093.                 $this->logger->error('Marine reports upstream HTTP ' $status ' for ' $url);
  1094.                 return $this->json([
  1095.                     'success' => false,
  1096.                     'message' => $this->translator->trans('marine_reports_fetch_failed'),
  1097.                     'httpStatus' => $status,
  1098.                 ], $status >= 400 && $status 600 $status 502);
  1099.             }
  1100.             $decoded json_decode($bodytrue);
  1101.             if (!\is_array($decoded)) {
  1102.                 return $this->json([
  1103.                     'success' => false,
  1104.                     'message' => $this->translator->trans('marine_reports_invalid_upstream_json'),
  1105.                 ], 502);
  1106.             }
  1107.             $envelope $this->marineReportService->buildEnvelope($decoded$url);
  1108.             if ($envelope === null) {
  1109.                 return $this->json([
  1110.                     'success' => false,
  1111.                     'message' => $this->translator->trans('marine_reports_envelope_failed'),
  1112.                 ], 422);
  1113.             }
  1114.             return $this->json($envelope);
  1115.         } catch (\Throwable $ex) {
  1116.             $this->logger->error('Marine reports fetch: ' $ex->getMessage());
  1117.             return $this->json([
  1118.                 'success' => false,
  1119.                 'message' => $this->translator->trans('marine_reports_fetch_failed'),
  1120.             ], 502);
  1121.         }
  1122.     }
  1123.     /**
  1124.      * @Route("/publish-10-day-forecast-report", name="api_ncm_report_publish_10_day_forecast", methods={"POST"})
  1125.      */
  1126.     public function publish10DayForecastReport(Request $requestUserInterface $user)
  1127.     {
  1128.         try {
  1129.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1130.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1131.                 return $this->json($permissions401);
  1132.             } elseif ($permissions['success'] === false) {
  1133.                 return $this->json($permissions);
  1134.             }
  1135.             $params  json_decode($request->getContent(), true);
  1136.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1137.             // Perform parameter validation here
  1138.             // || !isset($params['locations'])
  1139.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
  1140.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  1141.             }
  1142.             if (isset($params['organizations'])) {
  1143.                 if (!is_array($params['organizations'])) {
  1144.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  1145.                 }
  1146.             }
  1147.             if (isset($params['channels'])) {
  1148.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  1149.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  1150.                 }
  1151.                 if (in_array('email'$params['channels'])) {
  1152.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  1153.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  1154.                     }
  1155.                 }
  1156.                 if (in_array('twitter'$params['channels'])) {
  1157.                     if (!isset($params['xCaption']) || empty($params['xCaption'])) {
  1158.                         throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
  1159.                     }
  1160.                 }
  1161.             }
  1162.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  1163.             return $this->json($result);
  1164.         } catch (\Exception $ex) {
  1165.             $this->logger->error($ex->getMessage());
  1166.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1167.         }
  1168.     }
  1169.     /**
  1170.      * @Route("/publish-red-sea-report", name="api_ncm_report_publish_red_sea", methods={"POST"})
  1171.      */
  1172.     public function publishRedSeaReport(Request $requestUserInterface $user)
  1173.     {
  1174.         try {
  1175.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1176.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1177.                 return $this->json($permissions401);
  1178.             } elseif ($permissions['success'] === false) {
  1179.                 return $this->json($permissions);
  1180.             }
  1181.             $params  json_decode($request->getContent(), true);
  1182.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1183.             // Perform parameter validation here
  1184.             // || !isset($params['locations'])
  1185.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
  1186.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  1187.             }
  1188.             if (isset($params['organizations'])) {
  1189.                 if (!is_array($params['organizations'])) {
  1190.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  1191.                 }
  1192.             }
  1193.             if (isset($params['channels'])) {
  1194.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  1195.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  1196.                 }
  1197.                 if (in_array('email'$params['channels'])) {
  1198.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  1199.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  1200.                     }
  1201.                 }
  1202.                 if (in_array('twitter'$params['channels'])) {
  1203.                     if (!isset($params['xCaption']) || empty($params['xCaption'])) {
  1204.                         throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
  1205.                     }
  1206.                 }
  1207.             }
  1208.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  1209.             return $this->json($this->finalizeModerationPublishResult($result$user));
  1210.         } catch (\Exception $ex) {
  1211.             $this->logger->error($ex->getMessage());
  1212.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1213.         }
  1214.     }
  1215.     /**
  1216.      * @Route("/publish-custom-weather-report", name="api_ncm_report_publish_custom_weather", methods={"POST"})
  1217.      */
  1218.     public function publishCustomWeatherReport(Request $requestUserInterface $user)
  1219.     {
  1220.         try {
  1221.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1222.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1223.                 return $this->json($permissions401);
  1224.             } elseif ($permissions['success'] === false) {
  1225.                 return $this->json($permissions);
  1226.             }
  1227.             $params  json_decode($request->getContent(), true);
  1228.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1229.             // Perform parameter validation here
  1230.             // || !isset($params['locations'])
  1231.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
  1232.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  1233.             }
  1234.             if (isset($params['organizations'])) {
  1235.                 if (!is_array($params['organizations'])) {
  1236.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  1237.                 }
  1238.             }
  1239.             if (isset($params['channels'])) {
  1240.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  1241.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  1242.                 }
  1243.                 if (in_array('email'$params['channels'])) {
  1244.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  1245.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  1246.                     }
  1247.                 }
  1248.                 if (in_array('twitter'$params['channels'])) {
  1249.                     if (!isset($params['xCaption']) || empty($params['xCaption'])) {
  1250.                         throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
  1251.                     }
  1252.                 }
  1253.             }
  1254.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  1255.             return $this->json($result);
  1256.         } catch (\Exception $ex) {
  1257.             $this->logger->error($ex->getMessage());
  1258.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1259.         }
  1260.     }
  1261.     /**
  1262.      * @Route("/publish-mashaer-weather-report", name="api_ncm_report_publish_mashaer_weather", methods={"POST"})
  1263.      */
  1264.     public function publishMashaerWeatherReport(Request $requestUserInterface $user)
  1265.     {
  1266.         try {
  1267.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1268.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1269.                 return $this->json($permissions401);
  1270.             } elseif ($permissions['success'] === false) {
  1271.                 return $this->json($permissions);
  1272.             }
  1273.             $params  json_decode($request->getContent(), true);
  1274.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1275.             // Perform parameter validation here
  1276.             // || !isset($params['locations'])
  1277.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
  1278.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  1279.             }
  1280.             if (isset($params['organizations'])) {
  1281.                 if (!is_array($params['organizations'])) {
  1282.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  1283.                 }
  1284.             }
  1285.             if (isset($params['channels'])) {
  1286.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  1287.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  1288.                 }
  1289.                 if (in_array('email'$params['channels'])) {
  1290.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  1291.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  1292.                     }
  1293.                 }
  1294.                 if (in_array('twitter'$params['channels'])) {
  1295.                     if (!isset($params['xCaption']) || empty($params['xCaption'])) {
  1296.                         throw new \Exception($this->translator->trans('xCaption should be non empty'), 400);
  1297.                     }
  1298.                 }
  1299.             }
  1300.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  1301.             return $this->json($result);
  1302.         } catch (\Exception $ex) {
  1303.             $this->logger->error($ex->getMessage());
  1304.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1305.         }
  1306.     }
  1307.     /**
  1308.      * @Route("/get-city-list", name="api_ncm_report_get_city_list")
  1309.      */
  1310.     public function getCityListAction(Request $request)
  1311.     {
  1312.         try {
  1313.             $result = [];
  1314.             $lang = ($request->headers->has('lang')) ? $request->headers->get('lang') : "en";
  1315.             $params  json_decode($request->getContent(), true);
  1316.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1317.             $reportTypeId $params['report_type_id'] ?? null;
  1318.             $cities = new \Pimcore\Model\DataObject\City\Listing();
  1319.             if ($reportTypeId) {
  1320.                 $cities->setCondition("reportType REGEXP CONCAT('(^|,)', REPLACE('" $reportTypeId "', ',', '|'), '(,|$)')");
  1321.             } else {
  1322.                 $db \Pimcore\Db::get();
  1323.                 $selectedLocalities $db->fetchAllAssociative("SELECT oo_id  FROM `object_query_ReportType` WHERE (`isAutomaticReport` = 0)");
  1324.                 $ooIds array_column($selectedLocalities'oo_id');
  1325.                 $cities->setCondition("reportType REGEXP CONCAT('(^|,)', REPLACE('" implode(','$ooIds) . "', ',', '|'), '(,|$)')");
  1326.             }
  1327.             $cities->setOrderKey('orderId');
  1328.             $cities->setOrder('asc');
  1329.             $cities->load();
  1330.             if ($cities->getCount() > 0) {
  1331.                 foreach ($cities as $city) {
  1332.                     $result[] = [
  1333.                         "id" => $city->getId(),
  1334.                         "name" => $city->getCityName($lang),
  1335.                         "nameEn" => $city->getCityName('en'),
  1336.                         "nameAr" => $city->getCityName('ar'),
  1337.                         "lat" => $city->getLatitude(),
  1338.                         "long" => $city->getLongitude(),
  1339.                         "googlePlaceName" => $city->getGooglePlaceName(),
  1340.                     ];
  1341.                 }
  1342.                 return $this->json(["success" => true"data" => $result]);
  1343.             }
  1344.             return $this->json(["success" => false"message" => $this->translator->trans("no_city_is_available")]);
  1345.         } catch (\Exception $ex) {
  1346.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1347.         }
  1348.     }
  1349.     /**
  1350.      * @Route("/list-report", name="api_ncm_report_list_report", methods={"POST"})
  1351.      */
  1352.     public function getReportListAction(Request $requestPaginatorInterface $paginatorUserInterface $user)
  1353.     {
  1354.         try {
  1355.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1356.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1357.                 return $this->json($permissions401);
  1358.             } elseif ($permissions['success'] === false) {
  1359.                 return $this->json($permissions);
  1360.             }
  1361.             $params  json_decode($request->getContent(), true);
  1362.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1363.             if (!isset($params['page']) || !isset($params['limit'])) {
  1364.                 throw new \Exception('Missing required page_no or page_limit');
  1365.             }
  1366.             $report_type = isset($params['report_type']) ? $params['report_type'] : null;
  1367.             $lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
  1368.             $page $params['page'];
  1369.             $limit $params['limit'];
  1370.             $result $this->reportModel->reportList($params$page$limit$this->translator$paginator$report_type$user$langfalse);
  1371.             return $this->json($result);
  1372.         } catch (\Exception $ex) {
  1373.             $this->logger->error($ex->getMessage());
  1374.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1375.         }
  1376.     }
  1377.     /**
  1378.      * @Route("/list-reports-by-type", name="api_ncm_report_list_reports_by_type", methods={"POST"})
  1379.      */
  1380.     public function listReportsByType(Request $requestPaginatorInterface $paginatorUserInterface $user)
  1381.     {
  1382.         try {
  1383.             // $permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
  1384.             // if (isset($permissions['code']) && $permissions['code'] === 401) {
  1385.             //     return $this->json($permissions, 401);
  1386.             // } elseif ($permissions['success'] === false) {
  1387.             //     return $this->json($permissions);
  1388.             // }
  1389.             $params  json_decode($request->getContent(), true);
  1390.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1391.             if (!isset($params['page']) || !isset($params['limit'])) {
  1392.                 throw new \Exception('Missing required page or limit');
  1393.             }
  1394.             // Getting current JWT Token 
  1395.             $decodedJwtToken null;
  1396.             if ($this->tokenStorageInterface->getToken()) {
  1397.                 $decodedJwtToken $this->jwtManager->decode($this->tokenStorageInterface->getToken());
  1398.             }
  1399.             // Array to store permissions
  1400.             $allowedReportTypes = [];
  1401.             // Check if the permissions are true and store them in the array
  1402.             $permissionsList = [
  1403.                 'view_red_sea_report',
  1404.                 'view_arabian_gulf_report',
  1405.                 'view_10_day_forecast_report',
  1406.                 'view_custom_weather_report',
  1407.                 'view_advance_custom_weather_report',
  1408.                 'view_mashaer_weather_report',
  1409.                 'view_today_weather_report',
  1410.                 'view_alert_forecast_report'
  1411.             ];
  1412.             // Loop through each permission and check if it's true
  1413.             foreach ($permissionsList as $permission) {
  1414.                 $permissionStatus $this->userPermission->getUserPermissions($decodedJwtToken$this->translator);
  1415.                 if (isset($permissionStatus['grants'][$permission]) && $permissionStatus['grants'][$permission] === true) {
  1416.                     // Convert permission names to report type keys
  1417.                     $reportTypeKey '';
  1418.                     switch ($permission) {
  1419.                         case 'view_arabian_gulf_report':
  1420.                             $reportTypeKey 'arabian-gulf-report';
  1421.                             break;
  1422.                         case 'view_red_sea_report':
  1423.                             $reportTypeKey 'red-sea-report';
  1424.                             break;
  1425.                         case 'view_custom_weather_report':
  1426.                             $reportTypeKey 'custom-weather-report';
  1427.                             break;
  1428.                         case 'view_10_day_forecast_report':
  1429.                             $reportTypeKey '10-day-forecast-report';
  1430.                             break;
  1431.                         case 'view_mashaer_weather_report':
  1432.                             $reportTypeKey 'mashaer-weather-report';
  1433.                             break;
  1434.                         case 'view_advance_custom_weather_report':
  1435.                             $reportTypeKey 'advance-custom-weather-report';
  1436.                             break;
  1437.                         case 'view_today_weather_report':
  1438.                             $reportTypeKey 'today-weather-report';
  1439.                             break;
  1440.                         case 'view_alert_forecast_report':
  1441.                             $reportTypeKey ALERT_FORECAST_REPORT_TYPE_KEY;
  1442.                             break;
  1443.                     }
  1444.                     if (!empty($reportTypeKey)) {
  1445.                         $allowedReportTypes[] = $reportTypeKey;
  1446.                     }
  1447.                 }
  1448.             }
  1449.             $params['allowedReportTypes'] = $allowedReportTypes;
  1450.             $params['decodedJwtToken'] = $decodedJwtToken;
  1451.             $params['userPermission'] = $this->userPermission;
  1452.             $result $this->reportModel->listReportsByType($params$this->translator$paginator);
  1453.             return $this->json($result);
  1454.         } catch (\Exception $ex) {
  1455.             $this->logger->error($ex->getMessage());
  1456.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1457.         }
  1458.     }
  1459.     /**
  1460.      * @Route("/view-10-day-forecast-report", name="api_ncm_report_view_10_day_forecast_report", methods={"POST"})
  1461.      */
  1462.     public function view10DayForecastReport(Request $requestPaginatorInterface $paginatorUserInterface $user)
  1463.     {
  1464.         try {
  1465.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1466.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1467.                 return $this->json($permissions401);
  1468.             } elseif ($permissions['success'] === false) {
  1469.                 return $this->json($permissions);
  1470.             }
  1471.             $params  json_decode($request->getContent(), true);
  1472.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1473.             if (!isset($params['page']) || !isset($params['limit'])) {
  1474.                 throw new \Exception('Missing required page_no or page_limit');
  1475.             }
  1476.             $report_type = isset($params['report_type']) ? $params['report_type'] : null;
  1477.             $lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
  1478.             $page $params['page'];
  1479.             $limit $params['limit'];
  1480.             $result $this->reportModel->reportList($params$page$limit$this->translator$paginator$report_type$user$langfalse);
  1481.             return $this->json($result);
  1482.         } catch (\Exception $ex) {
  1483.             $this->logger->error($ex->getMessage());
  1484.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1485.         }
  1486.     }
  1487.     /**
  1488.      * @Route("/view-red-sea-report", name="api_ncm_report_view_red_sea_report", methods={"POST"})
  1489.      */
  1490.     public function viewRedSeaReport(Request $requestPaginatorInterface $paginatorUserInterface $user)
  1491.     {
  1492.         try {
  1493.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1494.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1495.                 return $this->json($permissions401);
  1496.             } elseif ($permissions['success'] === false) {
  1497.                 return $this->json($permissions);
  1498.             }
  1499.             $params  json_decode($request->getContent(), true);
  1500.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1501.             if (!isset($params['page']) || !isset($params['limit'])) {
  1502.                 throw new \Exception('Missing required page_no or page_limit');
  1503.             }
  1504.             $report_type = isset($params['report_type']) ? $params['report_type'] : null;
  1505.             $lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
  1506.             $page $params['page'];
  1507.             $limit $params['limit'];
  1508.             $result $this->reportModel->reportList($params$page$limit$this->translator$paginator$report_type$user$langfalse);
  1509.             return $this->json($result);
  1510.         } catch (\Exception $ex) {
  1511.             $this->logger->error($ex->getMessage());
  1512.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1513.         }
  1514.     }
  1515.     /**
  1516.      * @Route("/view-custom-weather-report", name="api_ncm_report_view_custom_weather_report", methods={"POST"})
  1517.      */
  1518.     public function viewCustomWeatherReport(Request $requestPaginatorInterface $paginatorUserInterface $user)
  1519.     {
  1520.         try {
  1521.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1522.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1523.                 return $this->json($permissions401);
  1524.             } elseif ($permissions['success'] === false) {
  1525.                 return $this->json($permissions);
  1526.             }
  1527.             $params  json_decode($request->getContent(), true);
  1528.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1529.             if (!isset($params['page']) || !isset($params['limit'])) {
  1530.                 throw new \Exception('Missing required page_no or page_limit');
  1531.             }
  1532.             $report_type = isset($params['report_type']) ? $params['report_type'] : null;
  1533.             $lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
  1534.             $page $params['page'];
  1535.             $limit $params['limit'];
  1536.             $result $this->reportModel->reportList($params$page$limit$this->translator$paginator$report_type$user$langfalse);
  1537.             return $this->json($result);
  1538.         } catch (\Exception $ex) {
  1539.             $this->logger->error($ex->getMessage());
  1540.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1541.         }
  1542.     }
  1543.     /**
  1544.      * @Route("/view-mashaer-weather-report", name="api_ncm_report_view_mashaer_weather_report", methods={"POST"})
  1545.      */
  1546.     public function viewMashaerWeatherReport(Request $requestPaginatorInterface $paginatorUserInterface $user)
  1547.     {
  1548.         try {
  1549.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1550.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1551.                 return $this->json($permissions401);
  1552.             } elseif ($permissions['success'] === false) {
  1553.                 return $this->json($permissions);
  1554.             }
  1555.             $params  json_decode($request->getContent(), true);
  1556.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1557.             if (!isset($params['page']) || !isset($params['limit'])) {
  1558.                 throw new \Exception('Missing required page_no or page_limit');
  1559.             }
  1560.             $report_type = isset($params['report_type']) ? $params['report_type'] : null;
  1561.             $lang = isset($params['lang']) ? $params['lang'] : DEFAULT_LOCALE;
  1562.             $page $params['page'];
  1563.             $limit $params['limit'];
  1564.             $result $this->reportModel->reportList($params$page$limit$this->translator$paginator$report_type$user$langfalse);
  1565.             return $this->json($result);
  1566.         } catch (\Exception $ex) {
  1567.             $this->logger->error($ex->getMessage());
  1568.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1569.         }
  1570.     }
  1571.     /**
  1572.      * @Route("/generate-report-pdf", name="api_ncm_report_generate_report_pdf", methods={"POST"})
  1573.      */
  1574.     public function generateReportPdf(Request $requestUserInterface $user)
  1575.     {
  1576.         try {
  1577.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1578.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1579.                 return $this->json($permissions401);
  1580.             } elseif ($permissions['success'] === false) {
  1581.                 return $this->json($permissions);
  1582.             }
  1583.             $params  json_decode($request->getContent(), true);
  1584.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1585.             $result $this->reportModel->generatePdfReport($request$user$this->snappy$this->translator);
  1586.             return $this->json($result);
  1587.         } catch (\Exception $ex) {
  1588.             $this->logger->error($ex->getMessage());
  1589.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1590.         }
  1591.     }
  1592.     /**
  1593.      * @Route("/get-report-types", name="api_ncm_report_get_report_types", methods={"POST"})
  1594.      */
  1595.     public function getReportTypes(Request $requestUserInterface $user)
  1596.     {
  1597.         try {
  1598.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1599.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1600.                 return $this->json($permissions401);
  1601.             } elseif ($permissions['success'] === false) {
  1602.                 return $this->json($permissions);
  1603.             }
  1604.             if (!$user) {
  1605.                 throw new \Exception('User is not authenticated');
  1606.             }
  1607.             $params  json_decode($request->getContent(), true);
  1608.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1609.             if (!isset($params['automatic'])) {
  1610.                 throw new \Exception('missing_required_parameters');
  1611.             }
  1612.             $result = [];
  1613.             $automatic $params['automatic'] ? true false;
  1614.             $reportTypes = new \Pimcore\Model\DataObject\ReportType\Listing();
  1615.             $reportTypes->setCondition('isAutomaticReport = ?', [$automatic]);
  1616.             $reportTypes->load();
  1617.             if ($reportTypes->getCount() > 0) {
  1618.                 foreach ($reportTypes as $reportType) {
  1619.                     $result[] = [
  1620.                         "id" => $reportType->getId(),
  1621.                         "key" => $reportType->getReportKey(),
  1622.                         "nameEn" => $reportType->getName('en'),
  1623.                         "nameAr" => $reportType->getName('ar'),
  1624.                         "descriptionEn" => $reportType->getDescription('en'),
  1625.                         "descriptionAr" => $reportType->getDescription('ar'),
  1626.                         "titleEn" => $reportType->getTitle('en'),
  1627.                         "titleAr" => $reportType->getTitle('ar'),
  1628.                         "automatic" => $reportType->getIsAutomaticReport()
  1629.                     ];
  1630.                 }
  1631.                 return $this->json(["success" => true"data" => $result]);
  1632.             }
  1633.             return $this->json(["success" => false"message" => $this->translator->trans("no_reportType_is_available")]);
  1634.         } catch (\Exception $ex) {
  1635.             $this->logger->error($ex->getMessage());
  1636.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1637.         }
  1638.     }
  1639.     /**
  1640.      * @Route("/get-weather-params-list", name="api_ncm_report_get_weather_params_list", methods={"POST"})
  1641.      */
  1642.     public function getWeatherParamsListAction(Request $request)
  1643.     {
  1644.         try {
  1645.             $result = [];
  1646.             $lang = ($request->headers->has('lang')) ? $request->headers->get('lang') : "en";
  1647.             $params  json_decode($request->getContent(), true);
  1648.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1649.             if (!isset($params['report_type_id'])) {
  1650.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  1651.             }
  1652.             $reportTypeId $params['report_type_id'];
  1653.             $parameters = new \Pimcore\Model\DataObject\ReportWeatherParameters\Listing();
  1654.             $parameters->setCondition("reportType REGEXP CONCAT('(^|,)', REPLACE('" $reportTypeId "', ',', '|'), '(,|$)')");
  1655.             $parameters->load();
  1656.             if ($parameters->getCount() > 0) {
  1657.                 foreach ($parameters as $paramter) {
  1658.                     $result[] = [
  1659.                         "id" => $paramter->getId(),
  1660.                         "nameEn" => $paramter->getName('en'),
  1661.                         "nameAr" => $paramter->getName('ar'),
  1662.                         "meteoMaticsKey" => $paramter->getMeteoMaticsKey(),
  1663.                         "units" => $paramter->getUnits(),
  1664.                         "unitTitle" => $paramter->getUnitTitle()
  1665.                     ];
  1666.                 }
  1667.                 return $this->json(["success" => true"data" => $result]);
  1668.             }
  1669.             return $this->json(["success" => false"message" => $this->translator->trans("no_weather_parameter_is_available")]);
  1670.         } catch (\Exception $ex) {
  1671.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1672.         }
  1673.     }
  1674.     /**
  1675.      * @Route("/generate-excel", name="api_ncm_report_generate_excel")
  1676.      */
  1677.     public function generateExcelReport(Request $requestUserInterface $user)
  1678.     {
  1679.         $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1680.         if (isset($permissions['code']) && $permissions['code'] === 401) {
  1681.             return $this->json($permissions401);
  1682.         } elseif ($permissions['success'] === false) {
  1683.             return $this->json($permissions);
  1684.         }
  1685.         $params  json_decode($request->getContent(), true);
  1686.         $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1687.         if (!isset($params['id'])) {
  1688.             throw new \Exception('missing_required_parameters');
  1689.         }
  1690.         $report Report::getById($params['id'], true);
  1691.         if (!$report instanceof Report) {
  1692.             throw new \Exception('no_report_found');
  1693.         }
  1694.         // Replace this with the actual data you want to use
  1695.         $jsonData json_decode($report->getJsonData(), true);
  1696.         // Create a new PhpSpreadsheet instance
  1697.         $spreadsheet = new Spreadsheet();
  1698.         // Create a worksheet
  1699.         $sheet $spreadsheet->getActiveSheet();
  1700.         // Determine headers dynamically based on the first item in the data
  1701.         $firstItem reset($jsonData);
  1702.         $parameters $firstItem['parameters'] ?? [];
  1703.         $headers = [$this->translator->trans('Location'),  $this->translator->trans('Latitude'),  $this->translator->trans('Longitude'),  $this->translator->trans('Date')]; // Initialize headers with common columns
  1704.         // Extract parameter names and add them to headers
  1705.         foreach ($parameters as $parameter) {
  1706.             if ($parameter['parameter'] == 'prob_precip_24h:p') {
  1707.                 $headers[] = $this->translator->trans('Precipitation Probability (%)');
  1708.             } elseif ($parameter['parameter'] == 'precip_24h:mm') {
  1709.                 $headers[] = $this->translator->trans('Precipitation Amount (mm)');
  1710.             } elseif ($parameter['parameter'] == 'wind_speed_mean_10m_24h:kmh') {
  1711.                 $headers[] = $this->translator->trans('Wind Speed (km/h)');
  1712.             } elseif ($parameter['parameter'] == 't_2m:C') {
  1713.                 $headers[] =  $this->translator->trans('Temperature (°C)');
  1714.             } else {
  1715.                 $headers[] = $parameter['parameter'];
  1716.             }
  1717.         }
  1718.         // Add headers to the worksheet
  1719.         foreach ($headers as $index => $header) {
  1720.             $sheet->setCellValueByColumnAndRow($index 11$header);
  1721.         }
  1722.         // Style headers
  1723.         $headerStyle = [
  1724.             'font' => [
  1725.                 'bold' => true,
  1726.                 'color' => ['rgb' => 'FFFFFF'], // White text
  1727.             ],
  1728.             'fill' => [
  1729.                 'fillType' => Fill::FILL_SOLID,
  1730.                 'startColor' => ['rgb' => '16365c'], // Blue background
  1731.             ],
  1732.             'alignment' => [
  1733.                 'horizontal' => Alignment::HORIZONTAL_CENTER,
  1734.                 'vertical' => Alignment::VERTICAL_CENTER,
  1735.             ],
  1736.         ];
  1737.         $sheet->getStyle('A1:H1')->applyFromArray($headerStyle);
  1738.         // Initialize row counter
  1739.         $row 2;
  1740.         foreach ($jsonData as $item) {
  1741.             // Extract city-related data
  1742.             $cityData = [$item['city'] ?? ''$item['lat'] ?? ''$item['lon'] ?? ''];
  1743.             // Loop through each date for all parameters
  1744.             foreach ($item['parameters'][0]['dates'] as $dateIndex => $date) {
  1745.                 // Initialize row data with city-related data and date
  1746.                 $rowData array_merge($cityData, [date('Y-m-d'strtotime($date['date']))]);
  1747.                 // Loop through each parameter
  1748.                 foreach ($item['parameters'] as $parameter) {
  1749.                     // Check if the value is set for the current date, otherwise set it to 0
  1750.                     $value = isset($parameter['dates'][$dateIndex]['value']) ? $parameter['dates'][$dateIndex]['value'] : 0;
  1751.                     // Add parameter value for the current date to the row data
  1752.                     $rowData[] = $value;
  1753.                 }
  1754.                 // Set cell values explicitly
  1755.                 foreach ($rowData as $colIndex => $cellValue) {
  1756.                     $sheet->setCellValueByColumnAndRow($colIndex 1$row$cellValue);
  1757.                 }
  1758.                 // Increment the row counter
  1759.                 $row++;
  1760.             }
  1761.         }
  1762.         foreach (range('A'$sheet->getHighestColumn()) as $columnID) {
  1763.             $sheet->getColumnDimension($columnID)->setAutoSize(true);
  1764.         }
  1765.         // Save the Excel file to a temporary file
  1766.         $tempFile tempnam(sys_get_temp_dir(), 'weather_report');
  1767.         $writer = new Xlsx($spreadsheet);
  1768.         $writer->save($tempFile);
  1769.         // Store the file in Pimcore Assets
  1770.         $assetFolder '/report/ExcelReports'// Change this to your actual asset folder path
  1771.         $filename $user->getId() . '_' time() . '_' 'weather_report.xlsx';
  1772.         $assetPath =  API_BASE_URL '/' $assetFolder '/' $filename;
  1773.         // Create a new asset
  1774.         $asset = new \Pimcore\Model\Asset();
  1775.         $asset->setFilename($filename);
  1776.         $asset->setData(file_get_contents($tempFile));
  1777.         $asset->setParent(\Pimcore\Model\Asset\Service::createFolderByPath($assetFolder));
  1778.         $asset->save();
  1779.         // Remove the temporary file
  1780.         unlink($tempFile);
  1781.         $report->setAsset($asset);
  1782.         $report->setIsHistorical(true);
  1783.         $report->save();
  1784.         // Return the path to the stored Excel file in Pimcore
  1785.         return $this->json(['success' => true'data' => $assetPath]);
  1786.     }
  1787.     /**
  1788.      * @Route("/generate-historical-report", name="api_ncm_report_generate_historical_report", methods={"POST"})
  1789.      */
  1790.     public function generateHistoricalReport(Request $request): JsonResponse
  1791.     {
  1792.         try {
  1793.             $response = [];
  1794.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1795.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1796.                 return $this->json($permissions401);
  1797.             } elseif ($permissions['success'] === false) {
  1798.                 return $this->json($permissions);
  1799.             }
  1800.             $params json_decode($request->getContent(), true);
  1801.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1802.             if (
  1803.                 !isset($params['from_date']) ||
  1804.                 !isset($params['to_date']) ||
  1805.                 !isset($params['hours']) ||
  1806.                 !isset($params['parameters'])  ||
  1807.                 !isset($params['locations'])
  1808.             ) {
  1809.                 throw new \Exception('Missing required parameters');
  1810.             }
  1811.             if (empty($params['parameters'] || !is_array($params['parameters']))) {
  1812.                 throw new \Exception('Parameters should be non empty array');
  1813.             }
  1814.             if (empty($params['locations'] || !is_array($params['locations']))) {
  1815.                 throw new \Exception('Locations should be non empty array');
  1816.             }
  1817.             if ($params['to_date'] > date('Y-m-d'strtotime(Carbon::now()))) {
  1818.                 $daysadd date('Y-m-d'strtotime(Carbon::now()->addDays('17')));
  1819.                 if ($params['to_date'] >= $daysadd) {
  1820.                     throw new \Exception('End date limit exceeded');
  1821.                 }
  1822.             }
  1823.             $model = isset($params['model']) ? $params['model'] : 'mix';
  1824.             $redisKey md5('generate_city_report-' $params['from_date'] . '-' $params['to_date'] . '-' $params['hours'] . '-' implode('_'$params['locations'])) . '-' implode('_'$params['parameters']) . '-' $model;
  1825.             $data $this->redisCache->get($redisKey);
  1826.             if (!$data) {
  1827.                 $cities = new \Pimcore\Model\DataObject\Location\Listing();
  1828.                 if (!empty($params['locations'])) {
  1829.                     $cities->setCondition('o_id IN (?)', [$params['locations']]);
  1830.                 }
  1831.                 $cities->load();
  1832.                 if ($cities->getCount() > 0) {
  1833.                     $params['coordinates'] = []; // Initialize an empty array for coordinates
  1834.                     $result = [];
  1835.                     $citiesArr = [];
  1836.                     foreach ($cities as $city) {
  1837.                         $cityLocations json_decode($city->getCoordinates(), true);
  1838.                         foreach ($cityLocations as $coordinates) {
  1839.                             $long number_format($coordinates[1], 6'.''');
  1840.                             $lat number_format($coordinates[0], 6'.''');
  1841.                             $params['coordinates'][] = $coordinates;
  1842.                             $citiesArr[$lat '|' $long] =  $city->getName();
  1843.                         }
  1844.                     }
  1845.                     $result $this->meteomaticsWeatherService->getReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $params['hours'], $model$params['parameters'], $this->translator$citiesArr$params);
  1846.                     $response[] = $result;
  1847.                     $jsonResponse = ['success' => true'data' => $response];
  1848.                     $this->redisCache->set($redisKey$jsonResponseREDIS_CACHE_TIME);
  1849.                     return $this->json($jsonResponse);
  1850.                 } else {
  1851.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  1852.                 }
  1853.             } else {
  1854.                 return $this->json($data);
  1855.             }
  1856.         } catch (\Exception $ex) {
  1857.             $this->logger->error($ex->getMessage());
  1858.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1859.         }
  1860.     }
  1861.     /**
  1862.      * @Route("/get-report-detail", name="api_ncm_report_get_report_detail")
  1863.      */
  1864.     public function getReportDetails(Request $request)
  1865.     {
  1866.         try {
  1867.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1868.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1869.                 return $this->json($permissions401);
  1870.             } elseif ($permissions['success'] === false) {
  1871.                 return $this->json($permissions);
  1872.             }
  1873.             $params json_decode($request->getContent(), true);
  1874.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1875.             if (
  1876.                 !isset($params['id'])
  1877.             ) {
  1878.                 throw new \Exception('Missing required parameters');
  1879.             }
  1880.             $report Report::getById($params['id'], true);
  1881.             if (!$report instanceof Report) {
  1882.                 throw new \Exception('no_report_found');
  1883.             } else {
  1884.                 $asset_path $report->getAsset()?->getPath() . $report->getAsset()?->getFileName() ? API_BASE_URL $report->getAsset()?->getPath() . $report->getAsset()?->getFileName() : '';
  1885.                 $data = [
  1886.                     'name' => $report->getCreatedBy()?->getId(),
  1887.                     'email' => $report->getCreatedBy()?->getEmail(),
  1888.                     'jsonData' => json_decode($report->getJsonData(), true),
  1889.                     'asset_path' => $asset_path,
  1890.                     'createdOn' => $report->getCreatedOn(),
  1891.                 ];
  1892.             }
  1893.             return $this->json(['success' => true'data' => $data]);
  1894.         } catch (\Exception $ex) {
  1895.             $this->logger->error($ex->getMessage());
  1896.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1897.         }
  1898.     }
  1899.     /**
  1900.      * @Route("/get-latest-report", name="api_ncm_report_get_latest_report")
  1901.      */
  1902.     public function getLatestReport(Request $requestUserInterface $user)
  1903.     {
  1904.         try {
  1905.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1906.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1907.                 return $this->json($permissions401);
  1908.             } elseif ($permissions['success'] === false) {
  1909.                 return $this->json($permissions);
  1910.             }
  1911.             if (!$user) {
  1912.                 throw new \Exception('User is not authenticated');
  1913.             }
  1914.             $params json_decode($request->getContent(), true);
  1915.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1916.             $reportType = (isset($params['report_type']) && !empty($params['report_type'])) ? $params['report_type'] : '10-day-forecast-report';
  1917.             $result $this->reportModel->getLatestReport($reportType$this->translator);
  1918.             return $this->json($result);
  1919.         } catch (\Exception $ex) {
  1920.             $this->logger->error($ex->getMessage());
  1921.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1922.         }
  1923.     }
  1924.     /**
  1925.      * @Route("/generate-manned-report", name="api_ncm_report_generate_manned_report" , methods={"POST"})
  1926.      */
  1927.     public function generateMannedReport(Request $requestUserInterface $user): JsonResponse
  1928.     {
  1929.         try {
  1930.             $response = [];
  1931.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1932.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1933.                 return $this->json($permissions401);
  1934.             } elseif ($permissions['success'] === false) {
  1935.                 return $this->json($permissions);
  1936.             }
  1937.             $params json_decode($request->getContent(), true);
  1938.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1939.             $requiredParameters = [
  1940.                 'titleEn',
  1941.                 'titleAr',
  1942.                 'descriptionEn',
  1943.                 'descriptionAr',
  1944.                 'channels',
  1945.                 'report_type_id',
  1946.                 'fileName',
  1947.                 'file',
  1948.                 'type'
  1949.             ];
  1950.             foreach ($requiredParameters as $param) {
  1951.                 if (!isset($params[$param]) || empty($params[$param])) {
  1952.                     $missingParams[] = $param;
  1953.                 }
  1954.             }
  1955.             if (!empty($missingParams)) {
  1956.                 // Throw an exception with a message that includes the missing parameters
  1957.                 $parameterList implode(", "$missingParams);
  1958.                 return $this->json(['success' => false'message' => sprintf($this->translator->trans("missing_required_parameters: %s"), $parameterList)]);
  1959.             }
  1960.             // Check if 'type' is either 'video' or 'pdf'
  1961.             if (isset($params['type']) && !in_array($params['type'], ['video''pdf'])) {
  1962.                 return $this->json(['success' => false'message' => $this->translator->trans("Type must be either video or pdf")]);
  1963.             }
  1964.             $result $this->reportModel->createMannedReport($request$this->translator$params$user);
  1965.             return $this->json($result);
  1966.         } catch (\Exception $ex) {
  1967.             $this->logger->error($ex->getMessage());
  1968.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1969.         }
  1970.     }
  1971.     /**
  1972.      * @Route("/get-automatic-reports", name="api_ncm_report_get_automatic_reports")
  1973.      */
  1974.     public function getAutomaticReports(Request $requestUserInterface $userPaginatorInterface $paginator)
  1975.     {
  1976.         try {
  1977.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  1978.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  1979.                 return $this->json($permissions401);
  1980.             } elseif ($permissions['success'] === false) {
  1981.                 return $this->json($permissions);
  1982.             }
  1983.             if (!$user) {
  1984.                 throw new \Exception('User is not authenticated');
  1985.             }
  1986.             $params  json_decode($request->getContent(), true);
  1987.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  1988.             if (!isset($params['page']) || !isset($params['limit']) || !isset($params['lang'])) {
  1989.                 throw new \Exception('Missing required parameters');
  1990.             }
  1991.             $search = isset($params['search']) ? $params['search'] : null;
  1992.             $orderKey = isset($params['orderKey']) ? $params['orderKey'] : 'createdOn';
  1993.             $order = isset($params['order']) ? $params['order'] : 'desc';
  1994.             $result $this->reportModel->listAutomaticReports($params$user$search$orderKey$order$this->translator$paginator);
  1995.             return $this->json($result);
  1996.         } catch (\Exception $ex) {
  1997.             $this->logger->error($ex->getMessage());
  1998.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  1999.         }
  2000.     }
  2001.     /**
  2002.      * @Route("/generate-automatic-report-pdf", name="api_ncm_report_generate_automatic_report_pdf")
  2003.      */
  2004.     public function generateAutomaticReportPdf(Request $requestUserInterface $user)
  2005.     {
  2006.         try {
  2007.             $result $this->reportModel->generatePdfReport($request$user$this->snappy$this->translator);
  2008.             return  $this->json($result);
  2009.         } catch (\Exception $ex) {
  2010.             $this->logger->error($ex->getMessage());
  2011.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2012.         }
  2013.     }
  2014.     /**
  2015.      * @Route("/generate-history-report-pdf", name="api_ncm_report_generate_history_report_pdf")
  2016.      */
  2017.     public function generateHistoryReportPdf(Request $requestUserInterface $user)
  2018.     {
  2019.         try {
  2020.             return $this->getEWSHistoryPDF($request$user'pdf/history_report_pdf.html.twig'$this->translator'_history_report.pdf');
  2021.         } catch (\Exception $ex) {
  2022.             p_r($ex->getMessage());
  2023.             exit;
  2024.             $this->logger->error($ex->getMessage());
  2025.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2026.         }
  2027.     }
  2028.     public function getEWSHistoryPDF($request$user$template$translator$report_type)
  2029.     {
  2030.         $params  json_decode($request->getContent(), true);
  2031.         if (!isset($params['id'])) {
  2032.             return $this->json(["success" => false"message" => $translator->trans("missing_required_parameters")]);
  2033.         }
  2034.         $ewsId $params['id'];
  2035.         $lang = isset($params['lang']) ? $params['lang'] : "en";
  2036.         $ews \Pimcore\Model\DataObject::getById($ewsId);
  2037.         if (!$ews instanceof EwsNotification) {
  2038.             return $this->json(["success" => false"message" => $translator->trans("no_report_found")]);
  2039.         }
  2040.         $ewsNotificationModel = new EwsNotificationModel();
  2041.         $fileName '_ews_history_report.pdf';
  2042.         $reportPath '/report/ReportPdf/' $params['id'];
  2043.         $template 'pdf/history_report_pdf.html.twig';
  2044.         $data $ewsNotificationModel->viewNotification($params$translator);
  2045.         $parameter = [
  2046.             'data' => $data,
  2047.             'reportTitleEn' => "EWS Notification History",
  2048.             'template' => $template,
  2049.             'lang' => $lang
  2050.         ];
  2051.         // return $this->render('pdf/automatic_report_pdf_template_copy.html.twig',$parameter);
  2052.         $pdf \App\Lib\Utility::generatePdf($parameter$this->snappy);
  2053.         // $tempFilePath = tempnam(sys_get_temp_dir(), 'image_');
  2054.         // file_put_contents($tempFilePath, $pdf);
  2055.         // Create a BinaryFileResponse and set headers
  2056.         //    $response = new BinaryFileResponse($tempFilePath);
  2057.         //    $response->headers->set('Content-Type', 'application/pdf');
  2058.         //    $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, 'image.pdf');
  2059.         // Return the response
  2060.         //    return $responseReport;
  2061.         $asset \App\Lib\Utility::createAsset($pdf'Alert_History_Report_' date('Y-m-d') . '-' $params['id'] . '.pdf'$reportPath);
  2062.         $pdfasset '';
  2063.         if ($asset instanceof Asset) {
  2064.             $pdfasset API_BASE_URL $asset->getPath() . $asset->getFilename();
  2065.         }
  2066.         return $this->json(['success' => true'data' => $pdfasset]);
  2067.     }
  2068.     public function getPdfReport($request$user$template$translator$report_type)
  2069.     {
  2070.         $params  json_decode($request->getContent(), true);
  2071.         if (!isset($params['id'])) {
  2072.             return $this->json(["success" => false"message" => $translator->trans("missing_required_parameters")]);
  2073.         }
  2074.         $report Report::getById($params['id'], true);
  2075.         $lang = isset($params['lang']) ? $params['lang'] : "en";
  2076.         if (!$report instanceof Report) {
  2077.             return $this->json(["success" => false"message" => $translator->trans("no_report_found")]);
  2078.         }
  2079.         $asset $lang == 'ar' $report->getAssetAr() : $report->getAsset();
  2080.         if ($asset) {
  2081.             $pdfasset API_BASE_URL $asset->getPath() . $asset->getFilename();
  2082.             return $this->json(['success' => true'data' => $pdfasset]);
  2083.         }
  2084.         //$template=$report->getReportType()?->getKey() == 'MannForecastReport'?'pdf/report_pdf_template.html.twig':'pdf/automatic_report_pdf_template.html.twig';
  2085.         $fileName '_custom_weather_report.pdf';
  2086.         $reportPath '/report/ReportPdf';
  2087.         if ($report->getReportType()?->getKey() == 'MannForecastReport') {
  2088.             $template =  'pdf/report_pdf_template.html.twig';
  2089.         } elseif ($report->getReportType()?->getKey() == 'advance-custom-weather-report') {
  2090.             $template 'pdf/advance_custom_report_pdf_template.html.twig';
  2091.             // $fileName = '_advance_custom_weather_report.pdf';
  2092.             $reportPath '/report/advanceCustomReportPdf';
  2093.         } else {
  2094.             $template 'pdf/automatic_report_pdf_template.html.twig';
  2095.         }
  2096.         $parameter = [
  2097.             'data' => $report,
  2098.             'reportTitleEn' => $report->getReportTitle('en'),
  2099.             'reportTitleAr' => $report->getReportTitle('ar'),
  2100.             'reportDescriptionEn' => $report->getDescription('en'),
  2101.             'reportDescriptionAr' => $report->getDescription('ar'),
  2102.             'reportDisclaimerEn' => $report->getReportDisclaimer('en'), // new 
  2103.             'reportDisclaimerAr' => $report->getReportDisclaimer('ar'), // new 
  2104.             'additionalNoteEn' => $report->getAdditionalNote('en'), // new 
  2105.             'additionalNoteAr' => $report->getAdditionalNote('ar'), // new 
  2106.             'stateOfTheSeaEn' => $report->getStateOfTheSea('en'), // new 
  2107.             'stateOfTheSeaAr' => $report->getStateOfTheSea('ar'), // new 
  2108.             'waveHeightEn' => $report->getWaveHeight('en'), // new 
  2109.             'waveHeightAr' => $report->getWaveHeight('ar'), // new 
  2110.             'surfaceWindEn' => $report->getSurfaceWind('en'), // new 
  2111.             'surfaceWindAr' => $report->getSurfaceWind('ar'), // new 
  2112.             'publishOnPdf' => $report->getPublishOnPdf() == true true false// new 
  2113.             'reportType' => $report->getReportType()?->getReportkey(),
  2114.             'template' => $template,
  2115.             'lang' => $lang
  2116.         ];
  2117.         // return $this->render('pdf/automatic_report_pdf_template_copy.html.twig',$parameter);
  2118.         $pdf \App\Lib\Utility::generatePdf($parameter$this->snappy);
  2119.         // $tempFilePath = tempnam(sys_get_temp_dir(), 'image_');
  2120.         // file_put_contents($tempFilePath, $pdf);
  2121.         // Create a BinaryFileResponse and set headers
  2122.         //    $response = new BinaryFileResponse($tempFilePath);
  2123.         //    $response->headers->set('Content-Type', 'application/pdf');
  2124.         //    $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, 'image.pdf');
  2125.         // Return the response
  2126.         //    return $response;
  2127.         // set the asset path and title
  2128.         $pdfReportName $report->getReportType() ? $report->getReportType()->getName($lang) : $report_type;
  2129.         $pdfReportName $pdfReportName '_' date('d-m-Y') . '.pdf';
  2130.         $reportPath $reportPath '/' $report->getId();
  2131.         $asset \App\Lib\Utility::createAsset($pdf,  $pdfReportName$reportPath);
  2132.         $pdfasset '';
  2133.         if ($asset instanceof Asset) {
  2134.             $pdfasset API_BASE_URL $asset->getPath() . $asset->getFilename();
  2135.         }
  2136.         if ($lang == 'ar') {
  2137.             $report->setAssetAr($asset);
  2138.         } else {
  2139.             $report->setAsset($asset);
  2140.         }
  2141.         $report->save();
  2142.         return $this->json(['success' => true'data' => $pdfasset]);
  2143.     }
  2144.     /**
  2145.      * @Route("/get-today-weather-report", name="api_ncm_report_get_today_weather_report")
  2146.      */
  2147.     public function getTodayWeatherReports(Request $requestUserInterface $userPaginatorInterface $paginator)
  2148.     {
  2149.         try {
  2150.             if (!$user) {
  2151.                 throw new \Exception('User is not authenticated');
  2152.             }
  2153.             $params  json_decode($request->getContent(), true);
  2154.             if (!isset($params['page']) || !isset($params['limit']) || !isset($params['lang'])) {
  2155.                 throw new \Exception('Missing required parameters');
  2156.             }
  2157.             $result $this->reportModel->getTodayWeatherReports($params$this->translator$paginator);
  2158.             return $this->json($result);
  2159.         } catch (\Exception $ex) {
  2160.             $this->logger->error($ex->getMessage());
  2161.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2162.         }
  2163.     }
  2164.     /**
  2165.      * @Route("/preview-advance-custom-report", name="api_ncm_report_preview_advance_custom_report" , methods={"POST"})
  2166.      */
  2167.     public function previewAdvanceCustomReport(Request $request): JsonResponse
  2168.     {
  2169.         try {
  2170.             $response = [];
  2171.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2172.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2173.                 return $this->json($permissions401);
  2174.             } elseif ($permissions['success'] === false) {
  2175.                 return $this->json($permissions);
  2176.             }
  2177.             $params json_decode($request->getContent(), true);
  2178.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2179.             $locations = (isset($params['locations']) && !empty($params['locations'])) || (isset($params['weather_stations']) && !empty($params['weather_stations']));
  2180.             if (
  2181.                 !isset($params['from_date']) ||
  2182.                 !isset($params['to_date']) ||
  2183.                 !isset($params['parameters'])  ||
  2184.                 !isset($locations)
  2185.             ) {
  2186.                 throw new \Exception('Missing required parameters');
  2187.             }
  2188.             if (empty($params['parameters'] || !is_array($params['parameters']))) {
  2189.                 throw new \Exception('Parameters should be non empty array');
  2190.             }
  2191.             if ((!isset($params['locations']) || empty($params['locations']) || !is_array($params['locations'])) && (!isset($params['weather_stations']) || empty($params['weather_stations']) || !is_array($params['weather_stations']))) {
  2192.                 throw new \Exception('Either locations or weather_stations should be non empty array');
  2193.             }
  2194.             // Set default values for new parameters
  2195.             $params['isAWSReport'] = isset($params['isAWSReport']) ? $params['isAWSReport'] : false;
  2196.             $params['hours'] = isset($params['hours']) ? $params['hours'] : 24;
  2197.             $params['weather_stations'] = isset($params['weather_stations']) ? $params['weather_stations'] : [];
  2198.             $params['locations'] = isset($params['locations']) ? $params['locations'] : [];
  2199.             $model = isset($params['model']) ? $params['model'] : 'mix';
  2200.             // $redisKey = md5('generate_city_report-' . $params['from_date'] . '-' . $params['to_date'] . '-' . $params['hours'] . '-' . ($params['isAWSReport'] ? 'aws_' . implode('_', $params['weather_stations']) : implode('_', $params['locations']))) . '-' . implode('_', $params['parameters']) . '-' . $model;
  2201.             // $data = $this->redisCache->get($redisKey);
  2202.             // if (!$data) {
  2203.             $params['coordinates'] = []; // Initialize an empty array for coordinates
  2204.             $result = [];
  2205.             $citiesArr = [];
  2206.             if ($params['isAWSReport']) {
  2207.                 // Handle AWS Weather Station report
  2208.                 $stations = new \Pimcore\Model\DataObject\WeatherStations\Listing();
  2209.                 if (!empty($params['weather_stations'])) {
  2210.                     $stations->setCondition('o_id IN (?)', [$params['weather_stations']]);
  2211.                 }
  2212.                 $stations->load();
  2213.                 if ($stations->getCount() > 0) {
  2214.                     $hashArr = [];
  2215.                     foreach ($stations as $station) {
  2216.                         $params['coordinates'][] = [$station->getlatitude(), $station->getlongitude()];
  2217.                         $hash $station->getHash();
  2218.                         // Append the coordinates for each station
  2219.                         $long number_format($station->getlongitude(), 6'.''');
  2220.                         $lat number_format($station->getlatitude(), 6'.''');
  2221.                         $citiesArr[$hash]["en"] = $station->getName("en");
  2222.                         $citiesArr[$hash]["ar"] = $station->getName("ar");
  2223.                         $citiesArr[$hash]["lat"] = $lat;
  2224.                         $citiesArr[$hash]["long"] = $long;
  2225.                         $hashArr[] = $hash;
  2226.                     }
  2227.                     $result $this->meteomaticsWeatherService->getWeatherStationReportData($params['from_date'], $params['to_date'], $params['parameters'], $hashArrfalse$this->translator'PT' $params['hours'] . 'H'$citiesArr);
  2228.                 } else {
  2229.                     return $this->json(['success' => true'message' => $this->translator->trans('no_weather_station_found')]);
  2230.                 }
  2231.             } else {
  2232.                 // Handle regular Governorate report
  2233.                 $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  2234.                 if (isset($params['locations']) && !empty($params['locations'])) {
  2235.                     $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  2236.                 }
  2237.                 $cities->load();
  2238.                 if ($cities->getCount() > 0) {
  2239.                     foreach ($cities as $city) {
  2240.                         $params['coordinates'][] = [$city->getLatitude(), $city->getLongitude()];
  2241.                         // Append the coordinates for each city
  2242.                         $long number_format($city->getLongitude(), 6'.''');
  2243.                         $lat number_format($city->getLatitude(), 6'.''');
  2244.                         $citiesArr[$lat '|' $long]["en"] =  $city->getName("en");
  2245.                         $citiesArr[$lat '|' $long]["ar"] =  $city->getName("ar");
  2246.                     }
  2247.                     $result $this->meteomaticsWeatherService->getReportForecastData($params['coordinates'], $params['from_date'], $params['to_date'], $params['hours'], $model$params['parameters'], $this->translator$citiesArrarray_merge($params, ['skip_service_cache' => true]));
  2248.                 } else {
  2249.                     return $this->json(['success' => true'message' => $this->translator->trans('no_city_found')]);
  2250.                 }
  2251.             }
  2252.             $response[] = $result;
  2253.             $jsonResponse = ['success' => true'data' => $response];
  2254.             // $this->redisCache->set($redisKey, $jsonResponse, REDIS_CACHE_TIME);
  2255.             return $this->json($jsonResponse);
  2256.             // } else {
  2257.             //     return $this->json($data);
  2258.             // }
  2259.         } catch (\Exception $ex) {
  2260.             $this->logger->error($ex->getMessage());
  2261.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2262.         }
  2263.     }
  2264.     /**
  2265.      * @Route("/publish-advance-custom-report", name="api_ncm_report_publish_advance_custom_report" , methods={"POST"})
  2266.      */
  2267.     public function publishAdvanceCustomReport(Request $requestUserInterface $user)
  2268.     {
  2269.         try {
  2270.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2271.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2272.                 return $this->json($permissions401);
  2273.             } elseif ($permissions['success'] === false) {
  2274.                 return $this->json($permissions);
  2275.             }
  2276.             $params  json_decode($request->getContent(), true);
  2277.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2278.             // Perform parameter validation here
  2279.             // || !isset($params['locations'])
  2280.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang'])) {
  2281.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  2282.             }
  2283.             if (isset($params['organizations'])) {
  2284.                 if (!is_array($params['organizations'])) {
  2285.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  2286.                 }
  2287.             }
  2288.             if (isset($params['channels'])) {
  2289.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  2290.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  2291.                 }
  2292.                 if (in_array('email'$params['channels'])) {
  2293.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  2294.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  2295.                     }
  2296.                 }
  2297.             }
  2298.             $result $this->reportModel->publishAdvanceCustomReport($user$params$this->translator$this->logger);
  2299.             return $this->json($this->finalizeModerationPublishResult($result$user));
  2300.         } catch (\Exception $ex) {
  2301.             $this->logger->error($ex->getMessage());
  2302.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2303.         }
  2304.     }
  2305.     /**
  2306.      * @Route("/archive-weather-report", name="api_ncm_report_archive_weather_report")
  2307.      */
  2308.     public function archiveWeatherReport(Request $requestUserInterface $user)
  2309.     {
  2310.         try {
  2311.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2312.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2313.                 return $this->json($permissions401);
  2314.             } elseif ($permissions['success'] === false) {
  2315.                 return $this->json($permissions);
  2316.             }
  2317.             if (!$user) {
  2318.                 throw new \Exception('User is not authenticated');
  2319.             }
  2320.             $params  json_decode($request->getContent(), true);
  2321.             if (!isset($params['report_id'])) {
  2322.                 throw new \Exception('Missing required parameters');
  2323.             }
  2324.             $result $this->reportModel->archiveWeatherReport($this->translator$user$params['report_id']);
  2325.             return $this->json($result);
  2326.         } catch (\Exception $ex) {
  2327.             $this->logger->error($ex->getMessage());
  2328.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2329.         }
  2330.     }
  2331.     /**
  2332.      * @Route("/delete-arabian-gulf-report", name="api_ncm_report_delete_arabian_gulf_report")
  2333.      */
  2334.     public function deleteArabianGulfReport(Request $requestUserInterface $user)
  2335.     {
  2336.         try {
  2337.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2338.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2339.                 return $this->json($permissions401);
  2340.             } elseif ($permissions['success'] === false) {
  2341.                 return $this->json($permissions);
  2342.             }
  2343.             if (!$user) {
  2344.                 throw new \Exception('User is not authenticated');
  2345.             }
  2346.             $params  json_decode($request->getContent(), true);
  2347.             if (!isset($params['report_id'])) {
  2348.                 throw new \Exception('Missing required parameters');
  2349.             }
  2350.             $result $this->reportModel->archiveWeatherReport($this->translator$user$params['report_id']);
  2351.             return $this->json($result);
  2352.         } catch (\Exception $ex) {
  2353.             $this->logger->error($ex->getMessage());
  2354.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2355.         }
  2356.     }
  2357.     /**
  2358.      * @Route("/delete-10-day-forecast-report", name="api_ncm_report_delete_10_day_forecast_report")
  2359.      */
  2360.     public function delete10DayForecastReport(Request $requestUserInterface $user)
  2361.     {
  2362.         try {
  2363.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2364.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2365.                 return $this->json($permissions401);
  2366.             } elseif ($permissions['success'] === false) {
  2367.                 return $this->json($permissions);
  2368.             }
  2369.             if (!$user) {
  2370.                 throw new \Exception('User is not authenticated');
  2371.             }
  2372.             $params  json_decode($request->getContent(), true);
  2373.             if (!isset($params['report_id'])) {
  2374.                 throw new \Exception('Missing required parameters');
  2375.             }
  2376.             $result $this->reportModel->archiveWeatherReport($this->translator$user$params['report_id']);
  2377.             return $this->json($result);
  2378.         } catch (\Exception $ex) {
  2379.             $this->logger->error($ex->getMessage());
  2380.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2381.         }
  2382.     }
  2383.     /**
  2384.      * @Route("/delete-red-sea-report", name="api_ncm_report_delete_red_sea_report")
  2385.      */
  2386.     public function deleteRedSeaReport(Request $requestUserInterface $user)
  2387.     {
  2388.         try {
  2389.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2390.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2391.                 return $this->json($permissions401);
  2392.             } elseif ($permissions['success'] === false) {
  2393.                 return $this->json($permissions);
  2394.             }
  2395.             if (!$user) {
  2396.                 throw new \Exception('User is not authenticated');
  2397.             }
  2398.             $params  json_decode($request->getContent(), true);
  2399.             if (!isset($params['report_id'])) {
  2400.                 throw new \Exception('Missing required parameters');
  2401.             }
  2402.             $result $this->reportModel->archiveWeatherReport($this->translator$user$params['report_id']);
  2403.             return $this->json($result);
  2404.         } catch (\Exception $ex) {
  2405.             $this->logger->error($ex->getMessage());
  2406.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2407.         }
  2408.     }
  2409.     /**
  2410.      * @Route("/delete-custom-weather-report", name="api_ncm_report_delete_custom_weather_report")
  2411.      */
  2412.     public function deleteCustomWeatherReport(Request $requestUserInterface $user)
  2413.     {
  2414.         try {
  2415.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2416.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2417.                 return $this->json($permissions401);
  2418.             } elseif ($permissions['success'] === false) {
  2419.                 return $this->json($permissions);
  2420.             }
  2421.             if (!$user) {
  2422.                 throw new \Exception('User is not authenticated');
  2423.             }
  2424.             $params  json_decode($request->getContent(), true);
  2425.             if (!isset($params['report_id'])) {
  2426.                 throw new \Exception('Missing required parameters');
  2427.             }
  2428.             $result $this->reportModel->archiveWeatherReport($this->translator$user$params['report_id']);
  2429.             return $this->json($result);
  2430.         } catch (\Exception $ex) {
  2431.             $this->logger->error($ex->getMessage());
  2432.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2433.         }
  2434.     }
  2435.     /**
  2436.      * @Route("/delete-mashaer-weather-report", name="api_ncm_report_delete_mashaer_weather_report")
  2437.      */
  2438.     public function deleteMashaerWeatherReport(Request $requestUserInterface $user)
  2439.     {
  2440.         try {
  2441.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2442.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2443.                 return $this->json($permissions401);
  2444.             } elseif ($permissions['success'] === false) {
  2445.                 return $this->json($permissions);
  2446.             }
  2447.             if (!$user) {
  2448.                 throw new \Exception('User is not authenticated');
  2449.             }
  2450.             $params  json_decode($request->getContent(), true);
  2451.             if (!isset($params['report_id'])) {
  2452.                 throw new \Exception('Missing required parameters');
  2453.             }
  2454.             $result $this->reportModel->archiveWeatherReport($this->translator$user$params['report_id']);
  2455.             return $this->json($result);
  2456.         } catch (\Exception $ex) {
  2457.             $this->logger->error($ex->getMessage());
  2458.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2459.         }
  2460.     }
  2461.     /**
  2462.      * @Route("/update-advance-custom-report", name="api_ncm_report_update_advance_custom_report" , methods={"POST"})
  2463.      */
  2464.     public function updateAdvanceCustomReport(Request $requestUserInterface $user)
  2465.     {
  2466.         try {
  2467.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2468.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2469.                 return $this->json($permissions401);
  2470.             } elseif ($permissions['success'] === false) {
  2471.                 return $this->json($permissions);
  2472.             }
  2473.             $params  json_decode($request->getContent(), true);
  2474.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2475.             // Perform parameter validation here
  2476.             // || !isset($params['locations'])
  2477.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
  2478.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  2479.             }
  2480.             if (isset($params['organizations'])) {
  2481.                 if (!is_array($params['organizations'])) {
  2482.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  2483.                 }
  2484.             }
  2485.             if (isset($params['channels'])) {
  2486.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  2487.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  2488.                 }
  2489.                 if (in_array('email'$params['channels'])) {
  2490.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  2491.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  2492.                     }
  2493.                 }
  2494.             }
  2495.             $result $this->reportModel->publishAdvanceCustomReport($user$params$this->translator$this->logger);
  2496.             return $this->json($this->finalizeModerationPublishResult($result$user));
  2497.         } catch (\Exception $ex) {
  2498.             $this->logger->error($ex->getMessage());
  2499.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2500.         }
  2501.     }
  2502.     /**
  2503.      * @Route("/update-report", name="api_ncm_report_update_report", methods={"POST"})
  2504.      */
  2505.     public function updateReport(Request $requestUserInterface $user)
  2506.     {
  2507.         try {
  2508.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2509.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2510.                 return $this->json($permissions401);
  2511.             } elseif ($permissions['success'] === false) {
  2512.                 return $this->json($permissions);
  2513.             }
  2514.             $params  json_decode($request->getContent(), true);
  2515.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2516.             // Perform parameter validation here
  2517.             // || !isset($params['locations'])
  2518.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
  2519.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  2520.             }
  2521.             if (isset($params['organizations'])) {
  2522.                 if (!is_array($params['organizations'])) {
  2523.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  2524.                 }
  2525.             }
  2526.             if (isset($params['channels'])) {
  2527.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  2528.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  2529.                 }
  2530.                 if (in_array('email'$params['channels'])) {
  2531.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  2532.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  2533.                     }
  2534.                 }
  2535.             }
  2536.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  2537.             return $this->json($result);
  2538.         } catch (\Exception $ex) {
  2539.             $this->logger->error($ex->getMessage());
  2540.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2541.         }
  2542.     }
  2543.     /**
  2544.      * @Route("/update-arabian-gulf-report", name="api_ncm_report_update_arabian_gulf_report", methods={"POST"})
  2545.      */
  2546.     public function updateArabianGulfReport(Request $requestUserInterface $user)
  2547.     {
  2548.         try {
  2549.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2550.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2551.                 return $this->json($permissions401);
  2552.             } elseif ($permissions['success'] === false) {
  2553.                 return $this->json($permissions);
  2554.             }
  2555.             $params  json_decode($request->getContent(), true);
  2556.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2557.             // Perform parameter validation here
  2558.             // || !isset($params['locations'])
  2559.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
  2560.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  2561.             }
  2562.             if (isset($params['organizations'])) {
  2563.                 if (!is_array($params['organizations'])) {
  2564.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  2565.                 }
  2566.             }
  2567.             if (isset($params['channels'])) {
  2568.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  2569.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  2570.                 }
  2571.                 if (in_array('email'$params['channels'])) {
  2572.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  2573.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  2574.                     }
  2575.                 }
  2576.             }
  2577.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  2578.             return $this->json($this->finalizeModerationPublishResult($result$user));
  2579.         } catch (\Exception $ex) {
  2580.             $this->logger->error($ex->getMessage());
  2581.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2582.         }
  2583.     }
  2584.     /**
  2585.      * @Route("/update-10-day-forecast-report", name="api_ncm_report_update_10_day_forecast_report", methods={"POST"})
  2586.      */
  2587.     public function update10DayForecastReport(Request $requestUserInterface $user)
  2588.     {
  2589.         try {
  2590.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2591.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2592.                 return $this->json($permissions401);
  2593.             } elseif ($permissions['success'] === false) {
  2594.                 return $this->json($permissions);
  2595.             }
  2596.             $params  json_decode($request->getContent(), true);
  2597.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2598.             // Perform parameter validation here
  2599.             // || !isset($params['locations'])
  2600.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
  2601.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  2602.             }
  2603.             if (isset($params['organizations'])) {
  2604.                 if (!is_array($params['organizations'])) {
  2605.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  2606.                 }
  2607.             }
  2608.             if (isset($params['channels'])) {
  2609.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  2610.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  2611.                 }
  2612.                 if (in_array('email'$params['channels'])) {
  2613.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  2614.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  2615.                     }
  2616.                 }
  2617.             }
  2618.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  2619.             return $this->json($result);
  2620.         } catch (\Exception $ex) {
  2621.             $this->logger->error($ex->getMessage());
  2622.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2623.         }
  2624.     }
  2625.     /**
  2626.      * @Route("/update-red-sea-report", name="api_ncm_report_update_red_sea_report", methods={"POST"})
  2627.      */
  2628.     public function updateRedSeaReport(Request $requestUserInterface $user)
  2629.     {
  2630.         try {
  2631.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2632.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2633.                 return $this->json($permissions401);
  2634.             } elseif ($permissions['success'] === false) {
  2635.                 return $this->json($permissions);
  2636.             }
  2637.             $params  json_decode($request->getContent(), true);
  2638.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2639.             // Perform parameter validation here
  2640.             // || !isset($params['locations'])
  2641.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
  2642.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  2643.             }
  2644.             if (isset($params['organizations'])) {
  2645.                 if (!is_array($params['organizations'])) {
  2646.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  2647.                 }
  2648.             }
  2649.             if (isset($params['channels'])) {
  2650.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  2651.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  2652.                 }
  2653.                 if (in_array('email'$params['channels'])) {
  2654.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  2655.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  2656.                     }
  2657.                 }
  2658.             }
  2659.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  2660.             return $this->json($this->finalizeModerationPublishResult($result$user));
  2661.         } catch (\Exception $ex) {
  2662.             $this->logger->error($ex->getMessage());
  2663.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2664.         }
  2665.     }
  2666.     /**
  2667.      * @Route("/update-custom-weather-report", name="api_ncm_report_update_custom_weather_report", methods={"POST"})
  2668.      */
  2669.     public function updateCustomWeatherReport(Request $requestUserInterface $user)
  2670.     {
  2671.         try {
  2672.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2673.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2674.                 return $this->json($permissions401);
  2675.             } elseif ($permissions['success'] === false) {
  2676.                 return $this->json($permissions);
  2677.             }
  2678.             $params  json_decode($request->getContent(), true);
  2679.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2680.             // Perform parameter validation here
  2681.             // || !isset($params['locations'])
  2682.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
  2683.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  2684.             }
  2685.             if (isset($params['organizations'])) {
  2686.                 if (!is_array($params['organizations'])) {
  2687.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  2688.                 }
  2689.             }
  2690.             if (isset($params['channels'])) {
  2691.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  2692.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  2693.                 }
  2694.                 if (in_array('email'$params['channels'])) {
  2695.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  2696.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  2697.                     }
  2698.                 }
  2699.             }
  2700.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  2701.             return $this->json($result);
  2702.         } catch (\Exception $ex) {
  2703.             $this->logger->error($ex->getMessage());
  2704.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2705.         }
  2706.     }
  2707.     /**
  2708.      * @Route("/update-mashaer-weather-report", name="api_ncm_report_update_mashaer_weather_report", methods={"POST"})
  2709.      */
  2710.     public function updateMashaerWeatherReport(Request $requestUserInterface $user)
  2711.     {
  2712.         try {
  2713.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2714.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2715.                 return $this->json($permissions401);
  2716.             } elseif ($permissions['success'] === false) {
  2717.                 return $this->json($permissions);
  2718.             }
  2719.             $params  json_decode($request->getContent(), true);
  2720.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2721.             // Perform parameter validation here
  2722.             // || !isset($params['locations'])
  2723.             if (!isset($params['data'])  || !isset($params['start_date']) || !isset($params['end_date']) || !isset($params['lang']) || !isset($params['report_id'])) {
  2724.                 return $this->json(['success' => false'message' =>  $this->translator->trans('missing_required_parameters')]);
  2725.             }
  2726.             if (isset($params['organizations'])) {
  2727.                 if (!is_array($params['organizations'])) {
  2728.                     throw new \Exception($this->translator->trans('Organizations should be non empty array'), 400);
  2729.                 }
  2730.             }
  2731.             if (isset($params['channels'])) {
  2732.                 if (!is_array($params['channels']) || empty($params['channels'])) {
  2733.                     throw new \Exception($this->translator->trans('Channels should be non empty array'), 400);
  2734.                 }
  2735.                 if (in_array('email'$params['channels'])) {
  2736.                     if (!isset($params['emails']) || !is_array($params['emails']) || empty($params['emails'])) {
  2737.                         throw new \Exception($this->translator->trans('Emails should be non empty array'), 400);
  2738.                     }
  2739.                 }
  2740.             }
  2741.             $result $this->reportModel->editReport($user$params$this->translator$this->logger);
  2742.             return $this->json($result);
  2743.         } catch (\Exception $ex) {
  2744.             $this->logger->error($ex->getMessage());
  2745.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2746.         }
  2747.     }
  2748.     /**
  2749.      * @Route("/get-centers", name="get_centeres", methods={"POST"})
  2750.      */
  2751.     public function getCenters(Request $requestUserInterface $userPaginatorInterface $paginator): JsonResponse
  2752.     {
  2753.         try {
  2754.             if (!$user) {
  2755.                 throw new \Exception('User is not authenticated');
  2756.             }
  2757.             $params json_decode($request->getContent(), true);
  2758.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2759.             if (empty($params['governorate_id'])) {
  2760.                 throw new \Exception("Governate id is required");
  2761.             }
  2762.             $result $this->reportModel->getCenters($params["governorate_id"], $params['lang']);
  2763.             return $this->json($result);
  2764.         } catch (\Exception $ex) {
  2765.             $this->logger->error($ex->getMessage());
  2766.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2767.         }
  2768.     }
  2769.     /**
  2770.      * @Route("/get-districts", name="get_districts", methods={"POST"})
  2771.      */
  2772.     public function getDistricts(Request $requestUserInterface $userPaginatorInterface $paginator): JsonResponse
  2773.     {
  2774.         try {
  2775.             if (!$user) {
  2776.                 throw new \Exception('User is not authenticated');
  2777.             }
  2778.             $params json_decode($request->getContent(), true);
  2779.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2780.             if (empty($params['governorate_id'])) {
  2781.                 throw new \Exception("Governate id is required");
  2782.             }
  2783.             $result $this->reportModel->getDistricts($params["governorate_id"], $params['lang']);
  2784.             return $this->json($result);
  2785.         } catch (\Exception $ex) {
  2786.             $this->logger->error($ex->getMessage());
  2787.             return $this->json(['success' => false'message' => $ex->getMessage()]);
  2788.         }
  2789.     }
  2790.     /**
  2791.      * @Route("/publish-alert-forecast-report", name="publish_alert_forecast_report", methods={"POST"})
  2792.      */
  2793.     public function publishAlertForecastReport(Request $requestUserInterface $user): JsonResponse
  2794.     {
  2795.         try {
  2796.             // Validate permissions
  2797.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2798.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2799.                 return $this->json($permissions401);
  2800.             } elseif ($permissions['success'] === false) {
  2801.                 return $this->json($permissions);
  2802.             }
  2803.             if (!$user) {
  2804.                 throw new \Exception('User is not authenticated');
  2805.             }
  2806.             // Decode the JSON request
  2807.             $params json_decode($request->getContent(), true);
  2808.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2809.             $requiredParameters = [
  2810.                 'titleEn',
  2811.                 'titleAr',
  2812.                 'descriptionEn',
  2813.                 'descriptionAr',
  2814.                 'regions',
  2815.                 'parameterId'
  2816.             ];
  2817.             $missingParams = [];
  2818.             foreach ($requiredParameters as $param) {
  2819.                 if (empty($params[$param])) {
  2820.                     $missingParams[] = $param;
  2821.                 }
  2822.             }
  2823.             if (!empty($missingParams)) {
  2824.                 $parameterList implode(", "$missingParams);
  2825.                 return $this->json(['success' => false'message' => $this->translator->trans("required parameters are missing in the request") . ": " $parameterList]);
  2826.             }
  2827.             $validationErrors $this->validateAlertForecastRegions($params['regions']);
  2828.             if (!empty($validationErrors)) {
  2829.                 return $this->json([
  2830.                     'success' => false,
  2831.                     'message' => $validationErrors
  2832.                 ]);
  2833.             }
  2834.             $emailChannelError $this->validateAlertForecastEmailChannel($params);
  2835.             if ($emailChannelError !== null) {
  2836.                 return $this->json(['success' => false'message' => $emailChannelError], 400);
  2837.             }
  2838.             $data = [];
  2839.             $data['titleEn'] = $params['titleEn'];
  2840.             $data['titleAr'] = $params['titleAr'];
  2841.             $data['descriptionEn'] = $params['descriptionEn'];
  2842.             $data['descriptionAr'] = $params['descriptionAr'];
  2843.             $data['regions'] = $params['regions'];
  2844.             $data['lang'] = $params['lang'];
  2845.             $data['user'] = $user;
  2846.             $data['channels'] = $params['channels'] ?? [];
  2847.             $data['parameterId'] = $params['parameterId'];
  2848.             $data['xCaption'] = $params['xCaption'] ?? null;
  2849.             $data['emails'] = $params['emails'] ?? [];
  2850.             $data['user_group_ids'] = $params['user_group_ids'] ?? [];
  2851.             $data['footerTitleEn'] = $params['footerTitleEn'] ?? '';
  2852.             $data['footerTitleAr'] = $params['footerTitleAr'] ?? '';
  2853.             $data['footerDescriptionEn'] = $params['footerDescriptionEn'] ?? '';
  2854.             $data['footerDescriptionAr'] = $params['footerDescriptionAr'] ?? '';
  2855.             // Step 3: Call the model function to handle report creation
  2856.             $result $this->reportModel->publishAlertForecastReport($data$user$this->translator);
  2857.             return $this->json($this->finalizeModerationPublishResult($result$user));
  2858.         } catch (\Exception $ex) {
  2859.             $this->logger->error($ex->getMessage());
  2860.             return $this->json(['success' => false'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
  2861.         }
  2862.     }
  2863.     /**
  2864.      * @Route("/update-alert-forecast-report", name="update_alert_forecast_report", methods={"POST"})
  2865.      */
  2866.     public function updateAlertForecastReport(Request $requestUserInterface $user): JsonResponse
  2867.     {
  2868.         try {
  2869.             // Validate permissions
  2870.             $permissions $this->userPermission->validateAPI($request$this->tokenStorageInterface$this->jwtManager$this->translator);
  2871.             if (isset($permissions['code']) && $permissions['code'] === 401) {
  2872.                 return $this->json($permissions401);
  2873.             } elseif ($permissions['success'] === false) {
  2874.                 return $this->json($permissions);
  2875.             }
  2876.             if (!$user) {
  2877.                 throw new \Exception('User is not authenticated');
  2878.             }
  2879.             // Decode the JSON request
  2880.             $params json_decode($request->getContent(), true);
  2881.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  2882.             $requiredParameters = [
  2883.                 'id',
  2884.                 'titleEn',
  2885.                 'titleAr',
  2886.                 'descriptionEn',
  2887.                 'descriptionAr',
  2888.                 'regions',
  2889.                 'parameterId'
  2890.             ];
  2891.             $missingParams = [];
  2892.             foreach ($requiredParameters as $param) {
  2893.                 if (empty($params[$param])) {
  2894.                     $missingParams[] = $param;
  2895.                 }
  2896.             }
  2897.             if (!empty($missingParams)) {
  2898.                 $parameterList implode(", "$missingParams);
  2899.                 return $this->json(['success' => false'message' => $this->translator->trans("required parameters are missing in the request") . ": " $parameterList]);
  2900.             }
  2901.             $validationErrors $this->validateAlertForecastRegions($params['regions']);
  2902.             if (!empty($validationErrors)) {
  2903.                 return $this->json([
  2904.                     'success' => false,
  2905.                     'message' => $validationErrors
  2906.                 ]);
  2907.             }
  2908.             $emailChannelError $this->validateAlertForecastEmailChannel($params);
  2909.             if ($emailChannelError !== null) {
  2910.                 return $this->json(['success' => false'message' => $emailChannelError], 400);
  2911.             }
  2912.             $data = [];
  2913.             $data['titleEn'] = $params['titleEn'];
  2914.             $data['titleAr'] = $params['titleAr'];
  2915.             $data['descriptionEn'] = $params['descriptionEn'];
  2916.             $data['descriptionAr'] = $params['descriptionAr'];
  2917.             $data['regions'] = $params['regions'];
  2918.             $data['lang'] = $params['lang'];
  2919.             $data['user'] = $user;
  2920.             $data['channels'] = $params['channels'] ?? [];
  2921.             $data['id'] = $params['id'];
  2922.             $data['xCaption'] = $params['xCaption'] ?? null;
  2923.             $data['parameterId'] = $params['parameterId'];
  2924.             $data['emails'] = $params['emails'] ?? [];
  2925.             $data['user_group_ids'] = $params['user_group_ids'] ?? [];
  2926.             $data['footerTitleEn'] = $params['footerTitleEn'] ?? '';
  2927.             $data['footerTitleAr'] = $params['footerTitleAr'] ?? '';
  2928.             $data['footerDescriptionEn'] = $params['footerDescriptionEn'] ?? '';
  2929.             $data['footerDescriptionAr'] = $params['footerDescriptionAr'] ?? '';
  2930.             // Step 3: Call the model function to handle report creation
  2931.             $result $this->reportModel->publishAlertForecastReport($data$user$this->translator);
  2932.             return $this->json($this->finalizeModerationPublishResult($result$user));
  2933.         } catch (\Exception $ex) {
  2934.             $this->logger->error($ex->getMessage());
  2935.             return $this->json(['success' => false'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
  2936.         }
  2937.     }
  2938.     private function validateAlertForecastEmailChannel(array $params): ?string
  2939.     {
  2940.         $channels $params['channels'] ?? [];
  2941.         if (!is_array($channels) || !in_array('email'$channelstrue)) {
  2942.             return null;
  2943.         }
  2944.         $hasEmails = isset($params['emails']) && is_array($params['emails']) && $params['emails'] !== [];
  2945.         $hasUserGroups = isset($params['user_group_ids']) && is_array($params['user_group_ids']) && $params['user_group_ids'] !== [];
  2946.         if (!$hasEmails && !$hasUserGroups) {
  2947.             return $this->translator->trans('alert_forecast_report_email_recipients_required');
  2948.         }
  2949.         return null;
  2950.     }
  2951.     private function validateAlertForecastRegions(array $regions): array
  2952.     {
  2953.         $errors = [];
  2954.         if (!is_array($regions) || $regions === []) {
  2955.             $errors[] = $this->translator->trans('regions is required');
  2956.             return $errors;
  2957.         }
  2958.         foreach ($regions as $regionIndex => $regionData) {
  2959.             $regionNumber $regionIndex 1;
  2960.             if (!is_array($regionData)) {
  2961.                 $errors[] = $this->translator->trans("Invalid region data at region index $regionNumber");
  2962.                 continue;
  2963.             }
  2964.             if (empty($regionData['regionId'])) {
  2965.                 $errors[] = $this->translator->trans("regionId is required at region index $regionNumber");
  2966.             }
  2967.             if (empty($regionData['governorates']) || !is_array($regionData['governorates'])) {
  2968.                 $errors[] = $this->translator->trans("governorates are required at region index $regionNumber");
  2969.                 continue;
  2970.             }
  2971.             foreach ($regionData['governorates'] as $governorateIndex => $governorateData) {
  2972.                 $governorateErrors $this->validateGovernorateData(
  2973.                     is_array($governorateData) ? $governorateData : [],
  2974.                     $regionNumber,
  2975.                     $governorateIndex 1
  2976.                 );
  2977.                 $errors array_merge($errors$governorateErrors);
  2978.             }
  2979.         }
  2980.         return $errors;
  2981.     }
  2982.     private function validateGovernorateData(array $governorateDataint $regionIndexint $governorateIndex): array
  2983.     {
  2984.         $errors = [];
  2985.         $location "region index $regionIndex, governorate index $governorateIndex";
  2986.         $requiredFields = [
  2987.             'governateIds' => 'governateIds',
  2988.             'categoryId' => 'categoryId',
  2989.             'startDate' => 'startDate',
  2990.             'endDate' => 'endDate',
  2991.             'timePeriod' => 'timePeriod',
  2992.         ];
  2993.         foreach ($requiredFields as $field => $localizedName) {
  2994.             if (empty($governorateData[$field])) {
  2995.                 $errors[] = $this->translator->trans("$localizedName is required at $location");
  2996.             }
  2997.         }
  2998.         if (isset($governorateData['governateIds']) && !empty($governorateData['governateIds'])) {
  2999.             $governorates explode(',', (string) $governorateData['governateIds']);
  3000.             if (count(array_filter(array_map('trim'$governorates))) < 1) {
  3001.                 $errors[] = $this->translator->trans("At least one governateId is required at $location");
  3002.             }
  3003.         }
  3004.         foreach (['centerIds''districtIds''otherLocationIds'] as $optionalField) {
  3005.             if (!isset($governorateData[$optionalField]) || $governorateData[$optionalField] === '' || $governorateData[$optionalField] === null) {
  3006.                 continue;
  3007.             }
  3008.             $ids array_filter(array_map('trim'explode(',', (string) $governorateData[$optionalField])));
  3009.             if ($ids === []) {
  3010.                 $errors[] = $this->translator->trans("Invalid $optionalField at $location");
  3011.             }
  3012.         }
  3013.         if (!isset($governorateData['categoryId']) || empty($governorateData['categoryId'])) {
  3014.             $errors[] = $this->translator->trans("category ID is required at $location");
  3015.         }
  3016.         if (isset($governorateData['startDate']) && !preg_match('/^\d{4}-\d{2}-\d{2}$/'$governorateData['startDate'])) {
  3017.             $errors[] = $this->translator->trans("Invalid startDate format at $location");
  3018.         }
  3019.         if (isset($governorateData['endDate']) && !preg_match('/^\d{4}-\d{2}-\d{2}$/'$governorateData['endDate'])) {
  3020.             $errors[] = $this->translator->trans("Invalid endDate format at $location");
  3021.         }
  3022.         if ($this->isTruthyAdditionalCondition($governorateData['additionalCondition'] ?? false)) {
  3023.             $additionalRequiredFields = [
  3024.                 'additionalConditionStartDate' => 'additionalConditionStartDate',
  3025.                 'additionalConditionEndDate' => 'additionalConditionEndDate',
  3026.             ];
  3027.             foreach ($additionalRequiredFields as $field => $localizedName) {
  3028.                 if (empty($governorateData[$field])) {
  3029.                     $errors[] = $this->translator->trans("$localizedName is required at $location when additionalCondition is true");
  3030.                 }
  3031.             }
  3032.             $hasConditionText = !empty($governorateData['additionalParameterConditionEn'])
  3033.                 || !empty($governorateData['additionalParameterConditionAr'])
  3034.                 || !empty($governorateData['additionalConditionText']);
  3035.             if (!$hasConditionText) {
  3036.                 $errors[] = $this->translator->trans("additionalParameterConditionEn or additionalParameterConditionAr is required at $location when additionalCondition is true");
  3037.             }
  3038.             foreach (['additionalConditionStartDate''additionalConditionEndDate'] as $dateField) {
  3039.                 if (
  3040.                     isset($governorateData[$dateField])
  3041.                     && $governorateData[$dateField] !== ''
  3042.                     && !preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $governorateData[$dateField])
  3043.                 ) {
  3044.                     $errors[] = $this->translator->trans("Invalid $dateField format at $location");
  3045.                 }
  3046.             }
  3047.         }
  3048.         return $errors;
  3049.     }
  3050.     private function isTruthyAdditionalCondition(mixed $value): bool
  3051.     {
  3052.         return filter_var($valueFILTER_VALIDATE_BOOLEANFILTER_NULL_ON_FAILURE) === true;
  3053.     }
  3054.      /**
  3055.      * @Route(
  3056.      *     "/alert-forecast-report-parameters",
  3057.      *     name="alert_forecast_report_parameters",
  3058.      *     methods={"POST"}
  3059.      * )
  3060.      */
  3061.     public function getAlertForecastParameters(Request $requestUserInterface $user)
  3062.     {
  3063.         try {
  3064.             // Validate permissions
  3065.             // $permissions = $this->userPermission->validateAPI($request, $this->tokenStorageInterface, $this->jwtManager, $this->translator);
  3066.             // if (isset($permissions['code']) && $permissions['code'] === 401) {
  3067.             //     return $this->json($permissions, 401);
  3068.             // } elseif ($permissions['success'] === false) {
  3069.             //     return $this->json($permissions);
  3070.             // }
  3071.             if (!$user) {
  3072.                 throw new \Exception('User is not authenticated');
  3073.             }
  3074.             
  3075.             $this->translator->setlocale(isset($params["lang"]) ? $params["lang"] : DEFAULT_LOCALE);
  3076.             $result $this->reportModel->getAlertForecastParameters($this->translator);
  3077.             return $this->json($result);
  3078.         } catch (\Exception $ex) {
  3079.             $this->logger->error($ex->getMessage());
  3080.             return $this->json(['success' => false'message' => $this->translator->trans(USER_ERROR_MESSAGE)]);
  3081.         }
  3082.     }
  3083.     /**
  3084.      * @Route( "/alert-forecast-report-risk-categories", name="alert_forecast_report_risk_categories",  methods={"POST"} )
  3085.      */
  3086.     public function getAlertForecastRiskCategories(Request $requestUserInterface $user)
  3087.     {
  3088.         try {
  3089.             if (!$user) {
  3090.                 throw new \Exception('User is not authenticated');
  3091.             }
  3092.             // Decode params BEFORE using them
  3093.             $params json_decode($request->getContent(), true) ?? [];
  3094.             // Now safe to access $params["lang"]
  3095.             $this->translator->setLocale($params["lang"] ?? DEFAULT_LOCALE);
  3096.             $result $this->reportModel->getAlertForecastRiskCategories($params);
  3097.             return $this->json($result);
  3098.         } catch (\Exception $ex) {
  3099.             $this->logger->error($ex->getMessage());
  3100.             return $this->json([
  3101.                 'success' => false,
  3102.                 'message' => $this->translator->trans(USER_ERROR_MESSAGE)
  3103.             ]);
  3104.         }
  3105.     }
  3106.     private function finalizeModerationPublishResult(array $resultUserInterface $user): array
  3107.     {
  3108.         if (empty($result['notificationType'])) {
  3109.             return $result;
  3110.         }
  3111.         $reportId = (int) ($result['reportId'] ?? $result['data'] ?? 0);
  3112.         if (empty($result['success'])) {
  3113.             $this->logger->warning(sprintf(
  3114.                 'Report moderation admin email skipped for report #%d: publish result was not successful',
  3115.                 $reportId
  3116.             ));
  3117.         } elseif (!$user instanceof Customer) {
  3118.             $this->logger->error(sprintf(
  3119.                 'Report moderation admin email skipped for report #%d: authenticated user is not a Customer instance',
  3120.                 $reportId
  3121.             ));
  3122.         } else {
  3123.             $this->reportModerationEmailService->notifyAdminReportSubmitted(
  3124.                 $reportId,
  3125.                 $result['reportTitleEn'] ?? '',
  3126.                 $result['reportTitleAr'] ?? '',
  3127.                 $user,
  3128.                 $result['notificationType'] === 'resubmitted'
  3129.             );
  3130.         }
  3131.         unset($result['notificationType'], $result['reportTitleEn'], $result['reportTitleAr']);
  3132.         return $result;
  3133.     }
  3134. }