<?php
namespace App\Controller\SunHospital;
use Pimcore\Translation\Translator;
use App\Validator\Validator;
use Symfony\Component\HttpFoundation\Request;
use App\Model\SunHospital\HomePage;
use Pimcore\Model\DataObject;
use Symfony\Component\Routing\Annotation\Route;
use App\Helper\MailHelper;
use App\Helper\LogHelper;
use App\Model\SunHospital\NewscategoryModel;
use App\Model\SunHospital\NewsModel;
use App\Model\SunHospital\DoctorsModel;
use Pimcore\Model\DataObject\Newscategory;
use App\Services\CaptchaService;
/**
* @Route("/api/sun-hospital/homepage")
*/
class HomepageController extends BaseController
{
protected $translator;
protected $validator;
protected $orderCount;
public function __construct(
Translator $translator,
Validator $validator,
)
{
$this->translator = $translator;
$this->validator = $validator;
}
/**
* @Route("/list", methods={"GET"})
*/
public function listing(Request $request)
{
try {
$locale = $request->get('locale');
$listing = new DataObject\HomePage\Listing();
$listing->setOrderKey('o_modificationDate');
$listing->setOrder('DESC');
$response = [
'data' => [],
];
foreach ($listing as $item) {
$homePageData = HomePage::getDetailJson($item, $locale);
if ($homePageData) {
$response['data'][] = $homePageData;
}
}
return $this->sendResponse($response);
} catch (\Throwable $e) {
return $this->sendError($e->getMessage(), 500);
}
}
/**
* @Route("/news/list", methods={"GET"})
*/
public function listNews(Request $request)
{
try {
$condStr = 'siteId = :siteId';
$condArr = [
'siteId' => $this->getSiteByName('SunHospital')->getId(),
];
$listing = new Newscategory\Listing();
$listing->setCondition($condStr, $condArr);
$response = [
'all' => [],
'data' => [],
];
// Lấy 3 new mới nhất
$dataAllNews = [];
$news = new DataObject\News\Listing();
$news->setOrderKey('o_modificationDate');
$news->setOrder('desc');
$news->setLimit(3);
$news->setCondition($condStr, $condArr);
foreach($news as $new) {
$response['all'][] = NewsModel::getNewsJson($new,'');
}
// Lấy tất cả dữ liệu category và new nằm trong category đó
$data =[];
foreach ($listing as $item){
$data[] = NewscategoryModel::getDetailJson($item);
}
$dataNews = [];
foreach($data as $item) {
$conStrNews = '';
$dataNews = [];
$conStrNews = 'siteId = :siteId';
$condArr = [
'siteId' => $this->getSiteByName('SunHospital')->getId(),
];
$conStrNews .= ' AND newscategory__id = '.$item['id'].'';
$news->setOrderKey('o_modificationDate');
$news->setOrder('desc');
$news->setLimit(3);
$news->setCondition($conStrNews, $condArr);
foreach($news as $new) {
$dataNews[] = NewsModel::getNewsJson($new,$item);
}
$response['data'][] = (object) array('category' => $item, 'news' => $dataNews);
}
return $this->sendResponse($response);
}
catch (\Throwable $e) {
return $this->sendError($e->getMessage(), 500);
}
}
/**
* @Route("/doctors/list", methods={"GET"})
*/
public function listDoctors(Request $request)
{
try {
$locale = $request->get('locale');
$listing = new DataObject\HospitalDoctor\Listing();
$listing->setOrderKey('o_modificationDate');
$listing->setOrder('DESC');
// Filter by specialist if provided
$specialistId = $request->get('specialist') ?: $request->get('specialistId');
if ($specialistId) {
$specialist = DataObject\HospitalSpecialist::getById((int) $specialistId);
if ($specialist) {
$listing->filterBySpecialis($specialist);
}
}
$limit = (int) $request->get('limit') ?: 10;
if ($limit > 0) {
$listing->setLimit($limit);
}
$response = [
'data' => [],
];
foreach ($listing as $doctor) {
$dataDoctor = DoctorsModel::getListing($doctor, $locale);
if ($dataDoctor) {
$response['data'][] = $dataDoctor;
}
}
return $this->sendResponse($response);
} catch (\Throwable $e) {
return $this->sendError($e->getMessage(), 500);
}
}
/**
* @Route("/booking", methods={"POST"})
*/
public function booking(Request $request) {
try {
$conditions = [
'name' => 'required|length:max,100',
'time' => 'required',
'healthProblem' => 'required|length:max,500',
'phone' => 'required|regex:^[0-9+\-]{8,15}$',
'birthday' => 'required|date',
'healthService' => 'required',
'specialist' => 'required',
'gender' => 'required',
'emailCustomer' => 'required|email',
];
$errorMessages = $this->validator->validate($conditions, $request);
if ($errorMessages) return $this->sendValidatorError($errorMessages);
if (!CaptchaService::verifyCaptchaV3($request)) {
return $this->sendError('Invalid captcha!');
}
$params = [];
foreach ($conditions as $field => $condition) {
$params[$field] = $request->get($field);
}
$params['customerCode'] = $request->get('customerCode') ?? '';
$documentPath = "/SunHospital/emails/booking-email";
$result = self::send($documentPath, $params, []);
if($result && isset($result['success']) && $result['success']) {
return $this->sendResponse([
'message' => 'Email sent successfully',
'from' => $result['from'] ?? null,
'to' => $result['to'] ?? null,
]);
}
$errorMessage = $result['error'] ?? 'Unable to send email';
return $this->sendError([
'message' => $errorMessage,
'from' => $result['from'] ?? null,
'to' => $result['to'] ?? null,
], 500);
}
catch (\Throwable $e) {
return $this->sendError($e->getMessage(), 500);
}
}
private static function send(string $documentPath, array $params, array $emails, string $subject = '')
{
$fromEmail = null;
$toEmails = [];
$validToEmails = [];
try {
$document = \Pimcore\Model\Document::getByPath($documentPath);
if (!$document) {
throw new \Exception("Document not found: {$documentPath}");
}
$mail = new \Pimcore\Mail();
$mail->setDocument($documentPath);
// Get from email
$fromEmail = \Pimcore\Config::getWebsiteConfig()->get('sender_email_address') ?? 'stg-noreply@sungroup.com.vn';
$mail->from($fromEmail);
$mail->setParams($params);
if ($subject) {
$mail->setSubject($subject);
}
// Get to emails from document if emails array is empty
if (empty($emails) && $document) {
$documentTo = $document->getTo();
if ($documentTo) {
$parsedTo = \Pimcore\Helper\Mail::parseEmailAddressField($documentTo);
$toEmails = array_column($parsedTo, 'email');
}
} else {
$toEmails = $emails;
}
// Validate and set email recipients
$hasValidEmail = false;
foreach ($toEmails as $key => $address) {
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
LogHelper::log('helper_mail', (string) ("Invalid email address: " . $address ."\n \n"));
continue;
}
$validToEmails[] = $address;
if ($key === 0) {
$mail->to($address);
} else {
$mail->addTo($address);
}
$hasValidEmail = true;
}
// Check if we have at least one valid recipient
if (!$hasValidEmail) {
throw new \Exception("No valid email recipient found. Document: {$documentPath}");
}
// Send email - this will throw exception if fails
try {
$mail->send();
// If send() completes without exception, email was sent successfully
// Log success for debugging
LogHelper::log('helper_mail', (string) ("Email sent successfully. From: {$fromEmail}, To: " . implode(', ', $validToEmails) . "\n"));
return [
'success' => true,
'from' => $fromEmail,
'to' => $validToEmails,
];
} catch (\Throwable $sendException) {
// If send() throws exception, email was not sent
LogHelper::log('helper_mail', (string) ("Failed to send email: " . $sendException->getMessage() . "\n"));
throw new \Exception("Failed to send email: " . $sendException->getMessage(), 0, $sendException);
}
} catch (\Throwable $e) {
LogHelper::log('helper_mail', (string) ("Error in send method: " . $e->getMessage() . "\n"));
return [
'success' => false,
'from' => $fromEmail,
'to' => $validToEmails,
'error' => $e->getMessage(),
];
}
}
}