src/Controller/SunHospital/HomepageController.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\Controller\SunHospital;
  3. use Pimcore\Translation\Translator;
  4. use App\Validator\Validator;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use App\Model\SunHospital\HomePage;
  7. use Pimcore\Model\DataObject;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use App\Helper\MailHelper;
  10. use App\Helper\LogHelper;
  11. use App\Model\SunHospital\NewscategoryModel;
  12. use App\Model\SunHospital\NewsModel;
  13. use App\Model\SunHospital\DoctorsModel;
  14. use Pimcore\Model\DataObject\Newscategory;
  15. use App\Services\CaptchaService;
  16. /**
  17.  * @Route("/api/sun-hospital/homepage")
  18.  */
  19. class HomepageController extends BaseController
  20. {
  21.     protected $translator;
  22.     protected $validator;
  23.     protected $orderCount;
  24.     public function __construct(
  25.         Translator $translator,
  26.         Validator $validator,
  27.     )
  28.     {
  29.         $this->translator $translator;
  30.         $this->validator $validator;
  31.     }
  32.     /**
  33.      * @Route("/list", methods={"GET"})
  34.      */
  35.     public function listing(Request $request)
  36.     {
  37.         try {
  38.             $locale $request->get('locale');
  39.             $listing = new DataObject\HomePage\Listing();
  40.             $listing->setOrderKey('o_modificationDate');
  41.             $listing->setOrder('DESC');
  42.             $response = [
  43.                 'data' => [],
  44.             ];
  45.             foreach ($listing as $item) {
  46.                 $homePageData HomePage::getDetailJson($item$locale);
  47.                 if ($homePageData) {
  48.                     $response['data'][] = $homePageData;
  49.                 }
  50.             }
  51.             return $this->sendResponse($response);
  52.         } catch (\Throwable $e) {
  53.             return $this->sendError($e->getMessage(), 500);
  54.         }
  55.     }
  56.      /**
  57.      * @Route("/news/list", methods={"GET"})
  58.      */
  59.     public function listNews(Request $request)
  60.     {
  61.         try {
  62.             
  63.             $condStr 'siteId = :siteId';
  64.             $condArr = [
  65.                 'siteId' => $this->getSiteByName('SunHospital')->getId(),
  66.             ];
  67.             $listing = new Newscategory\Listing();
  68.             $listing->setCondition($condStr$condArr);           
  69.             $response = [
  70.                 'all' => [],
  71.                 'data' => [],
  72.             ];
  73.             // Lấy 3 new mới nhất
  74.             $dataAllNews = [];            
  75.             $news = new DataObject\News\Listing();
  76.             $news->setOrderKey('o_modificationDate');
  77.             $news->setOrder('desc');
  78.             $news->setLimit(3);
  79.             $news->setCondition($condStr$condArr);
  80.             foreach($news as $new) {
  81.                 $response['all'][] =  NewsModel::getNewsJson($new,'');                   
  82.             }
  83.             // Lấy tất cả dữ liệu category và new nằm trong category đó
  84.             $data =[];
  85.             foreach ($listing as $item){
  86.                 $data[] = NewscategoryModel::getDetailJson($item);                          
  87.             }
  88.             $dataNews = [];
  89.             
  90.             foreach($data as $item) {
  91.                 $conStrNews '';
  92.                 $dataNews = [];
  93.                 $conStrNews 'siteId = :siteId';
  94.                 $condArr = [
  95.                     'siteId' => $this->getSiteByName('SunHospital')->getId(),
  96.                 ];
  97.                 $conStrNews .= ' AND newscategory__id = '.$item['id'].'';
  98.                 $news->setOrderKey('o_modificationDate');
  99.                 $news->setOrder('desc');
  100.                 $news->setLimit(3);
  101.                 $news->setCondition($conStrNews$condArr);                 
  102.                 foreach($news as $new) {
  103.                     $dataNews[] =  NewsModel::getNewsJson($new,$item);                   
  104.                 }
  105.                 $response['data'][] = (object) array('category' => $item'news' => $dataNews);                 
  106.             }
  107.             return $this->sendResponse($response);
  108.         }
  109.         catch (\Throwable $e) {
  110.             return $this->sendError($e->getMessage(), 500);
  111.         }
  112.     }
  113.     /**
  114.      * @Route("/doctors/list", methods={"GET"})
  115.      */
  116.     public function listDoctors(Request $request)
  117.     {
  118.         try {
  119.             $locale $request->get('locale');
  120.             
  121.             $listing = new DataObject\HospitalDoctor\Listing();
  122.             $listing->setOrderKey('o_modificationDate');
  123.             $listing->setOrder('DESC');
  124.             // Filter by specialist if provided
  125.             $specialistId $request->get('specialist') ?: $request->get('specialistId');
  126.             if ($specialistId) {
  127.                 $specialist DataObject\HospitalSpecialist::getById((int) $specialistId);
  128.                 if ($specialist) {
  129.                     $listing->filterBySpecialis($specialist);
  130.                 }
  131.             }
  132.             $limit = (int) $request->get('limit') ?: 10;
  133.             if ($limit 0) {
  134.                 $listing->setLimit($limit);
  135.             }
  136.             $response = [
  137.                 'data' => [],
  138.             ];
  139.             foreach ($listing as $doctor) {
  140.                 $dataDoctor DoctorsModel::getListing($doctor$locale);
  141.                 if ($dataDoctor) {
  142.                     $response['data'][] = $dataDoctor;
  143.                 }
  144.             }
  145.             return $this->sendResponse($response);
  146.         } catch (\Throwable $e) {
  147.             return $this->sendError($e->getMessage(), 500);
  148.         }
  149.     }
  150.     /**
  151.      * @Route("/booking", methods={"POST"})
  152.      */
  153.     public function booking(Request $request) {
  154.         try {
  155.             $conditions = [
  156.                 'name'          => 'required|length:max,100',
  157.                 'time'          => 'required',
  158.                 'healthProblem' => 'required|length:max,500',
  159.                 'phone'         => 'required|regex:^[0-9+\-]{8,15}$',
  160.                 'birthday'      => 'required|date',
  161.                 'healthService' => 'required',
  162.                 'specialist'    => 'required',
  163.                 'gender'        => 'required',
  164.                 'emailCustomer' => 'required|email',
  165.             ];
  166.             $errorMessages $this->validator->validate($conditions$request);
  167.             if ($errorMessages) return $this->sendValidatorError($errorMessages);
  168.             if (!CaptchaService::verifyCaptchaV3($request)) {
  169.                 return $this->sendError('Invalid captcha!');
  170.             }
  171.             $params = [];
  172.             foreach ($conditions as $field => $condition) {
  173.                 $params[$field] = $request->get($field);
  174.             }            
  175.             $params['customerCode'] = $request->get('customerCode') ?? '';     
  176.             $documentPath "/SunHospital/emails/booking-email";                 
  177.             $result self::send($documentPath$params, []);
  178.             
  179.             if($result && isset($result['success']) && $result['success']) {
  180.                 return $this->sendResponse([
  181.                     'message' => 'Email sent successfully',
  182.                     'from' => $result['from'] ?? null,
  183.                     'to' => $result['to'] ?? null,
  184.                 ]);
  185.             }     
  186.             
  187.             $errorMessage $result['error'] ?? 'Unable to send email';
  188.             return $this->sendError([
  189.                 'message' => $errorMessage,
  190.                 'from' => $result['from'] ?? null,
  191.                 'to' => $result['to'] ?? null,
  192.             ], 500);
  193.         }
  194.         catch (\Throwable $e) {
  195.             return $this->sendError($e->getMessage(), 500);
  196.         }
  197.     }
  198.     private static function send(string $documentPath, array $params, array $emailsstring $subject '')
  199.     {
  200.         $fromEmail null;
  201.         $toEmails = [];
  202.         $validToEmails = [];
  203.         
  204.         try {
  205.             $document \Pimcore\Model\Document::getByPath($documentPath);
  206.             
  207.             if (!$document) {
  208.                 throw new \Exception("Document not found: {$documentPath}");
  209.             }
  210.             $mail = new \Pimcore\Mail();
  211.             $mail->setDocument($documentPath);
  212.             
  213.             // Get from email
  214.             $fromEmail \Pimcore\Config::getWebsiteConfig()->get('sender_email_address') ?? 'stg-noreply@sungroup.com.vn';
  215.             $mail->from($fromEmail);
  216.             $mail->setParams($params);
  217.             if ($subject) {
  218.                 $mail->setSubject($subject);
  219.             }
  220.             
  221.             // Get to emails from document if emails array is empty
  222.             if (empty($emails) && $document) {
  223.                 $documentTo $document->getTo();
  224.                 if ($documentTo) {
  225.                     $parsedTo \Pimcore\Helper\Mail::parseEmailAddressField($documentTo);
  226.                     $toEmails array_column($parsedTo'email');
  227.                 }
  228.             } else {
  229.                 $toEmails $emails;
  230.             }
  231.             
  232.             // Validate and set email recipients
  233.             $hasValidEmail false;
  234.             foreach ($toEmails as $key => $address) {
  235.                 if (!filter_var($addressFILTER_VALIDATE_EMAIL)) {
  236.                     LogHelper::log('helper_mail', (string) ("Invalid email address: " $address ."\n \n"));
  237.                     continue;
  238.                 }
  239.             
  240.                 $validToEmails[] = $address;
  241.                 if ($key === 0) {
  242.                     $mail->to($address);
  243.                 } else {
  244.                     $mail->addTo($address);
  245.                 }
  246.                 $hasValidEmail true;
  247.             }
  248.             
  249.             // Check if we have at least one valid recipient
  250.             if (!$hasValidEmail) {
  251.                 throw new \Exception("No valid email recipient found. Document: {$documentPath}");
  252.             }
  253.             // Send email - this will throw exception if fails
  254.             try {
  255.             $mail->send();
  256.                 
  257.                 // If send() completes without exception, email was sent successfully
  258.                 // Log success for debugging
  259.                 LogHelper::log('helper_mail', (string) ("Email sent successfully. From: {$fromEmail}, To: " implode(', '$validToEmails) . "\n"));
  260.                 
  261.                 return [
  262.                     'success' => true,
  263.                     'from' => $fromEmail,
  264.                     'to' => $validToEmails,
  265.                 ];
  266.             } catch (\Throwable $sendException) {
  267.                 // If send() throws exception, email was not sent
  268.                 LogHelper::log('helper_mail', (string) ("Failed to send email: " $sendException->getMessage() . "\n"));
  269.                 throw new \Exception("Failed to send email: " $sendException->getMessage(), 0$sendException);
  270.             }
  271.         } catch (\Throwable $e) {
  272.             LogHelper::log('helper_mail', (string) ("Error in send method: " $e->getMessage() . "\n"));
  273.             return [
  274.                 'success' => false,
  275.                 'from' => $fromEmail,
  276.                 'to' => $validToEmails,
  277.                 'error' => $e->getMessage(),
  278.             ];
  279.         }
  280.     }
  281. }