src/Controller/ReportController.php line 48

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