src/Model/ReportLogModel.php line 435

Open in your IDE?
  1. <?php
  2. namespace App\Model;
  3. use Carbon\Carbon;
  4. use App\Lib\Utility;
  5. use App\Service\EmailService;
  6. use Pimcore\Model\DataObject;
  7. use App\Service\UserPermission;
  8. use Pimcore\Model\DataObject\Report;
  9. use Pimcore\Model\DataObject\Customer;
  10. use Pimcore\Model\DataObject\Location;
  11. use Symfony\Component\Process\Process;
  12. use Pimcore\Model\DataObject\ReportLog;
  13. use Pimcore\Model\DataObject\ReportType;
  14. use Pimcore\Model\DataObject\Organization;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\Process\Exception\ProcessFailedException;
  17. use Pimcore\Model\Asset;
  18. class ReportLogModel
  19. {
  20.     public function create(string $reportKey, array $param, array $response)
  21.     {
  22.         try {
  23.             // Define an array to store missing parameters
  24.             $missingParameters = [];
  25.             // Define an array of required parameters
  26.             $requiredParameters = [
  27.                 'type_of_report',
  28.                 'lon',
  29.                 'lat',
  30.                 'start_date',
  31.                 'end_date'
  32.             ];
  33.             // Check for missing required parameters
  34.             foreach ($requiredParameters as $parameter) {
  35.                 if (!isset($param[$parameter])) {
  36.                     $missingParameters[] = $parameter;
  37.                 }
  38.             }
  39.             // If there are missing parameters, return them
  40.             if (!empty($missingParameters)) {
  41.                 throw new \Exception("Missing parameters " implode(","$missingParameters));
  42.             }
  43.             if (!$response) {
  44.                 throw new \Exception("Response data not available");
  45.             }
  46.             $reportLog \Pimcore\Model\DataObject\ReportLog::getByReportKey($reportKeytrue);
  47.             if (!$reportLog) {
  48.                 $reportLog = new ReportLog();
  49.                 $reportLog->setKey($reportKey);
  50.                 $reportLog->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("ReportLog"));
  51.             }
  52.             $reportLog->setTypeOfReport($param['type_of_report']);
  53.             $reportLog->setLon($param['lon']);
  54.             $reportLog->setLat($param['lat']);
  55.             $reportLog->setStartDate(Carbon::parse(new \DateTime($param['start_date'])));
  56.             $reportLog->setEndDate(Carbon::parse(new \Datetime($param['end_date'])));
  57.             $reportLog->setIsPublished(true);
  58.             $reportLog->setPublished(true);
  59.             $reportLog->setReportKey($reportKey);
  60.             $reportLog->setResponseData(json_encode($response));
  61.             $reportLog->save();
  62.             return ["success" => true"data" => $reportLog->getReportKey()];
  63.         } catch (\Exception $ex) {
  64.             return ["success" => false"message" => $ex->getMessage()];
  65.         }
  66.     }
  67.     public function getReportLog($param)
  68.     {
  69.         $key $this->createKey($param);
  70.         $reportLog \Pimcore\Model\DataObject\ReportLog::getByReportKey($keytrue);
  71.         return $reportLog;
  72.     }
  73.     public function deleteReport($param)
  74.     {
  75.         $reportLog $this->getReportLog($param);
  76.         if ($reportLog) {
  77.             $reportLog->delete();
  78.             return true;
  79.         }
  80.         return false;
  81.     }
  82.     public function createKey($param)
  83.     {
  84.         return md5(implode(","$param));
  85.     }
  86.     public function editReport($user$params$translator$logger)
  87.     {
  88.         try {
  89.             $cityNames '';
  90.             if (!empty($params['locations'])) {
  91.                 // if governorate is true then get the cities from governorate else get the cities from city
  92.                 if (isset($params['is_governate']) && $params['is_governate']) {
  93.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  94.                     if (!empty($params['locations'])) {
  95.                         $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  96.                     }
  97.                 } else {
  98.                     $cities = new \Pimcore\Model\DataObject\City\Listing();
  99.                     if (!empty($params['locations'])) {
  100.                         $cities->setCondition('o_id IN (?)', [$params['locations']]);
  101.                     }
  102.                 }
  103.                 $cities->load();
  104.                 $locations = new \Pimcore\Model\DataObject\Location\Listing();
  105.                 $locations->setCondition('o_id IN (?)', [$params['locations']]);
  106.                 $locations->load();
  107.                 if ($cities->getCount() > 0) {
  108.                     foreach ($cities as $city) {
  109.                         // if governorate is true then get the cities from governorate else get the cities from city
  110.                         if ($params['is_governate']) {
  111.                             $nameEN $city->getName('en');
  112.                             $nameAR $city->getName('ar');
  113.                         } else {
  114.                             $nameEN $city->getCityName('en');
  115.                             $nameAR $city->getCityName('ar');
  116.                         }
  117.                         $cityNames .= !empty($nameEN) ? $nameEN ',' '';
  118.                         $cityNames .= !empty($nameAR) ? $nameAR ',' '';
  119.                     }
  120.                 } elseif ($locations->getCount() > 0) {
  121.                     foreach ($locations as $location) {
  122.                         $cityNames .= !empty($location->getName()) ? $location->getName() . ',' '';
  123.                     }
  124.                 } else {
  125.                     return ["success" => false"message" => "invalid_location"];
  126.                 }
  127.                 // Remove the trailing comma
  128.                 $cityNames rtrim($cityNames',');
  129.             }
  130.             if (isset($params['report_id'])) {
  131.                 $report Report::getById($params['report_id'], true);
  132.                 if (!$report instanceof Report) {
  133.                     return ["success" => false"message" => "invalid_report_id"];
  134.                 }
  135.             } else {
  136.                 $report = new Report();
  137.                 $report->setKey(\Pimcore\Model\Element\Service::getValidKey($user->getEmail() . time(), 'object'));
  138.                 $report->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("/Report/Report"));
  139.             }
  140.             $reportType '';
  141.             $report->setCreatedBy($user);
  142.             $report->setCreatedOn(Carbon::now());
  143.             $report->setStartDate(Carbon::parse(new \DateTime($params['start_date'])));
  144.             $report->setEndDate(Carbon::parse(new \Datetime($params['end_date'])));
  145.             $report->setSearchData($cityNames);
  146.             $report->setLang($params['lang']);
  147.             // $report->setEmail($user->getEmail());
  148.             $report->setJsonData(json_encode($params['data']));
  149.             if (isset($params['report_title'])) {
  150.                 $report->setReportTitle($params['report_title'], "en");
  151.             }
  152.             if (isset($params['report_title_ar'])) {
  153.                 $report->setReportTitle($params['report_title_ar'], "ar");
  154.             }
  155.             if (isset($params['surface_wind'])) {
  156.                 $report->setSurfaceWind($params['surface_wind'], "en");
  157.             }
  158.             if (isset($params['wave_height'])) {
  159.                 $report->setWaveHeight($params['wave_height'], "en");
  160.             }
  161.             if (isset($params['state_of_the_sea'])) {
  162.                 $report->setStateOfTheSea($params['state_of_the_sea'], "en");
  163.             }
  164.             if (isset($params['surface_wind_ar'])) {
  165.                 $report->setSurfaceWind($params['surface_wind_ar'], "ar");
  166.             }
  167.             if (isset($params['wave_height_ar'])) {
  168.                 $report->setWaveHeight($params['wave_height_ar'], "ar");
  169.             }
  170.             if (isset($params['state_of_the_sea_ar'])) {
  171.                 $report->setStateOfTheSea($params['state_of_the_sea_ar'], "ar");
  172.             }
  173.             if (isset($params['reportDisclaimerEn'])) {
  174.                 $report->setReportDisclaimer($params['reportDisclaimerEn'], "en");
  175.             }
  176.             if (isset($params['reportDisclaimerAr'])) {
  177.                 $report->setReportDisclaimer($params['reportDisclaimerAr'], "ar");
  178.             }
  179.             if (isset($params['additionalNoteEn'])) {
  180.                 $report->setAdditionalNote($params['additionalNoteEn'], "en");
  181.             }
  182.             if (isset($params['additionalNoteAr'])) {
  183.                 $report->setAdditionalNote($params['additionalNoteAr'], "ar");
  184.             }
  185.             if (isset($params['publishOnPdf'])) {
  186.                 $report->setPublishOnPdf($params['publishOnPdf'] == true  true false);
  187.             }
  188.             if (isset($params['is_governate']) && $params['is_governate']) {
  189.                 $report->setIsGovernorates(true);
  190.             }
  191.             if (!empty($params['xCaption'])) {
  192.                 $report->setTwitterDescription($params['xCaption']);
  193.             }
  194.             if (isset($params['report_type_id'])) {
  195.                 $reportType ReportType::getById($params['report_type_id'], true);
  196.                 if ($reportType instanceof ReportType) {
  197.                     $report->setReportType($reportType);
  198.                     // if ($reportType->getKey() != 'CustomWeatherReport' || $reportType->getKey() != 'MashaerWeatherReport') {
  199.                     //     $report->setForPublicPortal(true);
  200.                     //     $report->setForAjwaaPortal(true);
  201.                     // }
  202.                     if ($reportType->getReportKey() != 'arabian-gulf-report' || $reportType->getKey() != 'red-sea-report') {
  203.                         $report->setForPublicPortal(true);
  204.                         $report->setForAjwaaPortal(true);
  205.                     }
  206.                 }
  207.             }
  208.             if (!empty($params['organizations'])) {
  209.                 $selectedOrganizations = [];
  210.                 if ($params['organizations'][0] == 0) {
  211.                     $organizations = new Organization\Listing();
  212.                     if ($organizations->count() > 0) {
  213.                         foreach ($organizations as $organization) {
  214.                             if ($organization) {
  215.                                 $selectedOrganizations[] = $organization;
  216.                             }
  217.                         }
  218.                         $report->setOrganization($selectedOrganizations);
  219.                     }
  220.                 } else {
  221.                     foreach ($params['organizations'] as $organization) {
  222.                         $organizationObject Organization::getById($organizationtrue);
  223.                         if ($organizationObject) {
  224.                             $selectedOrganizations[] = $organizationObject;
  225.                         }
  226.                     }
  227.                     $report->setOrganization($selectedOrganizations);
  228.                 }
  229.             }
  230.             $emails "";
  231.             if (!empty($params['channels'])) {
  232.                 $channels = ['public_portal''ajwaa_portal''email''twitter''sms'];
  233.                 foreach ($params['channels'] as $channel) {
  234.                     if ($channel == 'public_portal') {
  235.                         $report->setForPublicPortal(true);
  236.                     } elseif ($channel == 'ajwaa_portal') {
  237.                         $report->setForAjwaaPortal(true);
  238.                         if (isset($params['send_email'])) {
  239.                             $report->setSendEmail(true);
  240.                         }
  241.                     } elseif ($channel == 'email') {
  242.                         $report->setForEmailChannel(true);
  243.                         $emails .= implode(","$params['emails']);
  244.                     } elseif ($channel == 'twitter') {
  245.                         $report->setForTwitterChannel(true);
  246.                     }
  247.                 }
  248.             }
  249.             $emailArray = [];
  250.             if (isset($params['user_group_ids']) && !empty($params['user_group_ids'])) {
  251.                 $userGroupIds = ($params['user_group_ids']);
  252.                 foreach ($userGroupIds as $userGroupId) {
  253.                     if ($userGroupId) {
  254.                         $userGroup \Pimcore\Model\DataObject\EwsAndReportUserGroup::getById($userGroupIdtrue);
  255.                         if ($userGroup instanceof \Pimcore\Model\DataObject\EwsAndReportUserGroup) {
  256.                             foreach (json_decode($userGroup->getJsonData()) as $currentUser) {
  257.                                 if (isset($currentUser->email)) {
  258.                                     $report->setForEmailChannel(true);
  259.                                     $emailArray[] = $currentUser->email;
  260.                                 }
  261.                             }
  262.                         }
  263.                     }
  264.                 }
  265.             }
  266.             if (!empty($emailArray)) {
  267.                 if (!empty($emails)) {
  268.                     $emails .= ',' implode(','$emailArray);
  269.                 } else {
  270.                     $emails implode(','$emailArray);
  271.                 }
  272.             }
  273.             $report->setEmails($emails);
  274.             $report->setPublished(true);
  275.             //schedule report
  276.             if (isset($params['is_schedule']) && $params['is_schedule'] && isset($params['schedule_date'])) {
  277.                 $report->setIsSchedule($params['is_schedule']);
  278.                 //  dd($params['schedule_date']);
  279.                 //  dd(Carbon::parse($params['schedule_date'], 'Asia/Riyadh'));
  280.                 //exit;
  281.                 $report->setScheduleDate(Carbon::parse($params['schedule_date'])->subHours(5));
  282.                 $report->setPublished(false);
  283.             } else {
  284.                 $report->setPublished(true);
  285.             }
  286.             // just to show title in public portal as description
  287.             $report->setShowPublicDescription(isset($params['show_public_description']) && $params['show_public_description'] === true);
  288.             // delete the existing pdf if report is updated
  289.             if (isset($params['report_id'])) {
  290.                 $pdfEn $report->getAsset();
  291.                 $pdfAr $report->getAssetAr();
  292.                 if ($pdfEn instanceof Asset) {
  293.                     $pdfEn->delete();
  294.                 }
  295.                 if ($pdfAr instanceof Asset) {
  296.                     $pdfAr->delete();
  297.                 }
  298.             }
  299.             $report->save();
  300.             //$phpPath = 'D:\laragon\bin\php\php-8.1.10-Win32-vs16-x64\php.exe'; // Adjust to the actual PHP path on your system
  301.             $consolePath 'bin\console'// Use backslashes for Windows paths
  302.             $commandArguments = ['bin/console''app:today-weather-pdf'];
  303.             if (!empty($reportType)) {
  304.                 if ($reportType->getKey() != 'CustomWeatherReport' || $reportType->getKey() != 'MashaerWeatherReport') {
  305.                     $process = new Process($commandArguments);
  306.                     $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
  307.                     try {
  308.                         $process->mustRun();
  309.                         $logger->info("Today Weather command executed successfully: " $process->getOutput());
  310.                         // p_r("Today Weather command executed successfully: " . $process->getOutput());exit;
  311.                         $result['success'] = true;
  312.                         $result['message'] = $process->getOutput();
  313.                     } catch (ProcessFailedException $exception) {
  314.                         $logger->error("Today Weather command failed: " $exception->getMessage());
  315.                         // p_r("Today Weather command failed: " . $exception->getMessage());exit;
  316.                         $result['success'] = false;
  317.                         $result['message'] = "Failed to execute notification command.";
  318.                     }
  319.                 }
  320.             }
  321.             if (isset($params['report_id'])) {
  322.                 return ["success" => true"message" => $translator->trans("report_updated_successfully"), "data" => $report->getId()];
  323.             } else {
  324.                 return ["success" => true"message" => $translator->trans("report_published_successfully"), "data" => $report->getId()];
  325.             }
  326.         } catch (\Exception $ex) {
  327.             return ["success" => false"message" => $ex->getMessage()];
  328.         }
  329.     }
  330.     public function reportList($params$page$limit$translator$paginator$report_type$user$lang$is_public true): array
  331.     {
  332.         $result = [];
  333.         try {
  334.             // Load blog listing
  335.             $reportList = new DataObject\Report\Listing();
  336.             $search = isset($params['search']) ? $params['search'] : '';
  337.             if ($report_type == 'mannforecast') {
  338.                 if (!empty($search)) {
  339.                     $db \Pimcore\Db::get();
  340.                     $selectedLocalities $db->fetchAllAssociative(
  341.                         "SELECT oo_id FROM `object_query_customer` WHERE (`name` LIKE ? OR `email` LIKE ?)",
  342.                         ["%" $search "%""%" $search "%"]
  343.                     );
  344.                     $ooIds array_column($selectedLocalities'oo_id');
  345.                     $reportList->setCondition(
  346.                         "((reportType__id IS NULL) AND (isHistorical IN (?)) AND (createdBy__id IN (?) OR searchData LIKE ?))",
  347.                         [
  348.                             [falsenull],
  349.                             $ooIds,
  350.                             '%' $search '%',
  351.                         ]
  352.                     );
  353.                 } else {
  354.                     $reportList->setCondition(
  355.                         "((reportType__id IS NULL) AND (isHistorical IN (?)))",
  356.                         [
  357.                             [falsenull]
  358.                         ]
  359.                     );
  360.                 }
  361.             } elseif ($report_type == 'historical') {
  362.                 if (!empty($search)) {
  363.                     $db \Pimcore\Db::get();
  364.                     $selectedLocalities $db->fetchAllAssociative(
  365.                         "SELECT oo_id FROM `object_query_customer` WHERE (`name` LIKE ? OR `email` LIKE ?)",
  366.                         ["%" $search "%""%" $search "%"]
  367.                     );
  368.                     $ooIds array_column($selectedLocalities'oo_id');
  369.                     $reportList->setCondition(
  370.                         "((reportType__id IS NULL) AND (isHistorical = ?) AND (createdBy__id = ?) AND  (searchData LIKE ?) )",
  371.                         [
  372.                             true,
  373.                             $user->getId(),
  374.                             '%' $search '%'
  375.                         ]
  376.                     );
  377.                 } else {
  378.                     $reportList->setCondition("((reportType__id IS NULL)  AND (createdBy__id = ?) AND (isHistorical = ?))", [$user->getId(), true]);
  379.                 }
  380.             } elseif ($report_type == 'advamced_report_and_custom_report') {
  381.                 // Define the report keys you want to check
  382.                 $reportKeys = ['advance-custom-weather-report''custom-weather-report'];
  383.                 $reportTypeIds = [];
  384.                 // Loop through each report key and fetch the report type if it exists
  385.                 foreach ($reportKeys as $key) {
  386.                     $reportType ReportType::getByReportKey($keytrue);
  387.                     if ($reportType instanceof ReportType) {
  388.                         $reportTypeIds[] = $reportType->getId();
  389.                     }
  390.                 }
  391.                 // If there are any valid report type IDs, set the condition with them
  392.                 if (!empty($reportTypeIds)) {
  393.                     $reportList->setCondition(
  394.                         "(reportType__id IN (?))",
  395.                         [$reportTypeIds]
  396.                     );
  397.                 }
  398.             } elseif ($is_public) {
  399.                 // this if logic is totally build for public portal to get all reports according to the report type key here we are sening the array in report_type variable except other report type whic is string
  400.                 // Define the report keys you want to check
  401.                 foreach ($report_type as $key) {
  402.                     $reportType ReportType::getByReportKey($keytrue);
  403.                     if ($reportType instanceof ReportType) {
  404.                         $reportTypeIds[] = $reportType->getId();
  405.                     }
  406.                 }
  407.                 // If there are any valid report type IDs, set the condition with them
  408.                 if (!empty($reportTypeIds)) {
  409.                     $reportList->setCondition(
  410.                         "(reportType__id IN (?)) AND forPublicPortal = ?",
  411.                         [$reportTypeIdstrue]
  412.                     );
  413.                 } else {
  414.                     $reportList->setCondition(
  415.                         "forPublicPortal = ?",
  416.                         [true]
  417.                     );
  418.                 }
  419.             } else {
  420.                 if (!empty($search)) {
  421.                     $db \Pimcore\Db::get();
  422.                     $selectedLocalities $db->fetchAllAssociative(
  423.                         "SELECT oo_id FROM `object_query_customer` WHERE (`name` LIKE ? OR `email` LIKE ?)",
  424.                         ["%" $search "%""%" $search "%"]
  425.                     );
  426.                     $selectedReportTypes = new ReportType\Listing();
  427.                     $selectedReportTypes->setLocale($lang);
  428.                     $selectedReportTypes->setCondition(
  429.                         "(name LIKE ?)",
  430.                         [
  431.                             '%' $search '%'
  432.                         ]
  433.                     );
  434.                     $selectedReportTypes->load();
  435.                     $report_types = [];
  436.                     foreach ($selectedReportTypes as $reportType) {
  437.                         array_push($report_types$reportType->getId());
  438.                     }
  439.                     // p_r($selectedReportTypes);exit;
  440.                     $organization $user->getOrganization()?->getId();
  441.                     $ooIds array_column($selectedLocalities'oo_id');
  442.                     $reportList->setLocale($params['lang']);
  443.                     $reportList->addConditionParam(
  444.                         "((reportType__id IS NOT NULL) AND (createdBy__id IN (?) OR reportType__id IN (?) OR reportTitle LIKE ?))",
  445.                         [
  446.                             $ooIds,
  447.                             $report_types,
  448.                             '%' $search '%'
  449.                         ]
  450.                     );
  451.                     if ($is_public) {
  452.                         $reportList->addConditionParam(
  453.                             "(forPublicPortal = ?)",
  454.                             [
  455.                                 true
  456.                             ]
  457.                         );
  458.                     }
  459.                 } else {
  460.                     $organization $user->getOrganization()?->getId();
  461.                     $reportList->addConditionParam("reportType__id IS NOT NULL");
  462.                     if ($is_public) {
  463.                         $reportList->addConditionParam(
  464.                             "(forPublicPortal = ?)",
  465.                             [
  466.                                 true
  467.                             ]
  468.                         );
  469.                     }
  470.                 }
  471.             }
  472.             $sortOrderCreatedAt $params['sortByCreated'] ?? 'desc';
  473.             $reportList->setOrderKey('createdOn')
  474.                 ->setOrder($sortOrderCreatedAt);
  475.             if (count($reportList) > 0) {
  476.                 // set pagination
  477.                 $paginate $paginator->paginate(
  478.                     $reportList,
  479.                     $page,
  480.                     $limit
  481.                 );
  482.                 return $this->getReportListData($paginate);
  483.             }
  484.             return ["success" => false"message" => $translator->trans("no_report_is_available")];
  485.         } catch (\Exception $ex) {
  486.             throw new \Exception($ex->getMessage());
  487.         }
  488.         return $result;
  489.     }
  490.     public function listReportsByType($params$translator$paginator): array
  491.     {
  492.         $page $params['page'];
  493.         $limit $params['limit'];
  494.         $lang $params['lang'] ?? 'en';
  495.         $search = isset($params['search']) ? $params['search'] : '';
  496.         $db \Pimcore\Db::get();
  497.         // Define the report keys you want to check
  498.         $reportTypeIds = [];
  499.         // Loop through each report key and fetch the report type if it exists
  500.         foreach ($params['allowedReportTypes'] as $key) {
  501.             $reportType ReportType::getByReportKey($keytrue);
  502.             if ($reportType instanceof ReportType) {
  503.                 $reportTypeIds[] = $reportType->getId();
  504.             }
  505.         }
  506.         // If no allowed report types resolved, return empty result to avoid IN (NULL)
  507.         if (empty($reportTypeIds)) {
  508.             $paginate $paginator->paginate([], $page$limit);
  509.             return ["success" => true"data" => [], "paginationVariables" => $paginate->getPaginationData()];
  510.         }
  511.         // Resolve class ids
  512.         $class = new \Pimcore\Model\DataObject\ClassDefinition();
  513.         $reportClassId $class->getDao()->getIdByName('Report');
  514.         $reportTypeClassId $class->getDao()->getIdByName('ReportType');
  515.         // Build query with proper joins for localized and relation fields
  516.         $select $db->createQueryBuilder();
  517.         $select->select('report.oo_id')
  518.             ->from('object_' $reportClassId'report')
  519.             ->where('report.reportType__id IS NOT NULL AND o_published =1')
  520.             ->andWhere('report.reportType__id IN (:reportTypeIds)')
  521.             ->setParameter('reportTypeIds'$reportTypeIds\Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
  522.         // Title search (localized)
  523.         if (!empty($search)) {
  524.             $select->leftJoin('report''object_localized_query_' $reportClassId '_' $lang'rq''rq.ooo_id = report.oo_id');
  525.             $select->andWhere('rq.reportTitle LIKE ' $db->quote('%' $search '%'));
  526.         }
  527.         // Sorting
  528.         $sortBy $params['orderKey'] ?? ($params['sortBy'] ?? 'createdOn');
  529.         $sortOrder strtoupper($params['order'] ?? ($params['sortByCreated'] ?? 'desc')) === 'ASC' 'ASC' 'DESC';
  530.         switch ($sortBy) {
  531.             case 'reportType':
  532.                 $select->leftJoin('report''object_localized_query_' $reportTypeClassId '_' $lang'rtq''rtq.ooo_id = report.reportType__id');
  533.                 $select->addSelect('rtq.name AS reportType_name');
  534.                 $select->orderBy('reportType_name'$sortOrder);
  535.                 break;
  536.             case 'title':
  537.                 $select->leftJoin('report''object_localized_query_' $reportClassId '_' $lang'rq_sort''rq_sort.ooo_id = report.oo_id');
  538.                 $select->addSelect('rq_sort.reportTitle AS localized_title');
  539.                 $select->orderBy('localized_title'$sortOrder);
  540.                 break;
  541.             case 'email':
  542.                 $select->leftJoin('report''object_query_customer''cbq''cbq.oo_id = report.createdBy__id');
  543.                 $select->addSelect('cbq.email AS createdBy_email');
  544.                 $select->orderBy('createdBy_email'$sortOrder);
  545.                 break;
  546.             case 'createdOn':
  547.             default:
  548.                 $select->orderBy('report.createdOn'$sortOrder);
  549.                 break;
  550.         }
  551.         // Avoid duplicates
  552.         $select->groupBy('report.oo_id');
  553.         $paginate $paginator->paginate($select$page$limit);
  554.         return $this->getReportTypeListData($params['decodedJwtToken'], $params['userPermission'], $paginate$translator);
  555.     }
  556.     public function listAutomaticReports($params$user$search$orderKey$order$translator$paginator)
  557.     {
  558.         $result = [];
  559.         try {
  560.             $organization $user->getOrganization();
  561.             if (!$organization instanceof Organization) {
  562.                 return ["success" => false"message" => $translator->trans("no_organization_is_available_to_this_user")];
  563.             }
  564.             $organizationId $user->getOrganization()?->getId();
  565.             $reportList = new DataObject\Report\Listing();
  566.             if (isset($params['report_type_id'])) {
  567.                 $reportList->addConditionParam("(reportType__id = ?) AND (forAjwaaPortal = ?) AND (organization IS NULL OR organization LIKE ?)", [$params['report_type_id'], true'%' $organizationId '%']);
  568.             } else {
  569.                 $reportList->addConditionParam("(reportType__id IS NOT NULL) AND (forAjwaaPortal = ?) AND (organization IS NULL OR organization LIKE ?)", [true'%' $organizationId '%']);
  570.             }
  571.             if ($search) {
  572.                 $reportList->setLocale($params['lang']);
  573.                 $reportList->addConditionParam(
  574.                     "reportTitle LIKE ?",
  575.                     ['%' $search '%']
  576.                 );
  577.             }
  578.             if (isset($params['startDate']) && isset($params['endDate']) && !empty($params['startDate']) && !empty($params['endDate'])) {
  579.                 $startDate = new \DateTime($params['startDate']);
  580.                 $endDate = new \DateTime($params['endDate']);
  581.                 // Ensure the dates are in the correct format
  582.                 $startDateStr strtotime($startDate->format('Y-m-d H:i:s'));
  583.                 $endDateStr strtotime($endDate->format('Y-m-d') . ' 23:59:59');
  584.                 $reportList->addConditionParam(
  585.                     "(createdOn >= ? AND createdOn <= ?)",
  586.                     [$startDateStr$endDateStr]
  587.                 );
  588.             }
  589.             $reportList->setOrderKey($orderKey)
  590.                 ->setOrder($order);
  591.             if (count($reportList) > 0) {
  592.                 // set pagination
  593.                 $paginate $paginator->paginate(
  594.                     $reportList,
  595.                     $params['page'],
  596.                     $params['limit']
  597.                 );
  598.                 return $this->getReportListData($paginate);
  599.             }
  600.             return ["success" => false"message" => $translator->trans("no_report_is_available")];
  601.         } catch (\Exception $ex) {
  602.             throw new \Exception($ex->getMessage());
  603.         }
  604.         return $result;
  605.     }
  606.     public function listAutomaticPublicReports($params$user$search$orderKey$order$translator$paginator)
  607.     {
  608.         $result = [];
  609.         try {
  610.             $organization $user->getOrganization();
  611.             if (!$organization instanceof Organization) {
  612.                 return ["success" => false"message" => $translator->trans("no_organization_is_available_to_this_user")];
  613.             }
  614.             $organizationId $user->getOrganization()?->getId();
  615.             $reportList = new DataObject\Report\Listing();
  616.             if (isset($params['report_type_id'])) {
  617.                 $reportList->addConditionParam("(reportType__id = ?) AND (forAjwaaPortal = ?)", [$params['report_type_id'], true]);
  618.             } else {
  619.                 $reportList->addConditionParam("(reportType__id IS NOT NULL) AND (forAjwaaPortal = ?)", [true]);
  620.             }
  621.             if ($search) {
  622.                 $reportList->setLocale($params['lang']);
  623.                 $reportList->addConditionParam(
  624.                     "reportTitle LIKE ?",
  625.                     ['%' $search '%']
  626.                 );
  627.             }
  628.             if (isset($params['startDate']) && isset($params['endDate']) && !empty($params['startDate']) && !empty($params['endDate'])) {
  629.                 $startDate = new \DateTime($params['startDate']);
  630.                 $endDate = new \DateTime($params['endDate']);
  631.                 // Ensure the dates are in the correct format
  632.                 $startDateStr strtotime($startDate->format('Y-m-d H:i:s'));
  633.                 $endDateStr strtotime($endDate->format('Y-m-d') . ' 23:59:59');
  634.                 $reportList->addConditionParam(
  635.                     "(createdOn >= ? AND createdOn <= ?)",
  636.                     [$startDateStr$endDateStr]
  637.                 );
  638.             }
  639.             $reportList->setOrderKey($orderKey)
  640.                 ->setOrder($order);
  641.             if (count($reportList) > 0) {
  642.                 // set pagination
  643.                 $paginate $paginator->paginate(
  644.                     $reportList,
  645.                     $params['page'],
  646.                     $params['limit']
  647.                 );
  648.                 return $this->getReportListData($paginate);
  649.             }
  650.             return ["success" => false"message" => $translator->trans("no_report_is_available")];
  651.         } catch (\Exception $ex) {
  652.             throw new \Exception($ex->getMessage());
  653.         }
  654.         return $result;
  655.     }
  656.     /**
  657.      * Get Latest MannForecastReport
  658.      */
  659.     public function getLatestReport($reportType$translator$isPublic true)
  660.     {
  661.         $mannforecastReportType ReportType::getByReportKey($reportTypetrue);
  662.         if (!$mannforecastReportType) {
  663.             return ["success" => false"message" => $translator->trans("report_type_not_created")];
  664.         }
  665.         $mannforecastReport = new Report\Listing();
  666.         $mannforecastReport->addConditionParam(
  667.             "reportType__id = ?",
  668.             [$mannforecastReportType->getId()]
  669.         );
  670.         if (!$isPublic) {
  671.             $mannforecastReport->addConditionParam(
  672.                 "(forPublicPortal = ?)",
  673.                 [
  674.                     true
  675.                 ]
  676.             );
  677.         }
  678.         $mannforecastReport->setOrderKey('createdOn');
  679.         $mannforecastReport->setOrder('desc');
  680.         $latestReport $mannforecastReport->current();
  681.         if (!$latestReport) {
  682.             return ["success" => false"message" => $translator->trans("no_latest_report_found")];
  683.         } else {
  684.             $data = [];
  685.             $data = [
  686.                 'id' => $latestReport->getId(),
  687.                 'name' => $latestReport->getCreatedBy()?->getName(),
  688.                 'email' => $latestReport->getCreatedBy()?->getEmail(),
  689.                 'jsonData' => json_decode($latestReport->getJsonData(), true),
  690.                 'createdOn' => $latestReport->getCreatedOn(),
  691.                 'reportTitle' => $latestReport->getReportTitle("en"),
  692.                 'stateOfTheSea' => $latestReport->getStateOfTheSea("en"),
  693.                 'waveHeight' => $latestReport->getWaveHeight("en"),
  694.                 'surfaceWind' => $latestReport->getSurfaceWind("en"),
  695.                 'reportTitleAr' => $latestReport->getReportTitle("ar"),
  696.                 'stateOfTheSeaAr' => $latestReport->getStateOfTheSea("ar"),
  697.                 'waveHeightAr' => $latestReport->getWaveHeight("ar"),
  698.                 'surfaceWindAr' => $latestReport->getSurfaceWind("ar"),
  699.                 'showTenDayDescription' => $latestReport->getShowPublicDescription(),
  700.                 'isGovernorates' => $latestReport->getIsGovernorates() == true true false
  701.             ];
  702.             return ['success' => true'data' => $data];
  703.         }
  704.     }
  705.     public function getReportListData($paginate)
  706.     {
  707.         $reportListData = [];
  708.         foreach ($paginate as $key => $reportlist) {
  709.             $asset_path $reportlist->getAsset()?->getPath() . $reportlist->getAsset()?->getFileName() ? API_BASE_URL $reportlist->getAsset()?->getPath() . $reportlist->getAsset()?->getFileName() : '';
  710.             $asset_path_ar $reportlist->getAssetAr()?->getPath() . $reportlist->getAssetAr()?->getFileName() ? API_BASE_URL $reportlist->getAssetAr()?->getPath() . $reportlist->getAssetAr()?->getFileName() : '';
  711.             $reportTitleEn $reportlist->getReportType()?->getReportKey() == "10-day-forecast-report" "10-Day Forecast Report" $reportlist->getReportTitle('en');
  712.             $reportTitleAr $reportlist->getReportType()?->getReportKey() == "10-day-forecast-report" "توقعات Ù„مدة 10 Ø£ÙŠØ§Ù…" $reportlist->getReportTitle('ar');
  713.             if ($reportlist->getReportType()?->getReportKey() == "advance-custom-weather-report") {
  714.                 if ($reportlist->getIsMannedReport()) {
  715.                     $isMannedReport true;
  716.                 } else {
  717.                     $isMannedReport false;
  718.                 }
  719.             } else {
  720.                 $isMannedReport null;
  721.             }
  722.             $reportListData[$key] = [
  723.                 'id' => $reportlist->getId(),
  724.                 'createdBy' => $reportlist->getCreatedBy()?->getName(),
  725.                 'email' => $reportlist->getCreatedBy()?->getEmail(),
  726.                 'createdOn' => $reportlist->getCreatedOn(),
  727.                 'startDate' => $reportlist->getStartDate('Y-m-d H:i:s'),
  728.                 'endDate' => $reportlist->getEndDate('Y-m-d H:i:s'),
  729.                 'report' => json_decode($reportlist->getJsonData(), true),
  730.                 'reportTypeEn' => $reportlist->getReportType()?->getName('en'),
  731.                 'reportTypeAr' => $reportlist->getReportType()?->getName('ar'),
  732.                 'reportTypeId' => $reportlist->getReportType()?->getId(),
  733.                 'reportTypeKey' => $reportlist->getReportType()?->getReportKey(),
  734.                 'reportTitleEn' => $reportTitleEn,
  735.                 'reportTitleAr' => $reportTitleAr,
  736.                 'reportDescriptionAr' => $reportlist->getDescription('ar'),
  737.                 'reportDescriptionEn' => $reportlist->getDescription('en'),
  738.                 'isMannedAdvanceCustomReport' => $isMannedReport,
  739.                 'stateOfTheSeaEn' => $reportlist->getStateOfTheSea('en'),
  740.                 'stateOfTheSeaAr' => $reportlist->getStateOfTheSea('ar'),
  741.                 'surfaceWindEn' => $reportlist->getSurfaceWind('en'),
  742.                 'surfaceWindAr' => $reportlist->getSurfaceWind('ar'),
  743.                 'waveHeightEn' => $reportlist->getWaveHeight('en'),
  744.                 'waveHeightAr' => $reportlist->getWaveHeight('ar'),
  745.                 'asset' => $asset_path,
  746.                 'assetAr' => $asset_path_ar,
  747.                 'isAWSReport' => $reportlist->getIsAWSReport(),
  748.             ];
  749.             // 15-Day Forecast Report
  750.             if ($reportlist->getReportType()?->getReportKey() == "15-day-forecast-report") {
  751.                 $reportListData[$key]['reportDescriptionEn']  = $reportlist->getReportTitle('en');
  752.                 $reportListData[$key]['reportDescriptionAr']  = $reportlist->getReportTitle('ar');
  753.             }
  754.         }
  755.         return ["success" => true"data" => $reportListData"paginationVariables" => $paginate->getPaginationData()];
  756.     }
  757.     public function getReportTypeListData($decodedJwtToken$userPermission$paginate$translator)
  758.     {
  759.         $reportListData = [];
  760.         foreach ($paginate as $key => $row) {
  761.             $reportlist \Pimcore\Model\DataObject\Report::getById($row['oo_id'], true);
  762.             if (!$reportlist instanceof \Pimcore\Model\DataObject\Report) {
  763.                 continue;
  764.             }
  765.             $asset_path $reportlist->getAsset()?->getPath() . $reportlist->getAsset()?->getFileName() ? API_BASE_URL $reportlist->getAsset()?->getPath() . $reportlist->getAsset()?->getFileName() : '';
  766.             $asset_path_ar $reportlist->getAssetAr()?->getPath() . $reportlist->getAssetAr()?->getFileName() ? API_BASE_URL $reportlist->getAssetAr()?->getPath() . $reportlist->getAssetAr()?->getFileName() : '';
  767.             $reportTitleEn $reportlist->getReportType()?->getReportKey() == "10-day-forecast-report" "10-Day Forecast Report" $reportlist->getReportTitle('en');
  768.             $reportTitleAr $reportlist->getReportType()?->getReportKey() == "10-day-forecast-report" "توقعات Ù„مدة 10 Ø£ÙŠØ§Ù…" $reportlist->getReportTitle('ar');
  769.             if ($reportlist->getReportType()?->getReportKey() == "advance-custom-weather-report") {
  770.                 if ($reportlist->getIsMannedReport()) {
  771.                     $isMannedReport true;
  772.                 } else {
  773.                     $isMannedReport false;
  774.                 }
  775.             } else {
  776.                 $isMannedReport null;
  777.             }
  778.             $reportListData[$key] = [
  779.                 'id' => $reportlist->getId(),
  780.                 'createdBy' => $reportlist->getCreatedBy()?->getName(),
  781.                 'email' => $reportlist->getCreatedBy()?->getEmail(),
  782.                 'createdOn' => $reportlist->getCreatedOn(),
  783.                 'startDate' => $reportlist->getStartDate('Y-m-d H:i:s'),
  784.                 'endDate' => $reportlist->getEndDate('Y-m-d H:i:s'),
  785.                 'report' => json_decode($reportlist->getJsonData(), true),
  786.                 'reportTypeEn' => $reportlist->getReportType()?->getName('en'),
  787.                 'reportTypeAr' => $reportlist->getReportType()?->getName('ar'),
  788.                 'reportTypeId' => $reportlist->getReportType()?->getId(),
  789.                 'reportTypeKey' => $reportlist->getReportType()?->getReportKey(),
  790.                 'reportTitleEn' => $reportTitleEn,
  791.                 'reportTitleAr' => $reportTitleAr,
  792.                 'reportDescriptionAr' => $reportlist->getDescription('ar'),
  793.                 'reportDescriptionEn' => $reportlist->getDescription('en'),
  794.                 'isMannedAdvanceCustomReport' => $isMannedReport,
  795.                 'stateOfTheSeaEn' => $reportlist->getStateOfTheSea('en'),
  796.                 'stateOfTheSeaAr' => $reportlist->getStateOfTheSea('ar'),
  797.                 'surfaceWindEn' => $reportlist->getSurfaceWind('en'),
  798.                 'surfaceWindAr' => $reportlist->getSurfaceWind('ar'),
  799.                 'waveHeightEn' => $reportlist->getWaveHeight('en'),
  800.                 'waveHeightAr' => $reportlist->getWaveHeight('ar'),
  801.                 'asset' => $asset_path,
  802.                 'assetAr' => $asset_path_ar,
  803.                 'isAWSReport' => $reportlist->getIsAWSReport(),
  804.                 'fileType' => $reportlist->getFileType() == 'video' 'Video' 'pdf',
  805.             ];
  806.             // Initialize edit and delete flags
  807.             $editFlag false;
  808.             $deleteFlag false;
  809.             // Get the current report's type key
  810.             $currentReportTypeKey $reportlist->getReportType()?->getReportKey();
  811.             // Map report type keys to permission names
  812.             $permissionMapping = [
  813.                 'red-sea-report' => 'red_sea_report',
  814.                 'arabian-gulf-report' => 'arabian_gulf_report',
  815.                 '10-day-forecast-report' => '10_day_forecast_report',
  816.                 'custom-weather-report' => 'custom_weather_report',
  817.                 'advance-custom-weather-report' => 'advance_custom_weather_report',
  818.                 'mashaer-weather-report' => 'mashaer_weather_report'
  819.             ];
  820.             // Check permissions only for the current report type
  821.             if ($currentReportTypeKey && isset($permissionMapping[$currentReportTypeKey])) {
  822.                 $permissionName $permissionMapping[$currentReportTypeKey];
  823.                 $permissionStatus $userPermission->getUserPermissions($decodedJwtToken$translator);
  824.                 // Check edit permission
  825.                 if (isset($permissionStatus['grants']["update_$permissionName"]) && $permissionStatus['grants']["update_$permissionName"] === true) {
  826.                     $editFlag true;
  827.                 }
  828.                 // Check delete permission
  829.                 if (isset($permissionStatus['grants']["delete_$permissionName"]) && $permissionStatus['grants']["delete_$permissionName"] === true) {
  830.                     $deleteFlag true;
  831.                 }
  832.             }
  833.             $reportListData[$key]['canEdit'] = $editFlag;
  834.             $reportListData[$key]['canDelete'] = $deleteFlag;
  835.             // 15-Day Forecast Report
  836.             if ($reportlist->getReportType()?->getReportKey() == "15-day-forecast-report") {
  837.                 $reportListData[$key]['reportDescriptionEn']  = $reportlist->getReportTitle('en');
  838.                 $reportListData[$key]['reportDescriptionAr']  = $reportlist->getReportTitle('ar');
  839.             }
  840.         }
  841.         return ["success" => true"data" => $reportListData"paginationVariables" => $paginate->getPaginationData()];
  842.     }
  843.     public function getTodayWeatherReports($params$translator$paginator)
  844.     {
  845.         $lang $param['lang'] ?? "en";
  846.         $reports = new \Pimcore\Model\DataObject\ReportTodayWeather\Listing();
  847.         $reports->setLocale($lang);
  848.         if (isset($params['search'])) {
  849.             $reports->setCondition(
  850.                 "(title LIKE ?)",
  851.                 [
  852.                     '%' $params['search'] . '%'
  853.                 ]
  854.             );
  855.         }
  856.         $sortOrderCreatedAt $params['sortByCreated'] ?? "desc";
  857.         $reports->setOrderKey("o_id")
  858.             ->setOrder($sortOrderCreatedAt);
  859.         if (count($reports) > 0) {
  860.             // set pagination
  861.             $paginate $paginator->paginate(
  862.                 $reports,
  863.                 $params['page'],
  864.                 $params['limit']
  865.             );
  866.             $data = [];
  867.             foreach ($paginate as $report) {
  868.                 $data[] = [
  869.                     'reportNameEn' => $report->getTitle("en"),
  870.                     'reportNameAr' => $report->getTitle("ar"),
  871.                     'reportPathEn' => $report->getPdfReport() ? API_BASE_URL $report->getPdfReport()->getPath() . $report->getPdfReport()->getFilename() : '',
  872.                     'reportPathAr' => $report->getPdfReportAr() ? API_BASE_URL $report->getPdfReportAr()->getPath() . $report->getPdfReportAr()->getFilename() : '',
  873.                     'generatedAt' => $report->getGeneratedAt()
  874.                 ];
  875.             }
  876.             return ['success' => true'data' => $data"paginationVariables" => $paginate->getPaginationData()];
  877.         }
  878.         return ["success" => false"message" => $translator->trans("no_report_is_available")];
  879.     }
  880.     public function getTodayWeatherReportData($request$translator)
  881.     {
  882.         $reportData = [];
  883.         $todaysDate = new \Carbon\Carbon(); // Assuming you are using Carbon\Carbon for $todaysDate
  884.         $todaysDate->setTime(000); // Set the time to midnight for comparison
  885.         $todaysDateString $todaysDate->format('Y-m-d');
  886.         // get 15 day forecast report
  887.         $mannforecast_report = new Report\Listing();
  888.         $mannforecast_report_type ReportType::getByKey('MannForecastReport'true);
  889.         if (!$mannforecast_report_type) {
  890.             return ["success" => false"message" => $translator->trans('mannforecast_report_type_not_created')];
  891.         }
  892.         $mannforecast_report->setCondition(
  893.             "((reportType__id = ?) AND (isHistorical IN (?)))",
  894.             [$mannforecast_report_type->getId(), [falsenull]]
  895.         );
  896.         $mannforecast_report->setOrderKey("o_creationDate");
  897.         $mannforecast_report->setOrder("desc");
  898.         $mann_forecast_report $mannforecast_report->current();
  899.         if (!$mann_forecast_report) {
  900.             return ["success" => false"message" => $translator->trans('mannforecast_report_not_created')];
  901.         }
  902.         // get 15 red sea report
  903.         $redsea_report = new Report\Listing();
  904.         $redsea_report_type ReportType::getByKey('RedSeaReport'true);
  905.         if (!$redsea_report_type) {
  906.             return ["success" => false"message" => $translator->trans('redsea_report_type_not_created')];
  907.         }
  908.         $redsea_report->setCondition(
  909.             "((reportType__id = ?) AND (isHistorical IN (?)))",
  910.             [$redsea_report_type->getId(), [falsenull]]
  911.         );
  912.         $redsea_report->setOrderKey("o_creationDate");
  913.         $redsea_report->setOrder("desc");
  914.         $red_sea_report $redsea_report->current();
  915.         if (!$red_sea_report) {
  916.             return ["success" => false"message" => $translator->trans('redsea_report_not_created')];
  917.         }
  918.         // get 15 arabiangulf_report 
  919.         $arabiangulf_report = new Report\Listing();
  920.         $arabiangulf_report_type ReportType::getByKey('ArabianGulfReport'true);
  921.         if (!$arabiangulf_report_type) {
  922.             return ["success" => false"message" => $translator->trans('arabiangulf_report_type_not_created')];
  923.         }
  924.         $arabiangulf_report->setCondition(
  925.             "((reportType__id = ?) AND (isHistorical IN (?)))",
  926.             [$arabiangulf_report_type->getId(), [falsenull]]
  927.         );
  928.         $arabiangulf_report->setOrderKey("o_creationDate");
  929.         $arabiangulf_report->setOrder("desc");
  930.         $arabian_gulf_report $arabiangulf_report->current();
  931.         if (!$arabian_gulf_report) {
  932.             return ["success" => false"message" => $translator->trans('arabiangulf_report_not_created')];
  933.         }
  934.         $red_sea_list = [
  935.             // 'reportTitleEn' => $red_sea_report->getReportTitle('en'),
  936.             // 'reportTitleAr' => $red_sea_report->getReportTitle('ar'),
  937.             'surfaceWindEn' => $red_sea_report->getSurfaceWind('en'),
  938.             'surfaceWindAr' => $red_sea_report->getSurfaceWind('ar'),
  939.             'waveHeightEn' => $red_sea_report->getWaveHeight('en'),
  940.             'waveHeightAr' => $red_sea_report->getWaveHeight('ar'),
  941.             'stateOfTheSeaEn' => $red_sea_report->getStateOfTheSea('en'),
  942.             'stateOfTheSeaAr' => $red_sea_report->getStateOfTheSea('ar'),
  943.         ];
  944.         $json_data = [];
  945.         foreach (json_decode($mann_forecast_report->getJsonData()) as $data) {
  946.             $cityEn $data->cityEn;
  947.             if (!isset($json_data[$cityEn])) {
  948.                 $json_data[$cityEn] = [];
  949.             }
  950.             foreach ($data->parameters as $parameter) {
  951.                 $first_date $parameter->dates[0];
  952.                 $json_data[$cityEn][] = [
  953.                     'cityAr' => $data->cityAr,
  954.                     'lat' => $data->lat,
  955.                     'lon' => $data->lon,
  956.                     'parameter' => $parameter->parameter,
  957.                     'date' => $first_date->date,
  958.                     'value' => $first_date->value
  959.                 ];
  960.             }
  961.         }
  962.         $mannforeacast_list = [
  963.             'reportTitleEn' => $mann_forecast_report->getReportTitle(),
  964.             'reportTitleAr' => $mann_forecast_report->getReportTitle(),
  965.             'jsonData' => $json_data,
  966.             'createdOn' => $mann_forecast_report->getCreatedOn(),
  967.             // 'lang' => $mann_forecast_report->getLang()
  968.         ];
  969.         $arabian_gulf_list = [
  970.             // 'reportTitleEn' => $arabian_gulf_report->getReportTitle('en'),
  971.             // 'reportTitleAr' => $arabian_gulf_report->getReportTitle('ar'),
  972.             'surfaceWindEn' => $arabian_gulf_report->getSurfaceWind('en'),
  973.             'surfaceWindAr' => $arabian_gulf_report->getSurfaceWind('ar'),
  974.             'waveHeightEn' => $arabian_gulf_report->getWaveHeight('en'),
  975.             'waveHeightAr' => $arabian_gulf_report->getWaveHeight('ar'),
  976.             'stateOfTheSeaEn' => $arabian_gulf_report->getStateOfTheSea('en'),
  977.             'stateOfTheSeaAr' => $arabian_gulf_report->getStateOfTheSea('ar'),
  978.         ];
  979.         $reportData = [
  980.             'redSea' => $red_sea_list,
  981.             'fifteenDay' => $mannforeacast_list,
  982.             'arabianGulf' => $arabian_gulf_list
  983.         ];
  984.         return ['success' => true'data' => $reportData];
  985.     }
  986.     public function getAllWeatherReportData($request$translator)
  987.     {
  988.         $json_data = [];
  989.         $report_listing_data = [
  990.             'reports' => [
  991.                 'customWeather' => [],
  992.                 'mashaerWeather' => [],
  993.                 'todayWeather' => [],
  994.                 'redSea' => [],
  995.                 'arabianGulf' => [],
  996.             ],
  997.         ];
  998.         $todaysDate = new \Carbon\Carbon(); // Assuming you are using Carbon\Carbon for $todaysDate
  999.         $todaysDate->setTime(000); // Set the time to midnight for comparison
  1000.         $todaysDateString $todaysDate->format('Y-m-d');
  1001.         // get Custom Weather report
  1002.         $customWeatherReport = new Report\Listing();
  1003.         $customWeatherReport_type ReportType::getByKey('CustomWeatherReport'true);
  1004.         if (!is_null($customWeatherReport_type)) {
  1005.             $customWeatherReport->setCondition(
  1006.                 "((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
  1007.                 [$customWeatherReport_type->getId(), [falsenull], $todaysDateString]
  1008.             );
  1009.             $customWeatherReport->setOrderKey("o_creationDate");
  1010.             $customWeatherReport->setOrder("desc");
  1011.             $custom_Weather_Report $customWeatherReport->current();
  1012.             $json_data = [];
  1013.             if (!empty($custom_Weather_Report) and !is_null($custom_Weather_Report)) {
  1014.                 if (!empty($custom_Weather_Report->getJsonData()) and !is_null($custom_Weather_Report->getJsonData())) {
  1015.                     foreach (json_decode($custom_Weather_Report->getJsonData()) as $data) {
  1016.                         $cityEn $data->cityEn;
  1017.                         if (!isset($json_data[$cityEn])) {
  1018.                             $json_data[$cityEn] = [];
  1019.                         }
  1020.                         $json_data[$cityEn] = [
  1021.                             'cityEn' => $data->cityEn,
  1022.                             'cityAr' => $data->cityAr,
  1023.                             'lat' => $data->lat,
  1024.                             'lon' => $data->lon,
  1025.                             'data'  =>  $data->parameters
  1026.                         ];
  1027.                     }
  1028.                 }
  1029.                 $report_listing_data['reports']['customWeather'] = [
  1030.                     'id' => $custom_Weather_Report->getId(),
  1031.                     'reportTitleEn' => $custom_Weather_Report->getReportTitle('en'),
  1032.                     'reportTitleAr' => $custom_Weather_Report->getReportTitle('ar'),
  1033.                     'jsonData' => $json_data,
  1034.                     'createdOn' => $custom_Weather_Report->getCreatedOn()->format('Y-m-d H:i:s')
  1035.                 ];
  1036.             }
  1037.         }
  1038.         // get Mashaer Weather report
  1039.         $mashaerWeatherReport = new Report\Listing();
  1040.         $mashaerWeatherReport_type ReportType::getByKey('MashaerWeatherReport'true);
  1041.         if (!is_null($mashaerWeatherReport_type)) {
  1042.             $mashaerWeatherReport->setCondition(
  1043.                 "((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
  1044.                 [$mashaerWeatherReport_type->getId(), [falsenull], $todaysDateString]
  1045.             );
  1046.             $mashaerWeatherReport->setOrderKey("o_creationDate");
  1047.             $mashaerWeatherReport->setOrder("desc");
  1048.             $mashaer_Weather_Report $mashaerWeatherReport->current();
  1049.             $json_data = [];
  1050.             if (!empty($mashaer_Weather_Report) and !is_null($mashaer_Weather_Report)) {
  1051.                 if (!empty($mashaer_Weather_Report->getJsonData()) and !is_null($mashaer_Weather_Report->getJsonData())) {
  1052.                     foreach (json_decode($mashaer_Weather_Report->getJsonData()) as $data) {
  1053.                         $cityEn $data->cityEn;
  1054.                         if (!isset($json_data[$cityEn])) {
  1055.                             $json_data[$cityEn] = [];
  1056.                         }
  1057.                         $json_data[$cityEn] = [
  1058.                             'cityEn' => $data->cityEn,
  1059.                             'cityAr' => $data->cityAr,
  1060.                             'lat' => $data->lat,
  1061.                             'lon' => $data->lon,
  1062.                             'data'  =>  $data->parameters
  1063.                         ];
  1064.                     }
  1065.                 }
  1066.                 $report_listing_data['reports']['mashaerWeather'] = [
  1067.                     'id' => $mashaer_Weather_Report->getId(),
  1068.                     'reportTitleEn' => $mashaer_Weather_Report->getReportTitle('en'),
  1069.                     'reportTitleAr' => $mashaer_Weather_Report->getReportTitle('ar'),
  1070.                     'jsonData' => $json_data,
  1071.                     'createdOn' => $mashaer_Weather_Report->getCreatedOn()->format('Y-m-d H:i:s')
  1072.                 ];
  1073.             }
  1074.         }
  1075.         // get 15 red sea report
  1076.         $redsea_report = new Report\Listing();
  1077.         $redsea_report_type ReportType::getByKey('RedSeaReport'true);
  1078.         if (!is_null($redsea_report_type)) {
  1079.             $redsea_report->setCondition(
  1080.                 "((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
  1081.                 [$redsea_report_type->getId(), [falsenull], $todaysDate]
  1082.             );
  1083.             $redsea_report->setOrderKey("o_creationDate");
  1084.             $redsea_report->setOrder("desc");
  1085.             $redsea_report->setLimit(10);
  1086.             $red_sea_report $redsea_report->current();
  1087.             $json_data = [];
  1088.             if (!empty($red_sea_report) and !is_null($red_sea_report)) {
  1089.                 if (!empty($red_sea_report->getJsonData()) and !is_null($red_sea_report->getJsonData())) {
  1090.                     foreach (json_decode($red_sea_report->getJsonData()) as $data) {
  1091.                         $cityEn $data->cityEn;
  1092.                         if (!isset($json_data[$cityEn])) {
  1093.                             $json_data[$cityEn] = [];
  1094.                         }
  1095.                         $json_data[$cityEn] = [
  1096.                             'cityEn' => $data->cityEn,
  1097.                             'cityAr' => $data->cityAr,
  1098.                             'lat' => $data->lat,
  1099.                             'lon' => $data->lon,
  1100.                             'data'  =>  $data->parameters
  1101.                         ];
  1102.                     }
  1103.                 }
  1104.                 $report_listing_data['reports']['redSea'] = [
  1105.                     'id' => $red_sea_report->getId(),
  1106.                     'surfaceWindEn' => $red_sea_report->getSurfaceWind('en'),
  1107.                     'surfaceWindAr' => $red_sea_report->getSurfaceWind('ar'),
  1108.                     'waveHeightEn' => $red_sea_report->getWaveHeight('en'),
  1109.                     'waveHeightAr' => $red_sea_report->getWaveHeight('ar'),
  1110.                     'stateOfTheSeaEn' => $red_sea_report->getStateOfTheSea('en'),
  1111.                     'stateOfTheSeaAr' => $red_sea_report->getStateOfTheSea('ar'),
  1112.                     'reportTitleEn' => $red_sea_report->getReportTitle('en'),
  1113.                     'reportTitleAr' => $red_sea_report->getReportTitle('ar'),
  1114.                     'jsonData' => $json_data,
  1115.                     'createdOn' => $red_sea_report->getCreatedOn()->format('Y-m-d H:i:s')
  1116.                 ];
  1117.             }
  1118.         }
  1119.         // get 15 arabiangulf_report 
  1120.         $arabiangulf_report = new Report\Listing();
  1121.         $arabiangulf_report_type ReportType::getByKey('ArabianGulfReport'true);
  1122.         if (!is_null($arabiangulf_report_type)) {
  1123.             $arabiangulf_report->setCondition(
  1124.                 "((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
  1125.                 [$arabiangulf_report_type->getId(), [falsenull], $todaysDate]
  1126.             );
  1127.             $arabiangulf_report->setOrderKey("o_creationDate");
  1128.             $arabiangulf_report->setOrder("desc");
  1129.             $arabian_gulf_report $arabiangulf_report->current();
  1130.             $json_data = [];
  1131.             if (!empty($arabian_gulf_report) and !is_null($arabian_gulf_report)) {
  1132.                 if (!empty($arabian_gulf_report->getJsonData()) and !is_null($arabian_gulf_report->getJsonData())) {
  1133.                     foreach (json_decode($arabian_gulf_report->getJsonData()) as $data) {
  1134.                         $cityEn $data->cityEn;
  1135.                         if (!isset($json_data[$cityEn])) {
  1136.                             $json_data[$cityEn] = [];
  1137.                         }
  1138.                         $json_data[$cityEn] = [
  1139.                             'cityEn' => $data->cityEn,
  1140.                             'cityAr' => $data->cityAr,
  1141.                             'lat' => $data->lat,
  1142.                             'lon' => $data->lon,
  1143.                             'data'  =>  $data->parameters
  1144.                         ];
  1145.                     }
  1146.                 }
  1147.                 $report_listing_data['reports']['arabianGulf'] = [
  1148.                     'id' => $arabian_gulf_report->getId(),
  1149.                     'surfaceWindEn' => $arabian_gulf_report->getSurfaceWind('en'),
  1150.                     'surfaceWindAr' => $arabian_gulf_report->getSurfaceWind('ar'),
  1151.                     'waveHeightEn' => $arabian_gulf_report->getWaveHeight('en'),
  1152.                     'waveHeightAr' => $arabian_gulf_report->getWaveHeight('ar'),
  1153.                     'stateOfTheSeaEn' => $arabian_gulf_report->getStateOfTheSea('en'),
  1154.                     'stateOfTheSeaAr' => $arabian_gulf_report->getStateOfTheSea('ar'),
  1155.                     'reportTitleEn' => $arabian_gulf_report->getReportTitle('en'),
  1156.                     'reportTitleAr' => $arabian_gulf_report->getReportTitle('ar'),
  1157.                     'jsonData' => $json_data,
  1158.                     'createdOn' => $arabian_gulf_report->getCreatedOn()->format('Y-m-d H:i:s')
  1159.                 ];
  1160.             }
  1161.         }
  1162.         // get 15 day forecast report'
  1163.         $mannforecast_report = new Report\Listing();
  1164.         $mannforecast_report_type ReportType::getByKey('MannForecastReport'true);
  1165.         if (!is_null($mannforecast_report_type)) {
  1166.             $mannforecast_report->setCondition(
  1167.                 "((reportType__id = ?) AND (isHistorical IN (?))) AND (DATE(FROM_UNIXTIME(createdOn)) = ?)",
  1168.                 [$mannforecast_report_type->getId(), [falsenull], $todaysDateString]
  1169.             );
  1170.             $mannforecast_report->setOrderKey("o_creationDate");
  1171.             $mannforecast_report->setOrder("desc");
  1172.             $mann_forecast_report $mannforecast_report->current();
  1173.             $json_data = [];
  1174.             if (!empty($mann_forecast_report) and !is_null($mann_forecast_report)) {
  1175.                 foreach (json_decode($mann_forecast_report->getJsonData()) as $data) {
  1176.                     $cityEn $data->cityEn;
  1177.                     if (!isset($json_data[$cityEn])) {
  1178.                         $json_data[$cityEn] = [];
  1179.                     }
  1180.                     foreach ($data->parameters as $parameter) {
  1181.                         $first_date $parameter->dates[0];
  1182.                         $json_data[$cityEn][] = [
  1183.                             'cityAr' => $data->cityAr,
  1184.                             'lat' => $data->lat,
  1185.                             'lon' => $data->lon,
  1186.                             'parameter' => $parameter->parameter,
  1187.                             'date' => $first_date->date,
  1188.                             'value' => $first_date->value
  1189.                         ];
  1190.                     }
  1191.                 }
  1192.                 $report_listing_data['reports']['todayWeather']['todayWeatherData'] = [
  1193.                     'id' => $mann_forecast_report->getId(),
  1194.                     'reportTitleEn' => $mann_forecast_report->getReportTitle('en'),
  1195.                     'reportTitleAr' => $mann_forecast_report->getReportTitle('ar'),
  1196.                     'jsonData' => $json_data,
  1197.                     'createdOn' => $mann_forecast_report->getCreatedOn()->format('Y-m-d H:i:s')
  1198.                 ];
  1199.                 if ($red_sea_report) {
  1200.                     $report_listing_data['reports']['todayWeather']['redSeaData'] = [
  1201.                         'surfaceWindEn' => $red_sea_report->getSurfaceWind('en'),
  1202.                         'surfaceWindAr' => $red_sea_report->getSurfaceWind('ar'),
  1203.                         'waveHeightEn' => $red_sea_report->getWaveHeight('en'),
  1204.                         'waveHeightAr' => $red_sea_report->getWaveHeight('ar'),
  1205.                         'stateOfTheSeaEn' => $red_sea_report->getStateOfTheSea('en'),
  1206.                         'stateOfTheSeaAr' => $red_sea_report->getStateOfTheSea('ar'),
  1207.                         'reportTitleEn' => $red_sea_report->getReportTitle('en'),
  1208.                         'reportTitleAr' => $red_sea_report->getReportTitle('ar'),
  1209.                     ];
  1210.                 }
  1211.                 if ($arabian_gulf_report) {
  1212.                     $report_listing_data['reports']['todayWeather']['arabianGulfData'] = [
  1213.                         'surfaceWindEn' => $arabian_gulf_report->getSurfaceWind('en'),
  1214.                         'surfaceWindAr' => $arabian_gulf_report->getSurfaceWind('ar'),
  1215.                         'waveHeightEn' => $arabian_gulf_report->getWaveHeight('en'),
  1216.                         'waveHeightAr' => $arabian_gulf_report->getWaveHeight('ar'),
  1217.                         'stateOfTheSeaEn' => $arabian_gulf_report->getStateOfTheSea('en'),
  1218.                         'stateOfTheSeaAr' => $arabian_gulf_report->getStateOfTheSea('ar'),
  1219.                         'reportTitleEn' => $arabian_gulf_report->getReportTitle('en'),
  1220.                         'reportTitleAr' => $arabian_gulf_report->getReportTitle('ar'),
  1221.                     ];
  1222.                 }
  1223.             }
  1224.         }
  1225.         return ['success' => true'data' => $report_listing_data];
  1226.     }
  1227.     public function createMannedReport($request$translator$params$user)
  1228.     {
  1229.         try {
  1230.             $reportType ReportType::getById($params['report_type_id'], true);
  1231.             if (!$reportType instanceof ReportType) {
  1232.                 return ["success" => true"message" => $translator->trans("report_type_does_not_exists")];
  1233.             }
  1234.             $report = new Report();
  1235.             $report->setPublished(true);
  1236.             $report->setParent(DataObject\Service::createFolderByPath('/Report/Report/' $reportType->getReportKey() . '/'));
  1237.             $report->setKey($params['titleEn'] . '-' uniqid());
  1238.             $report->setReportType($reportType);
  1239.             $report->setIsMannedReport(true);
  1240.             $report->setCreatedBy($user);
  1241.             $report->setCreatedOn(Carbon::now());
  1242.             $report->setReportTitle($params['titleEn'], 'en');
  1243.             $report->setReportTitle($params['titleAr'], 'ar');
  1244.             $report->setDescription($params['descriptionEn'], 'en');
  1245.             $report->setDescription($params['descriptionAr'], 'ar');
  1246.             $report->setLang($params['lang']);
  1247.             if (!empty($params['file'])) {
  1248.                 // Set the filename from the input
  1249.                 $filename $params['fileName'];
  1250.                 // Check if the file type is video or pdf, and if so, append a unique ID
  1251.                 if ($params['type'] == 'video' || $params['type'] == 'pdf') {
  1252.                     // Append a unique ID before the extension (to ensure uniqueness)
  1253.                     $filename pathinfo($filenamePATHINFO_FILENAME) . '_' uniqid() . '.' pathinfo($filenamePATHINFO_EXTENSION);
  1254.                 }
  1255.                  $asset $this->createAsset($params['file'], $filename$params['type']);
  1256.                 if ($asset) {
  1257.                     $report->setAsset($asset);
  1258.                     $report->setFileType($params['type']);
  1259.                 }
  1260.             }
  1261.             if (isset($params['organizations']) && !empty($params['organizations'])) {
  1262.                 $selectedOrganizations = [];
  1263.                 if ($params['organizations'][0] == 0) {
  1264.                     // $organizations = new Organization\Listing();
  1265.                     // if ($organizations->count() > 0) {
  1266.                     //     foreach ($organizations as $organization) {
  1267.                     //         if ($organization) {
  1268.                     //             $selectedOrganizations[] = $organization;
  1269.                     //         }
  1270.                     //     }
  1271.                     //     $report->setOrganization($selectedOrganizations);
  1272.                     // }
  1273.                 } else {
  1274.                     foreach ($params['organizations'] as $organization) {
  1275.                         $organizationObject Organization::getById($organizationtrue);
  1276.                         if ($organizationObject) {
  1277.                             $selectedOrganizations[] = $organizationObject;
  1278.                         }
  1279.                     }
  1280.                     $report->setOrganization($selectedOrganizations);
  1281.                 }
  1282.             }
  1283.             $emails "";
  1284.             if (!empty($params['channels'])) {
  1285.                 $channels = ['public_portal''ajwaa_portal''email''twitter''sms'];
  1286.                 foreach ($params['channels'] as $channel) {
  1287.                     if ($channel == 'public_portal') {
  1288.                         $report->setForPublicPortal(true);
  1289.                     } elseif ($channel == 'ajwaa_portal') {
  1290.                         $report->setForAjwaaPortal(true);
  1291.                         if (isset($params['send_email'])) {
  1292.                             $report->setSendEmail(true);
  1293.                         }
  1294.                     } elseif ($channel == 'email') {
  1295.                         $report->setForEmailChannel(true);
  1296.                         $emails .= implode(","$params['emails']);
  1297.                     } elseif ($channel == 'twitter') {
  1298.                         $report->setForTwitterChannel(true);
  1299.                     }
  1300.                 }
  1301.             }
  1302.             $emailArray = [];
  1303.             if (isset($params['user_group_ids']) && !empty($params['user_group_ids'])) {
  1304.                 $userGroupIds = ($params['user_group_ids']);
  1305.                 foreach ($userGroupIds as $userGroupId) {
  1306.                     if ($userGroupId) {
  1307.                         $userGroup \Pimcore\Model\DataObject\EwsAndReportUserGroup::getById($userGroupIdtrue);
  1308.                         if ($userGroup instanceof \Pimcore\Model\DataObject\EwsAndReportUserGroup) {
  1309.                             foreach (json_decode($userGroup->getJsonData()) as $currentUser) {
  1310.                                 if (isset($currentUser->email)) {
  1311.                                     $report->setForEmailChannel(true);
  1312.                                     $emailArray[] = $currentUser->email;
  1313.                                 }
  1314.                             }
  1315.                         }
  1316.                     }
  1317.                 }
  1318.             }
  1319.             if (!empty($emailArray)) {
  1320.                 if (!empty($emails)) {
  1321.                     $emails .= ',' implode(','$emailArray);
  1322.                 } else {
  1323.                     $emails implode(','$emailArray);
  1324.                 }
  1325.             }
  1326.             $report->setEmails($emails);
  1327.             $report->save();
  1328.             return ["success" => true"message" => $translator->trans("report_generated_successfully"), "report_id" => $report->getId()];
  1329.         } catch (\Exception $ex) {
  1330.             return ["success" => false"message" => $ex->getMessage()];
  1331.         }
  1332.     }
  1333.     public function createAsset($fileData$filename$type null)
  1334.     {
  1335.         // Validate the file data
  1336.         if (preg_match('/^data:(image\/(png|jpe?g)|application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel)|video\/(mp4|webm|x-msvideo|quicktime|x-matroska|x-flv|x-ms-wmv|mpeg|3gpp));base64,/'$fileData) !== 1) {
  1337.             return false// Invalid file data or MIME type
  1338.         }
  1339.         // Extract the file extension from the MIME type
  1340.         $extension '';
  1341.         if (preg_match('/^data:image\/(png|jpe?g);base64,/'$fileData)) {
  1342.             $extension 'jpg'// Assume JPG for base64-encoded image data (PNG or JPEG)
  1343.         } elseif (preg_match('/^data:application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel);base64,/'$fileData)) {
  1344.             $extension 'pdf'// PDF, DOCX, or Excel
  1345.         } elseif (preg_match('/^data:video\/(mp4|webm|x-msvideo|quicktime|x-matroska|x-flv|x-ms-wmv|mpeg|3gpp);base64,/'$fileData)) {
  1346.             // Added more video extensions
  1347.             if (preg_match('/^data:video\/mp4;base64,/'$fileData)) {
  1348.                 $extension 'mp4'// MP4
  1349.             } elseif (preg_match('/^data:video\/webm;base64,/'$fileData)) {
  1350.                 $extension 'webm'// WebM
  1351.             } elseif (preg_match('/^data:video\/x-msvideo;base64,/'$fileData)) {
  1352.                 $extension 'avi'// AVI
  1353.             } elseif (preg_match('/^data:video\/quicktime;base64,/'$fileData)) {
  1354.                 $extension 'mov'// MOV
  1355.             } elseif (preg_match('/^data:video\/x-matroska;base64,/'$fileData)) {
  1356.                 $extension 'mkv'// MKV
  1357.             } elseif (preg_match('/^data:video\/x-flv;base64,/'$fileData)) {
  1358.                 $extension 'flv'// FLV
  1359.             } elseif (preg_match('/^data:video\/x-ms-wmv;base64,/'$fileData)) {
  1360.                 $extension 'wmv'// WMV
  1361.             } elseif (preg_match('/^data:video\/mpeg;base64,/'$fileData)) {
  1362.                 $extension 'mpeg'// MPEG
  1363.             } elseif (preg_match('/^data:video\/3gpp;base64,/'$fileData)) {
  1364.                 $extension '3gp'// 3GP
  1365.             }
  1366.         }
  1367.         // Remove the "data:image/png;base64," or "data:application/pdf;base64," prefix to get the actual base64-encoded content
  1368.         $base64Content preg_replace('/^data:(image\/png|application\/(pdf|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.ms-excel)|video\/(mp4|webm|x-msvideo|quicktime|x-matroska|x-flv|x-ms-wmv|mpeg|3gpp));base64,/'''$fileData);
  1369.         // Decode the base64-encoded content
  1370.         $fileContent base64_decode($base64Content);
  1371.         // Validate the decoded content
  1372.         if ($fileContent === false) {
  1373.             return false// Invalid base64-encoded content
  1374.         }
  1375.         
  1376.         // Create the Pimcore asset
  1377.         $asset = new \Pimcore\Model\Asset();
  1378.         $parent Asset\Service::createFolderByPath('/Reports/uploaded_files/'. ($type ?? '')); // General folder path
  1379.         $asset->setFilename($filename); // Replace with the desired filename and extension
  1380.         $asset->setParent($parent);
  1381.         $asset->setData($fileContent);
  1382.         // Set the MIME type based on the file extension
  1383.         $mimeType '';
  1384.         if ($extension === 'pdf') {
  1385.             $mimeType 'application/pdf';
  1386.         } elseif ($extension === 'jpg') {
  1387.             $mimeType 'image/jpeg';
  1388.         } elseif ($extension === 'png') {
  1389.             $mimeType 'image/png';
  1390.         } elseif ($extension === 'docx') {
  1391.             $mimeType 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  1392.         } elseif ($extension === 'xlsx') {
  1393.             $mimeType 'application/vnd.ms-excel';
  1394.         } elseif ($extension === 'mp4') {
  1395.             $mimeType 'video/mp4'// Video MP4
  1396.         } elseif ($extension === 'webm') {
  1397.             $mimeType 'video/webm'// Video WebM
  1398.         } elseif ($extension === 'avi') {
  1399.             $mimeType 'video/x-msvideo'// Video AVI
  1400.         } elseif ($extension === 'mov') {
  1401.             $mimeType 'video/quicktime'// Video MOV
  1402.         } elseif ($extension === 'mkv') {
  1403.             $mimeType 'video/x-matroska'// Video MKV
  1404.         } elseif ($extension === 'flv') {
  1405.             $mimeType 'video/x-flv'// Video FLV
  1406.         } elseif ($extension === 'wmv') {
  1407.             $mimeType 'video/x-ms-wmv'// Video WMV
  1408.         } elseif ($extension === 'mpeg') {
  1409.             $mimeType 'video/mpeg'// Video MPEG
  1410.         } elseif ($extension === '3gp') {
  1411.             $mimeType 'video/3gpp'// Video 3GP
  1412.         }
  1413.         // Validate the MIME type
  1414.         if (!in_array($mimeType, ['image/jpeg''image/png''application/pdf''application/vnd.openxmlformats-officedocument.wordprocessingml.document''application/vnd.ms-excel''video/mp4''video/webm''video/x-msvideo''video/quicktime''video/x-matroska''video/x-flv''video/x-ms-wmv''video/mpeg''video/3gpp'])) {
  1415.             return false// Invalid MIME type
  1416.         }
  1417.         $asset->setType($mimeType);
  1418.         // Save the asset
  1419.         $asset->save();
  1420.         return $asset;
  1421.     }
  1422.     public function publishAdvanceCustomReport($user$params$translator$logger)
  1423.     {
  1424.         try {
  1425.             $cityNames '';
  1426.             // Set default values for new parameters
  1427.             $params['isAWSReport'] = isset($params['isAWSReport']) ? $params['isAWSReport'] : false;
  1428.             $params['weather_stations'] = isset($params['weather_stations']) ? $params['weather_stations'] : [];
  1429.             if ($params['isAWSReport']) {
  1430.                 // Handle AWS Weather Station report
  1431.                 if (!empty($params['weather_stations'])) {
  1432.                     $stations = new \Pimcore\Model\DataObject\WeatherStations\Listing();
  1433.                     $stations->setCondition('o_id IN (?)', [$params['weather_stations']]);
  1434.                     $stations->load();
  1435.                     if ($stations->getCount() > 0) {
  1436.                         foreach ($stations as $station) {
  1437.                             $nameEN $station->getName('en');
  1438.                             $nameAR $station->getName('ar');
  1439.                             $cityNames .= !empty($nameEN) ? $nameEN ',' '';
  1440.                             $cityNames .= !empty($nameAR) ? $nameAR ',' '';
  1441.                         }
  1442.                     } else {
  1443.                         return ["success" => false"message" => "invalid_weather_station"];
  1444.                     }
  1445.                     // Remove the trailing comma
  1446.                     $cityNames rtrim($cityNames',');
  1447.                 }
  1448.             } else {
  1449.                 // Handle regular Governorate report
  1450.                 if (!empty($params['locations'])) {
  1451.                     $cities = new \Pimcore\Model\DataObject\Governorate\Listing();
  1452.                     $cities->setCondition('governoteId IN (?)', [$params['locations']]);
  1453.                     $cities->load();
  1454.                     if ($cities->getCount() > 0) {
  1455.                         foreach ($cities as $city) {
  1456.                             $nameEN $city->getCityName('en');
  1457.                             $nameAR $city->getCityName('ar');
  1458.                             $cityNames .= !empty($nameEN) ? $nameEN ',' '';
  1459.                             $cityNames .= !empty($nameAR) ? $nameAR ',' '';
  1460.                         }
  1461.                     } else {
  1462.                         return ["success" => false"message" => "invalid_location"];
  1463.                     }
  1464.                     // Remove the trailing comma
  1465.                     $cityNames rtrim($cityNames',');
  1466.                 }
  1467.             }
  1468.             if (isset($params['report_id'])) {
  1469.                 $report Report::getById($params['report_id'], true);
  1470.                 if (!$report instanceof Report) {
  1471.                     return ["success" => false"message" => "invalid_report_id"];
  1472.                 }
  1473.             } else {
  1474.                 $report = new Report();
  1475.                 $report->setKey(\Pimcore\Model\Element\Service::getValidKey($user->getEmail() . uniqid(), 'object'));
  1476.                 $report->setParent(\Pimcore\Model\DataObject\Service::createFolderByPath("/Report/Report/advance_custom_report/"));
  1477.             }
  1478.             $reportType '';
  1479.             $report->setCreatedBy($user);
  1480.             $report->setCreatedOn(Carbon::now());
  1481.             $report->setStartDate(Carbon::parse(new \DateTime($params['start_date'])));
  1482.             $report->setEndDate(Carbon::parse(new \Datetime($params['end_date'])));
  1483.             $report->setSearchData($cityNames);
  1484.             $report->setLang($params['lang']);
  1485.             // $report->setEmail($user->getEmail());
  1486.             $report->setJsonData(json_encode($params['data']));
  1487.             if (isset($params['titleEn'])) {
  1488.                 $report->setReportTitle($params['titleEn'], "en");
  1489.             }
  1490.             if (isset($params['titleAr'])) {
  1491.                 $report->setReportTitle($params['titleAr'], "ar");
  1492.             }
  1493.             if (isset($params['descriptionEn'])) {
  1494.                 $report->setDescription($params['descriptionEn'], "en");
  1495.             }
  1496.             if (isset($params['descriptionAr'])) {
  1497.                 $report->setDescription($params['descriptionAr'], "ar");
  1498.             }
  1499.             if (isset($params['reportDisclaimerEn'])) {
  1500.                 $report->setReportDisclaimer($params['reportDisclaimerEn'], "en");
  1501.             }
  1502.             if (isset($params['reportDisclaimerAr'])) {
  1503.                 $report->setReportDisclaimer($params['reportDisclaimerAr'], "ar");
  1504.             }
  1505.             if (isset($params['additionalNoteEn'])) {
  1506.                 $report->setAdditionalNote($params['additionalNoteEn'], "en");
  1507.             }
  1508.             if (isset($params['additionalNoteAr'])) {
  1509.                 $report->setAdditionalNote($params['additionalNoteAr'], "ar");
  1510.             }
  1511.             if (isset($params['publishOnPdf'])) {
  1512.                 $report->setPublishOnPdf($params['publishOnPdf'] == true  true false);
  1513.             }
  1514.             if (isset($params['report_type_id'])) {
  1515.                 $reportType ReportType::getById($params['report_type_id'], true);
  1516.                 if ($reportType instanceof ReportType) {
  1517.                     $report->setReportType($reportType);
  1518.                     // if($reportType->getKey()!='CustomWeatherReport'|| $reportType->getKey()!='MashaerWeatherReport'){
  1519.                     //     $report->setForPublicPortal(true);
  1520.                     //     $report->setForAjwaaPortal(true);
  1521.                     // }
  1522.                 }
  1523.             }
  1524.             if (!empty($params['organizations'])) {
  1525.                 $selectedOrganizations = [];
  1526.                 if ($params['organizations'][0] == 0) {
  1527.                     // $organizations= new Organization\Listing();
  1528.                     // if ( $organizations->count() > 0) {
  1529.                     //     foreach ($organizations as $organization) {
  1530.                     //         if ($organization) {
  1531.                     //             $selectedOrganizations[] = $organization;
  1532.                     //         }
  1533.                     //     }
  1534.                     //     $report->setOrganization($selectedOrganizations);
  1535.                     // }
  1536.                 } else {
  1537.                     foreach ($params['organizations'] as $organization) {
  1538.                         $organizationObject Organization::getById($organizationtrue);
  1539.                         if ($organizationObject) {
  1540.                             $selectedOrganizations[] = $organizationObject;
  1541.                         }
  1542.                     }
  1543.                     $report->setOrganization($selectedOrganizations);
  1544.                 }
  1545.             }
  1546.             $emails "";
  1547.             if (!empty($params['channels'])) {
  1548.                 $channels = ['public_portal''ajwaa_portal''email''twitter''sms'];
  1549.                 foreach ($params['channels'] as $channel) {
  1550.                     if ($channel == 'public_portal') {
  1551.                         $report->setForPublicPortal(true);
  1552.                     } elseif ($channel == 'ajwaa_portal') {
  1553.                         $report->setForAjwaaPortal(true);
  1554.                         if (isset($params['send_email'])) {
  1555.                             $report->setSendEmail(true);
  1556.                         }
  1557.                     } elseif ($channel == 'email') {
  1558.                         $report->setForEmailChannel(true);
  1559.                         $emails .= implode(","$params['emails']);
  1560.                     } elseif ($channel == 'twitter') {
  1561.                         $report->setForTwitterChannel(true);
  1562.                     }
  1563.                 }
  1564.             }
  1565.             $emailArray = [];
  1566.             if (isset($params['user_group_ids']) && !empty($params['user_group_ids'])) {
  1567.                 $userGroupIds = ($params['user_group_ids']);
  1568.                 foreach ($userGroupIds as $userGroupId) {
  1569.                     if ($userGroupId) {
  1570.                         $userGroup \Pimcore\Model\DataObject\EwsAndReportUserGroup::getById($userGroupIdtrue);
  1571.                         if ($userGroup instanceof \Pimcore\Model\DataObject\EwsAndReportUserGroup) {
  1572.                             foreach (json_decode($userGroup->getJsonData()) as $currentUser) {
  1573.                                 if (isset($currentUser->email)) {
  1574.                                     $report->setForEmailChannel(true);
  1575.                                     $emailArray[] = $currentUser->email;
  1576.                                 }
  1577.                             }
  1578.                         }
  1579.                     }
  1580.                 }
  1581.             }
  1582.             if (!empty($emailArray)) {
  1583.                 if (!empty($emails)) {
  1584.                     $emails .= ',' implode(','$emailArray);
  1585.                 } else {
  1586.                     $emails implode(','$emailArray);
  1587.                 }
  1588.             }
  1589.             $report->setIsAWSReport($params['isAWSReport']);
  1590.             $report->setEmails($emails);
  1591.             $report->setPublished(true);
  1592.             // delete the existing pdf if report is updated
  1593.             if (isset($params['report_id'])) {
  1594.                 $pdfEn $report->getAsset();
  1595.                 $pdfAr $report->getAssetAr();
  1596.                 if ($pdfEn instanceof Asset) {
  1597.                     $pdfEn->delete();
  1598.                 }
  1599.                 if ($pdfAr instanceof Asset) {
  1600.                     $pdfAr->delete();
  1601.                 }
  1602.             }
  1603.             $report->save();
  1604.             // //$phpPath = 'D:\laragon\bin\php\php-8.1.10-Win32-vs16-x64\php.exe'; // Adjust to the actual PHP path on your system
  1605.             // $consolePath = 'bin\console'; // Use backslashes for Windows paths
  1606.             // $commandArguments = ['bin/console', 'app:today-weather-pdf'];
  1607.             // if(!empty($reportType)){
  1608.             //     if($reportType->getKey()!='CustomWeatherReport' || $reportType->getKey()!='MashaerWeatherReport'){
  1609.             //         $process = new Process($commandArguments);
  1610.             //         $process->setWorkingDirectory(PIMCORE_PROJECT_ROOT);
  1611.             //         try {
  1612.             //             $process->mustRun();
  1613.             //             $logger->info("Today Weather command executed successfully: " . $process->getOutput());
  1614.             //             // p_r("Today Weather command executed successfully: " . $process->getOutput());exit;
  1615.             //             $result['success'] = true;
  1616.             //             $result['message'] = $process->getOutput();
  1617.             //         } catch (ProcessFailedException $exception) {
  1618.             //             $logger->error("Today Weather command failed: " . $exception->getMessage());
  1619.             //             // p_r("Today Weather command failed: " . $exception->getMessage());exit;
  1620.             //             $result['success'] = false;
  1621.             //             $result['message'] = "Failed to execute notification command.";
  1622.             //         }
  1623.             //     }
  1624.             // }
  1625.             if (isset($params['report_id'])) {
  1626.                 return ["success" => true"message" => $translator->trans("report_updated_successfully"), "data" => $report->getId()];
  1627.             } else {
  1628.                 return ["success" => true"message" => $translator->trans("report_published_successfully"), "data" => $report->getId()];
  1629.             }
  1630.         } catch (\Exception $ex) {
  1631.             return ["success" => false"message" => $ex->getMessage()];
  1632.         }
  1633.     }
  1634.     public function archiveWeatherReport($translator$user$reportId)
  1635.     {
  1636.         $report Report::getById($reportId);
  1637.         if ($report->getPublished()) {
  1638.             $report->setPublished(false);
  1639.             $report->setSoftDelete(true);
  1640.             $report->save();
  1641.             return ["success" => true"message" => $translator->trans("archive_weather_report")];
  1642.         } else {
  1643.             return ["success" => false"message" => $translator->trans("report_not_found")];
  1644.         }
  1645.     }
  1646.     public function generatePdfReport($request$user$snappy$translator)
  1647.     {
  1648.         // Parse request parameters
  1649.         $params json_decode($request->getContent(), true);
  1650.         if (empty($params['id'])) {
  1651.             return [
  1652.                 "success" => false,
  1653.                 "message" => $translator->trans("missing_required_parameters")
  1654.             ];
  1655.         }
  1656.         // Fetch the report
  1657.         $report Report::getById($params['id'], true);
  1658.         $lang $params['lang'] ?? "en";
  1659.         if (!$report instanceof Report) {
  1660.             return [
  1661.                 "success" => false,
  1662.                 "message" => $translator->trans("no_report_found")
  1663.             ];
  1664.         }
  1665.         // Check for existing asset
  1666.         $asset $lang === 'ar' $report->getAssetAr() : $report->getAsset();
  1667.         if ($asset) {
  1668.             $pdfUrl API_BASE_URL $asset->getPath() . $asset->getFilename();
  1669.             return ['success' => true'data' => $pdfUrl];
  1670.         }
  1671.         // Determine the template and path based on the report type
  1672.         $templates = [
  1673.             'arabian-gulf-report' => 'pdfReportTemplates/arabian-gulf-report.html.twig',
  1674.             'red-sea-report' => 'pdfReportTemplates/red-sea-report.html.twig',
  1675.             'custom-weather-report' => 'pdfReportTemplates/custom-weather-report.html.twig',
  1676.             '10-day-forecast-report' => 'pdfReportTemplates/ten-day-forecast-report.html.twig',
  1677.             'mashaer-weather-report' => 'pdfReportTemplates/mashaer-weather-report.html.twig',
  1678.             'advance-custom-weather-report' => 'pdfReportTemplates/advance-custom-weather-report.html.twig',
  1679.         ];
  1680.         $defaultTemplate 'pdfReportTemplates/automatic_report_pdf_template.html.twig';
  1681.         $reportKey $report->getReportType()?->getReportkey();
  1682.         $template $templates[$reportKey] ?? $defaultTemplate;
  1683.         // Determine report path
  1684.         $reportPaths = [
  1685.             'red-sea-report' => '/report/advanceCustomReportPdf',
  1686.             'custom-weather-report' => '/report/advanceCustomReportPdf',
  1687.             '10-day-forecast-report' => '/report/advanceCustomReportPdf',
  1688.             'mashaer-weather-report' => '/report/advanceCustomReportPdf',
  1689.             'advance-custom-weather-report' => '/report/advanceCustomReportPdf',
  1690.         ];
  1691.         $reportPath $reportPaths[$reportKey] ?? '/report/ReportPdf';
  1692.         // Prepare parameters for PDF generation
  1693.         $parameter = [
  1694.             'data' => $report,
  1695.             'reportTitleEn' => $report->getReportTitle('en'),
  1696.             'reportTitleAr' => $report->getReportTitle('ar'),
  1697.             'reportDescriptionEn' => $report->getDescription('en'),
  1698.             'reportDescriptionAr' => $report->getDescription('ar'),
  1699.             'reportDisclaimerEn' => $report->getReportDisclaimer('en'),
  1700.             'reportDisclaimerAr' => $report->getReportDisclaimer('ar'),
  1701.             'additionalNoteEn' => $report->getAdditionalNote('en'),
  1702.             'additionalNoteAr' => $report->getAdditionalNote('ar'),
  1703.             'stateOfTheSeaEn' => $report->getStateOfTheSea('en'),
  1704.             'stateOfTheSeaAr' => $report->getStateOfTheSea('ar'),
  1705.             'waveHeightEn' => $report->getWaveHeight('en'),
  1706.             'waveHeightAr' => $report->getWaveHeight('ar'),
  1707.             'surfaceWindEn' => $report->getSurfaceWind('en'),
  1708.             'surfaceWindAr' => $report->getSurfaceWind('ar'),
  1709.             'publishOnPdf' => (bool)$report->getPublishOnPdf(),
  1710.             'reportTypeNameEn' => $report->getReportType()?->getName('en'),
  1711.             'reportTypeNameAr' => $report->getReportType()?->getName('ar'),
  1712.             'reportType' => $reportKey,
  1713.             'template' => $template,
  1714.             'lang' => $lang,
  1715.         ];
  1716.         // Generate PDF
  1717.         try {
  1718.             $pdf \App\Lib\Utility::generatePdf($parameter$snappy);
  1719.         } catch (\Exception $e) {
  1720.             return [
  1721.                 'success' => false,
  1722.                 'message' => $translator->trans("pdf_generation_failed"),
  1723.                 'error' => $e->getMessage(),
  1724.             ];
  1725.         }
  1726.         // Set file name and report path
  1727.         $pdfReportName = ($report->getReportType()?->getName($lang) ?? 'Report') . '_' date('d-m-Y') . '.pdf';
  1728.         $reportPath .= '/' $report->getId();
  1729.         // Create asset
  1730.         $asset \App\Lib\Utility::createAsset($pdf$pdfReportName$reportPath);
  1731.         if (!$asset instanceof Asset) {
  1732.             return [
  1733.                 'success' => false,
  1734.                 'message' => $translator->trans("asset_creation_failed"),
  1735.             ];
  1736.         }
  1737.         // Save the asset to the report
  1738.         if ($lang === 'ar') {
  1739.             $report->setAssetAr($asset);
  1740.         } else {
  1741.             $report->setAsset($asset);
  1742.         }
  1743.         $report->save();
  1744.         // Return the asset URL
  1745.         $pdfUrl API_BASE_URL $asset->getPath() . $asset->getFilename();
  1746.         return ['success' => true'data' => $pdfUrl];
  1747.     }
  1748. }