<?php
namespace App\Controller;
use App\Aws\SESManager;
use App\Entity\Clinic\Appointment;
use App\Entity\Clinic\Appointment\GoogleEvent;
use App\Entity\Clinic\Person\ClinicUser;
use App\Entity\Clinic\PriceTier\PromoCode;
use App\Entity\Organisation\Organisation;
use App\Entity\Patient\Payment\Kind;
use App\Entity\Person\Admin;
use App\Entity\Person\Patient;
use App\Entity\Person\SuperClinicAdmin;
use App\Entity\Person\User;
use App\Form\Model\MailChimpWebhookRequestType;
use App\Form\Type\AddPasswordType;
use App\Form\Type\LoginType;
use App\Form\Type\RecoveryType;
use App\Form\Type\RegistrationType;
use App\Model\MailChimp\MailChimpWebhookRequest;
use App\Services\AppHelper;
use App\Services\ClinicManager;
use App\Services\CreateClinicGiftVoucher;
use App\Services\CreateDefaultDataClinic;
use App\Services\CreateDefaultPaymentType;
use App\Services\MailChimp\MailChimpClientImpl;
use App\Services\MailChimp\MailChimpException;
use App\Services\UserManager;
use Psr\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use WhiteOctober\BreadcrumbsBundle\Model\Breadcrumbs;
use App\Entity\Clinic\Membership\Membership;
use App\Entity\Clinic\Clinic;
use App\Entity\Website;
use App\Services\MembershipService;
use App\Entity\Patient\UsedMembership;
use App\Entity\Patient\Payment;
use App\Services\InvoiceHistoryService;
use App\Entity\Patient\Invoice\InvoiceHistory;
use App\Entity\Patient\Invoice;
use App\Services\StripeService;
use App\Entity\UsedMembershipItems;
use App\Entity\Patient\UsedMembershipHistory;
use App\Entity\Clinic\GenericSystemEmails;
use App\Entity\Clinic\Stock\TreatmentClinic;
use App\Entity\Clinic\SystemEmails;
use App\Entity\Domain;
use App\Form\Model\SearchFilter;
use App\Entity\Communication;
use App\Services\Plivo;
use App\Services\Twilio;
use App\Services\SmsService;
use Exception;
/**
* Class DefaultController.
*/
class DefaultController extends AbstractController
{
/**
* @var Breadcrumbs
*/
private $breadcrumbs;
/**
* @var UserPasswordEncoderInterface
*/
private $userPasswordEncoder;
/**
* @var SESManager
*/
private $SESManager;
/**
* @var CreateDefaultDataClinic
*/
private $createDefaultDataClinic;
/**
* @var CreateDefaultPaymentType
*/
private $createDefaultPaymentType;
/**
* @var ClinicManager
*/
private $clinicManager;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var MembershipService
*/
private $membershipService;
/**
* @var InvoiceHistoryService
*/
private $historyService;
/**
* @var StripeService
*/
private $stripeService;
/**
* @var Twilio
*/
private $twilio;
/**
* @var Plivo
*/
private $plivo;
/**
* @var SmsService
*/
private $smsService;
public function __construct(
Breadcrumbs $breadcrumbs,
UserPasswordEncoderInterface $userPasswordEncoder,
SESManager $SESManager,
CreateDefaultDataClinic $createDefaultDataClinic,
CreateDefaultPaymentType $createDefaultPaymentType,
ClinicManager $clinicManager,
LoggerInterface $logger,
MembershipService $membershipService,
InvoiceHistoryService $historyService,
StripeService $stripeService,
Twilio $twilio,
Plivo $plivo,
SmsService $smsService
) {
$this->breadcrumbs = $breadcrumbs;
$this->userPasswordEncoder = $userPasswordEncoder;
$this->SESManager = $SESManager;
$this->createDefaultDataClinic = $createDefaultDataClinic;
$this->createDefaultPaymentType = $createDefaultPaymentType;
$this->clinicManager = $clinicManager;
$this->logger = $logger;
$this->membershipService = $membershipService;
$this->historyService = $historyService;
$this->stripeService = $stripeService;
$this->twilio = $twilio;
$this->plivo = $plivo;
$this->smsService = $smsService;
}
/**
* @Route("/", name="indexPage")
*/
public function index(AppHelper $appHelper)
{
$user = $this->getUser();
// $mainDomain='consentz.tribital.com';
$mainDomain = @$_ENV['APP_DOMAIN'];
$websiteDomain = @$_ENV['WEBSITE_DOMAIN'];
$domain = $_SERVER['HTTP_HOST'];
$subdomain = str_replace([$websiteDomain, '.'], '', $domain);
if ($domain != $mainDomain) {
$checkdomain = $this->getDoctrine()->getRepository(Domain::class)
->findOneBy(['domain' => $domain]);
if ($checkdomain && $checkdomain->getStatus() == 1) {
$website = $this->getDoctrine()->getRepository(Website::class)
->findOneBy(['clinic_id' => $checkdomain->getClinicId() ,'parent_id' => null, 'status' => 1]);
if ($website) {
$html = $website->getContent();
} else {
header('Location: ' . $_ENV['APP_URl']);
exit;
}
$getwidgeturl = $this->getDoctrine()->getRepository(Clinic::class)->findOneBy(['id' => $checkdomain->getClinicId()]);
$widgetUrl = $this->generateUrl('widget', ['subDomain' => $getwidgeturl->getSubDomain()]);
$html = str_replace('{BOOKING_SECTION}', '<iframe src="' . $widgetUrl . '" frameborder="0" id="builder_iframe" style="height: 100%; width: 100%;min-height: 945px;"></iframe>', $html);
$html = str_replace('{title}', $website->getTitle(), $html);
$html = str_replace('{faviconicon}', $website->getLogo(), $html);
$html .= '<style>'.$website->getCss().'</style>';
echo $html;
exit;
} elseif ($checkdomain && ($checkdomain->getStatus() || $checkdomain->getStatus() != 1)) {
header('Location: ' . $_ENV['APP_URl']);
exit;
} else {
header('Location: ' . $_ENV['APP_URl'] . 'booking/' . $subdomain);
exit;
// $subdomain=trim($domain,$mainDomain);
/*
$clinic=$this->getDoctrine()->getRepository(Clinic::class)
->findOneBy(['sub_domain'=>$subdomain ]);
if (!$clinic){
return new JsonResponse(['status' => 'error','message' => 'Clinic Not Exist' ]);
}
$em=$this->getDoctrine()->getManager();
$superClinincAdmin = new SuperClinicAdmin();
$appointment = $superClinincAdmin->getAppointmentData($em,$clinic->getId());
$filter = new SearchFilter();
$filter->setClinic($clinic);
$isPermission = false;
if($user){
$isPermission = $this->isGranted('edit', $clinic);
}
$isOnline = null;
$clinicId = $clinic->getId();
$repository = $em->getRepository('App:Clinic\Person\ClinicUser');
$queryBuilder = $repository->createQueryBuilder('user');
$queryBuilder->where('user.clinic = :clinicId')
->andWhere('user.deleted = FALSE')
->setParameter('clinicId', $clinicId)
->orderBy('user.createdAt', 'DESC');
$team = $queryBuilder->getQuery()->getResult();
if($user){
return $this->render('publicProfile.html.twig', [
'clinic' => $clinic,
'isOnline' => $isOnline,
'treatments' => $appointment['treatments'],
'isPermission' => $isPermission,
'users' =>$team,
]);
}
else{
return $this->render('newPublicProfile.html.twig', [
'clinic' => $clinic,
'isOnline' => $isOnline,
'treatments' => $appointment['treatments'],
'isPermission' => $isPermission,
'users' =>$team,
]);
}
*/
}
}
// $clinics = $this->getDoctrine()->getRepository(User::Class)->find(3229);
// $clinicData = $this->getDoctrine()->getRepository(Clinic::Class)->find(3);
// $clinics->setCurrentClinic($clinicData);
// $em = $this->getDoctrine()->getManager();
// $em->persist($clinics);
// $em->flush();
// dump($clinics); die;
return $appHelper->handleDefaultRoute($this->getUser());
}
/**
* @Route("/{slug}", name="indexPage")
*/
public function indexslug($slug){
$user = $this->getUser();
$mainDomain = @$_ENV['APP_DOMAIN'];
$websiteDomain = @$_ENV['WEBSITE_DOMAIN'];
$domain = $_SERVER['HTTP_HOST'];
$subdomain = str_replace([$websiteDomain, '.'], '', $domain);
if ($domain != $mainDomain) {
$checkdomain = $this->getDoctrine()->getRepository(Domain::class)
->findOneBy(['domain' => $domain]);
if ($checkdomain && $checkdomain->getStatus() == 1) {
$website = $this->getDoctrine()->getRepository(Website::class)
->findOneBy(['clinic_id' => $checkdomain->getClinicId(),'url'=>$slug, 'status' => 1]);
if ($website) {
$html = $website->getContent();
} else {
header('Location: ' . $_ENV['APP_URl']);
exit;
}
$parentWebsite = $this->getDoctrine()->getRepository(Website::class)
->findOneBy(['id' => $website->getParentId(),'parent_id' => null, 'status' => 1]);
$getwidgeturl = $this->getDoctrine()->getRepository(Clinic::class)->findOneBy(['id' => $checkdomain->getClinicId()]);
$widgetUrl = $this->generateUrl('widget', ['subDomain' => $getwidgeturl->getSubDomain()]);
$html = str_replace('{BOOKING_SECTION}', '<iframe src="' . $widgetUrl . '" frameborder="0" id="builder_iframe" style="height: 100%; width: 100%;min-height: 945px;"></iframe>', $html);
if($parentWebsite){
$html = str_replace('{title}', $parentWebsite->getTitle(), $html);
$html = str_replace('{faviconicon}', $parentWebsite->getLogo(), $html);
}else{
$html = str_replace('{title}', 'Consentz', $html);
$html = str_replace('{faviconicon}', '', $html);
}
// $html = str_replace('{title}', $parentWebsite->getTitle(), $html);
// $html = str_replace('{faviconicon}', $parentWebsite->getLogo(), $html);
echo $html;
exit;
} elseif ($checkdomain && ($checkdomain->getStatus() || $checkdomain->getStatus() != 1)) {
header('Location: ' . $_ENV['APP_URl']);
exit;
} else {
header('Location: ' . $_ENV['APP_URl'] . 'booking/' . $subdomain);
exit;
}
}
return $appHelper->handleDefaultRoute($this->getUser());
}
/**
* @Route("/admin/login", name="login")
* @Template("default/login.html.twig")
*
* @return array
*/
public function login(AuthenticationUtils $authenticationUtils)
{
$user = $this->getUser();
// dd($user);
if($user){
if($user->getLoginFrom() == 0){
$em = $this->getDoctrine()->getManager();
$user->setLoginFrom(1);
$em->persist($user);
$em->flush();
}
if ($user->getRole() == 'ROLE_CONSENTZ_ADMIN') {
return $this->redirectToRoute('organisation_list');
}else{
if ($user->getClinic() != null) {
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find($user->getClinic());
} else if ($user->getOrganisation() && $user->getOrganisation()->getClinics()->count() > 0 && $user->getRole() == 'ROLE_SUPER_CLINIC_ADMIN') {
$clinic = $user->getOrganisation()->getClinics()->first();
}
if ($clinic) {
return new RedirectResponse($this->generateUrl('appointments_calendar', ['clinicId' => $clinic->getId()]));
}
}
}
$form = $this->createForm(LoginType::class, ['username' => $authenticationUtils->getLastUsername()], [
'action' => $this->generateUrl('login_check'),
]);
if ($error = $authenticationUtils->getLastAuthenticationError()) {
$this->addFlash('danger', $error->getMessage());
}
$this->breadcrumbs->addItem('Welcome to Consentz');
return ['form' => $form->createView()];
}
//==============================for SMS reminder =========================================================(14-03-2023)//
/**
* @Route("/admin/send-sms-reminder", name="send_sms_reminder", options={"expose"=true}, methods={"GET"})
*/
public function sendSMSReminder(Request $request)
{
date_default_timezone_set('Europe/London');
$todayDat = date('Y-m-d');
$em = $this->getDoctrine()->getManager();
$appo_query = "SELECT appointment.id as appo_id,appointment.clinic_id,patient_id,clinic_user_id,treatment_clinic_id,start,end,clinics.name,clinics.email as clinic_email,clinics.verified_email,clinics.reminder_header,clinics.reminder_footer,user.phone,user.country_code,user.clinic_id as userclinicId,user.email,user.first_name, user.last_name, a.first_name as pract_first_name, a.last_name as pract_last_name, clinics.timezone as clinic_timezone FROM `appointment`
left join clinics on clinics.id = appointment.clinic_id
left join user on user.id = appointment.patient_id
left join user as a on a.id = appointment.clinic_user_id
WHERE start >= '" . $todayDat . "' and user.phone IS NOT NULL and appointment.status!='patientCanceled' group by appointment.id";
//echo $appo_query;exit;
$appointment = $em->getConnection()->prepare($appo_query);
$appointment->execute();
$appointmentList = $appointment->fetchAllAssociative();
$currentDate = date('d-m-Y H:i:s');
//echo $currentDate;
//echo "<br>";
foreach ($appointmentList as $list) {
$dt = new \DateTime($list['start'], new \DateTimeZone($list['clinic_timezone']));
// change the timezone of the object without changing its time
$dt->setTimezone(new \DateTimeZone('Europe/London'));
$list['start'] = $dt->format('Y-m-d H:i:s');
$appoitmentDate = date('d-m-Y H:i', strtotime($list['start']));
$d1 = new \DateTime($currentDate); // first date
$d2 = new \DateTime($appoitmentDate); // second date
$diff = $d1->diff($d2); // get difference between two dates
$years = $diff->y;
$months = $diff->m;
echo $days = $diff->d;
echo "<br>";
echo $hours = $diff->h;
echo "<br>";
echo $minutes = $diff->i;
echo "<br>";
echo $list['appo_id'] . 'clinic(' . $list['clinic_id'] . ')';
echo "<br>";
echo "====================";
echo "<br>";
$hourDiff = 1;
$cronHours = date('H:i', strtotime($currentDate));
$appoitmentHours = date('H:i', strtotime($appoitmentDate));
$sendingDate = date('l d M') . ' ' . $appoitmentHours;
$sendingDateForEmail = date('l d M');
$sendingDateForEmail = date('l d M', strtotime($list['start']));
//echo $sendingDate;exit;
if ($cronHours > $appoitmentHours) {
$hourDiff = 0;
}
//$hourDiff = 1;
if ($hourDiff == 1) {
if ($days == 0 && $years == 0 && $months == 0 && $minutes == 0 && $hours > 0) {
if ($hours == 1) {
$selectHours = '1 hour';
} else {
$selectHours = $hours . ' hours';
}
$reminder_query = "SELECT time,treatment_id FROM `reminder` WHERE time='" . $selectHours . "' and clinic_id = " . $list['clinic_id']; //reminder table
$reminder = $em->getConnection()->prepare($reminder_query);
$reminder->execute();
$reminderList = $reminder->fetchAllAssociative();
//==========new code for check treatment==============//
$checkRemindSendStatus = array();
foreach ($reminderList as $relist) {
array_push($checkRemindSendStatus, $relist['treatment_id']);
}
$arrayContainsNull = in_array(null, $checkRemindSendStatus);
//==========new code for check treatment==============//
//dd($checkRemindSendStatus);
if (!empty($reminderList)) {
if ($arrayContainsNull) {
//$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
if ($list['reminder_header'] !== '' && $list['reminder_footer'] != '') {
$message = "" . $list['reminder_header'] . " " . $sendingDate . " with " . $list['name'] . " . " . $list['reminder_footer'] . "";
} else {
$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
}
$to = $list['country_code'] . '' . $list['phone'];
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find($list['clinic_id']);
$response = $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
//$returnMsgStatus = $this->twilio->sendMessageForReminder($sid, $token, $from, $to, $message);
if ($response['status'] == 1) {
$review_name = "Appointment Reminder Sms";
$this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name, $message, $list['appo_id']);
// $em->flush();
$RAW_QUERY5 = "UPDATE `google_event` SET `status` = 'reminderSent' WHERE appointment_id = " . $list['appo_id'];;
$statements5 = $em->getConnection()->prepare($RAW_QUERY5);
$statements5->execute();
$RAW_QUERY6 = "UPDATE `appointment` SET `status` = 'reminderSent' WHERE id = " . $list['appo_id'];;
$statements6 = $em->getConnection()->prepare($RAW_QUERY6);
$statements6->execute();
}
if ($list['email'] != '' && $list['verified_email'] == 1) {
$user_email = $list['email'];
$user_name = $list['first_name'] . ' ' . $list['last_name'];
$pract_name = $list['pract_first_name'] . ' ' . $list['pract_last_name'];
//$email_body = $this->returnEmailTemplateSendEmailReminder($user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
$email_body = $this->returnEmailTemplateSendEmailReminder($list['appo_id'], $list['clinic_id'], $list['clinic_email'], $list['verified_email'], $user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
if ($email_body['status'] != 0) {
$review_name = "Appointment Reminder - Email";
$message = json_encode($email_body['content']);
$this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name, $message, $list['appo_id'], 6);
}
}
echo "need to " . $hours . " reminder call";
} else {
$arrayContainsId = in_array($list['treatment_clinic_id'], $checkRemindSendStatus);
if ($arrayContainsId) {
//$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
if ($list['reminder_header'] !== '' && $list['reminder_footer'] != '') {
$message = "" . $list['reminder_header'] . " " . $sendingDate . " with " . $list['name'] . " . " . $list['reminder_footer'] . "";
} else {
$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
}
$to = $list['country_code'] . '' . $list['phone'];
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find($list['clinic_id']);
$returnMsgStatus = $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
// $returnMsgStatus = $this->twilio->sendMessageForReminder($sid, $token, $from, $to, $message);
if ($returnMsgStatus['status'] == 1) {
$review_name = "Appointment Reminder Sms";
$this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name, $message, $list['appo_id']);
// $em->flush();
$RAW_QUERY5 = "UPDATE `google_event` SET `status` = 'reminderSent' WHERE appointment_id = " . $list['appo_id'];;
$statements5 = $em->getConnection()->prepare($RAW_QUERY5);
$statements5->execute();
$RAW_QUERY6 = "UPDATE `appointment` SET `status` = 'reminderSent' WHERE id = " . $list['appo_id'];;
$statements6 = $em->getConnection()->prepare($RAW_QUERY6);
$statements6->execute();
}
if ($list['email'] != '' && $list['verified_email'] == 1) {
$user_email = $list['email'];
$user_name = $list['first_name'] . ' ' . $list['last_name'];
$pract_name = $list['pract_first_name'] . ' ' . $list['pract_last_name'];
//$email_body = $this->returnEmailTemplateSendEmailReminder($user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
$email_body = $this->returnEmailTemplateSendEmailReminder($list['appo_id'], $list['clinic_id'], $list['clinic_email'], $list['verified_email'], $user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
if ($email_body['status'] != 0) {
$review_name = "Appointment Reminder - Email";
$message = json_encode($email_body['content']);
$this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name, $message, $list['appo_id'], 6);
}
}
echo "need to " . $hours . " reminder call";
}
}
}
//echo $selectHours;exit;
}
if ($days > 0 && $years == 0 && $months == 0 && $minutes == 0 && $hours == 0) {
if ($days == 1) {
$selectDay = '1 Day';
} else {
$selectDay = $days . ' Days';
}
$reminder_query = "SELECT time,treatment_id FROM `reminder` WHERE time='" . $selectDay . "' and clinic_id = " . $list['clinic_id']; //reminder table
$reminder = $em->getConnection()->prepare($reminder_query);
$reminder->execute();
$reminderList = $reminder->fetchAllAssociative();
//==========new code for check treatment==============//
$checkRemindSendStatus = array();
foreach ($reminderList as $relist) {
array_push($checkRemindSendStatus, $relist['treatment_id']);
}
$arrayContainsNull = in_array(null, $checkRemindSendStatus);
//==========new code for check treatment==============//
if (!empty($reminderList)) {
if ($arrayContainsNull) {
$sendingDate = date('l d M H-i', strtotime($list['start']));
$sendingDateForEmail = date('l d M', strtotime($list['start']));
//$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
if ($list['reminder_header'] !== '' && $list['reminder_footer'] != '') {
$message = "" . $list['reminder_header'] . " " . $sendingDate . " with " . $list['name'] . " . " . $list['reminder_footer'] . "";
} else {
$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
}
$to = $list['country_code'] . '' . $list['phone'];
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find($list['clinic_id']);
$returnMsgStatus = $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
// $returnMsgStatus = $this->twilio->sendMessageForReminder($sid, $token, $from, $to, $message);
if ($returnMsgStatus['status'] == 1) {
$review_name = "Appointment Reminder Sms";
$this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name, $message, $list['appo_id']);
// $em->flush();
$RAW_QUERY5 = "UPDATE `google_event` SET `status` = 'reminderSent' WHERE appointment_id = " . $list['appo_id'];;
$statements5 = $em->getConnection()->prepare($RAW_QUERY5);
$statements5->execute();
$RAW_QUERY6 = "UPDATE `appointment` SET `status` = 'reminderSent' WHERE id = " . $list['appo_id'];;
$statements6 = $em->getConnection()->prepare($RAW_QUERY6);
$statements6->execute();
}
if ($list['email'] != '' && $list['verified_email'] == 1) {
$user_email = $list['email'];
$user_name = $list['first_name'] . ' ' . $list['last_name'];
$pract_name = $list['pract_first_name'] . ' ' . $list['pract_last_name'];
//$email_body = $this->returnEmailTemplateSendEmailReminder($user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
$email_body = $this->returnEmailTemplateSendEmailReminder($list['appo_id'], $list['clinic_id'], $list['clinic_email'], $list['verified_email'], $user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
if ($email_body['status'] != 0) {
$review_name = "Appointment Reminder - Email";
$message = json_encode($email_body['content']);
$this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name, $message, $list['appo_id'], 6);
}
}
echo "need to " . $selectDay . " day reminder call";
} else {
$arrayContainsId = in_array($list['treatment_clinic_id'], $checkRemindSendStatus);
if ($arrayContainsId) {
$sendingDate = date('l d M H-i', strtotime($list['start']));
$sendingDateForEmail = date('l d M', strtotime($list['start']));
//$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
if ($list['reminder_header'] !== '' && $list['reminder_footer'] != '') {
$message = "" . $list['reminder_header'] . " " . $sendingDate . " with " . $list['name'] . " . " . $list['reminder_footer'] . "";
} else {
$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
}
$to = $list['country_code'] . '' . $list['phone'];
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find($list['clinic_id']);
$returnMsgStatus = $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
//$returnMsgStatus = $this->twilio->sendMessageForReminder($sid, $token, $from, $to, $message);
if ($returnMsgStatus['status'] == 0) {
$review_name = "Appointment Reminder Sms";
$this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name, $message, $list['appo_id']);
// $em->flush();
$RAW_QUERY5 = "UPDATE `google_event` SET `status` = 'reminderSent' WHERE appointment_id = " . $list['appo_id'];;
$statements5 = $em->getConnection()->prepare($RAW_QUERY5);
$statements5->execute();
$RAW_QUERY6 = "UPDATE `appointment` SET `status` = 'reminderSent' WHERE id = " . $list['appo_id'];;
$statements6 = $em->getConnection()->prepare($RAW_QUERY6);
$statements6->execute();
}
if ($list['email'] != '' && $list['verified_email'] == 1) {
$user_email = $list['email'];
$user_name = $list['first_name'] . ' ' . $list['last_name'];
$pract_name = $list['pract_first_name'] . ' ' . $list['pract_last_name'];
//$email_body = $this->returnEmailTemplateSendEmailReminder($user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
$email_body = $this->returnEmailTemplateSendEmailReminder($list['appo_id'], $list['clinic_id'], $list['clinic_email'], $list['verified_email'], $user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
if ($email_body['status'] != 0) {
$review_name = "Appointment Reminder - Email";
$message = json_encode($email_body['content']);
$this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name, $message, $list['appo_id'], 6);
}
}
echo "need to " . $selectDay . " day reminder call";
}
}
}
}
}
}
echo "<br>";
exit;
return $this->json(['status' => "success", 'msg' => 'OK']);
exit;
}
public function addSendReminderCorrespondence($patient_id, $clinic_id, $review_name, $message, $appointment_id, $type = 5)
{
$message = mysqli_real_escape_string($message);
$em = $this->getDoctrine()->getManager();
$RAW_QUERY = "INSERT INTO `patient_correspondence` (patient_id, clinic_id, subject_email, message, created_at, updated_at, appointment_id) VALUES (" . $patient_id . ", " . $clinic_id . ", '" . $review_name . "', '" . $message . "', '" . date('Y-m-d H:i:s') . "', '" . date('Y-m-d H:i:s') . "', '" . $appointment_id . "')";
$statements = $em->getConnection()->prepare($RAW_QUERY);
$statements->execute();
$this->addAutomatedPatientMessage($em, $patient_id, $clinic_id, $review_name, $message, $type);
return true;
}
public function sendSMSReminderCreatedByOthers(Request $request)
{
//get clinic_id
$this->logger->error('cron job is working fine');
// $message = "Test Message";
// $sid = "AC7c4fcd71a8000f9b3150e96da80ed494";
// $token = "fc58ee2a75a71a71138d783deafacdc4";
// $from = "+17622543122";
// $to = "+918233922863";
// $this->twilio->send($sid, $token, $from, $to, $message);
$em = $this->getDoctrine()->getManager();
$RAW_QUERY1 = "SELECT DISTINCT clinic_id FROM `reminder`"; //reminder table
$statements1 = $em->getConnection()->prepare($RAW_QUERY1);
if ($statements1->execute()) {
$res1 = $statements1->fetchAllAssociative();
foreach ($res1 as $clinic_id) {
//appointment table
$RAW_QUERY2 = "SELECT id,clinic_id,patient_id,clinic_user_id,treatment_clinic_id,start,end FROM `appointment` WHERE clinic_id=" . $clinic_id['clinic_id'];
$statements2 = $em->getConnection()->prepare($RAW_QUERY2);
$statements2->execute();
$res2 = $statements2->fetchAllAssociative();
$now_time = '';
$clinic = $this->getDoctrine()->getRepository(Clinic::class)->find($clinic_id['clinic_id']);
if (!empty($res2)) {
foreach ($res2 as $res) {
//get time
$RAW_QUERY3 = "SELECT time,treatment_id FROM `reminder` WHERE clinic_id = " . $res['clinic_id']; //reminder table
$statements3 = $em->getConnection()->prepare($RAW_QUERY3);
$statements3->execute();
$res3 = $statements3->fetchAllAssociative();
if (!empty($res3)) {
foreach ($res3 as $time) {
if ($time['time']) {
$a = explode(" ", $time['time']);
if ($a[0] && $a[1]) {
$number_time = $a[0];
$string_time = $a[1];
if (!empty($a[0]) && $a[1] == 'hour' || $a[1] == 'hours') {
$now_time = date('Y-m-d H:i', strtotime('+' . $a[0] . ' hour')); // today time - time
} else {
$now_time = date('Y-m-d H:i', strtotime('+' . $a[0] . ' day')); // today time - date
}
$match_date = date('Y-m-d H:i', strtotime($res['start'])); //Actual Appointment date
//====================================================New
$subSevenMin = strtotime($now_time . '- 6 minute');
$subSevenMinTime = date('Y-m-d H:i', $subSevenMin);
$addSevenMin = strtotime($now_time . '+ 6 minute');
$addSevenMinTime = date('Y-m-d H:i', $addSevenMin);
//=====================================================New
if ($match_date >= $subSevenMinTime && $match_date <= $addSevenMinTime) {
//get twilio id using clinic_id
$RAW_QUERY5 = "SELECT country_code,phone FROM `user` WHERE id=" . $res['patient_id'];
$statements5 = $em->getConnection()->prepare($RAW_QUERY5);
$statements5->execute();
$res5 = $statements5->fetchAllAssociative();
$message = "Hi, You have an appointment in " . $time['time'];
$to = $res5[0]['country_code'] . '' . $res5[0]['phone'];
$this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
}
}
}
}
}
}
}
}
}
return $this->json(['status' => "success", 'msg' => 'OK']);
}
//==============================for SMS reminder =========================================================(14-03-2023)//
//==============================for otp auth and login =========================================================//
/**
* @Route("/admin/custom-login-otp", name="custom_login_otp", options={"expose"=true}, methods={"GET"})
*/
public function checkLoginOtpCustom(Request $request, UserPasswordEncoderInterface $passwordEncoder): JsonResponse
{
$json = [];
$json['username'] = $request->get('username');
$json['password'] = $request->get('password');
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['username' => $json['username']]); //get user details
if (!empty($user) && !empty($user->getLastOTPVerified())) //check last otp verified
{
$last_verified_time = $user->getLastOTPVerified(); //get
$now = strtotime(date('Y-m-d H:i:s')); // today date
$your_date = strtotime($last_verified_time);
$datediff = $now - $your_date;
$date_diff = round($datediff / (60 * 60 * 24));
if ($date_diff <= 5) {
return $this->json(['status' => "success", 'msg' => 'Please Login']);
}
}
if($json['username'] == 'please_do_not_reply@consentz.com' || $json['username'] == 'demo' || $json['username'] == 'jack_clinic_admin' || strpos($json['username'], 'jack_clinic') || $json['username'] == 'jack_clinic_practitioner' || $json['username'] == 'arsal_receptionist' || $json['username'] == 'arsal_receptionist1') {
return $this->json(['status' => "success", 'msg' => 'Please Login']);
}
if (!empty($user) && (!empty($user->getEmail()) || (!empty($user->getPhone())))) //check phone no. or email
{
$user_id = $user->getid();
$otp_code = random_int(100000, 999999);
$em = $this->getDoctrine()->getManager();
if($json['username'] == 'demo') {
$otp_code = '1234';
}
$RAW_QUERY = "UPDATE `user` set otp = '" . $otp_code . "', otp_sent_at = '" . date('Y-m-d H:i:s') . "' WHERE id =" . $user_id;
$statements = $em->getConnection()->prepare($RAW_QUERY);
if ($statements->execute()) {
$user_name = '';
if (!empty($user->getUsername())) {
$user_name = $user->getUsername();
}
$message = "Hi " . $user_name . ", Your Consentz login OTP is " . $otp_code;
try {
if (!empty($user->getEmail())) //send email code
{
$from = 'mail@consentz.com';
$id_msg = $message . '-' . $user->getEmail();
$to = $user->getEmail();
$subject = "Consentz One Time Passcode Verification";
$email_body = $this->returnEmailTemplateForOTP($user_name, $otp_code);
$this->SESManager->sendEmailToProspect($email_body, $to, $id_msg, $subject, $from); //email
}
$this->logger->info('inside sms passwpord');
if (!empty($user->getPhone())) {
$country_code = '';
if (empty($user->getCountryCode())) {
$country_code = '+44';
} else {
$country_code = $user->getCountryCode();
}
$to = $country_code . $user->getPhone();
$sid = $user->getClinic()->getTwilio()->getSid();
$token = $user->getClinic()->getTwilio()->getToken();
$from = $user->getClinic()->getTwilio()->getNumberFrom();
$this->twilio->send($sid, $token, $from, $to, $message);
}
} finally {
return $this->json(['status' => 'success', 'success' => $otp_code . '@' . $user_id, 'msg' => 'OTP send successfully']);
}
}
} else {
return $this->json(['status' => 'error', 'msg' => 'Invalid Credentials']);
}
}
/**
* @Route("/admin/check-custom-otp", name="check_custom_otp", options={"expose"=true}, methods={"GET"})
*/
public function checkCustomOTP(Request $request) //Need to check otp there
{
$json = [];
$json['otp'] = $request->get('otp');
$json['userid'] = $request->get('userid');
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['id' => $json['userid']]);
$otp = $user->getOtp();
if (!empty($otp)) {
if ($otp == $json['otp']) {
$em = $this->getDoctrine()->getManager();
$RAW_QUERY = "UPDATE `user` set last_otp_verified = '" . date('Y-m-d H:i:s') . "' WHERE id =" . $json['userid'];
$statements = $em->getConnection()->prepare($RAW_QUERY);
$statements->execute();
return $this->json(['status' => "success", 'msg' => 'OTP Matched']);
} else {
return $this->json(['status' => 'error', 'msg' => 'OTP does not mach']);
}
} else {
return $this->json(['status' => 'error', 'msg' => 'Something went wrong']);
}
}
/**
* @Route("/admin/resend-otp", name="resned_otp", options={"expose"=true}, methods={"GET"})
*/
public function resendOTP(Request $request) //Need to check otp there
{
$json = [];
$json['userid'] = $request->get('uid');
$user_id = $json['userid'];
if (!empty($user_id)) {
$user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['id' => $user_id]);
$otp_code = random_int(100000, 999999); //generate otp
$em = $this->getDoctrine()->getManager();
$RAW_QUERY = "UPDATE `user` set otp = '" . $otp_code . "', otp_sent_at = '" . date('Y-m-d H:i:s') . "' WHERE id =" . $user_id;
$statements = $em->getConnection()->prepare($RAW_QUERY);
if ($statements->execute()) {
$user_name = '';
if (!empty($user->getUsername())) {
$user_name = $user->getUsername();
}
$message = "Hi " . $user_name . ", Your Consentz login OTP is " . $otp_code;
try {
$this->logger->info('inside sms pss verig');
if (!empty($user->getEmail())) //send email code
{
$from = 'mail@consentz.com';
$id_msg = $message . '-' . $user->getEmail();
$to = $user->getEmail();
$subject = "Consentz One Time Passcode Verification";
$email_body = $this->returnEmailTemplateForOTP($user_name, $otp_code);
$this->SESManager->sendEmailToProspect($email_body, $to, $id_msg, $subject, $from); //email
}
if (!empty($user->getPhone())) {
$country_code = '';
if (empty($user->getCountryCode())) {
$country_code = '+44';
} else {
$country_code = $user->getCountryCode();
}
$to = $country_code . $user->getPhone();
$sid = $user->getClinic()->getTwilio()->getSid();
$token = $user->getClinic()->getTwilio()->getToken();
$from = $user->getClinic()->getTwilio()->getNumberFrom();
$this->twilio->send($sid, $token, $from, $to, $message); //send sms
}
} finally {
return $this->json(['status' => 'success', 'success' => $otp_code . '@' . $user_id, 'msg' => 'OTP resend successfully']);
}
}
} else {
return $this->json(['status' => 'error', 'msg' => 'Something went wrong']);
}
}
public function returnEmailTemplateSendEmailReminder($appointment_id, $clinic_id, $clinic_email, $mail_verirfy, $user_email, $patient_name, $appointment_date, $appointment_time, $practitioner_name)
{
$returnArray['status'] = '';
$returnArray['content'] = '';
$em = $this->getDoctrine()->getManager();
$appo_query = "SELECT content from system_emails where email_key = 2 and clinic_id = 3";
//$appo_query = "SELECT content from generic_system_emails where id = 2";
$appointment = $em->getConnection()->prepare($appo_query);
$appointment->execute();
$email_template = $appointment->fetchAllAssociative();
if (!empty($email_template)) {
if (!empty($email_template[0]['content'])) {
$template = $email_template[0]['content'];
}
$mixed_search = array("[Patient Name]", "[Appointment Date]", "[Appointment Time]", "[Practitioner Name]");
$mixed_replace = array($patient_name, $appointment_date, $appointment_time, $practitioner_name);
$messagebody = str_replace($mixed_search, $mixed_replace, $template);
$content = $messagebody;
$from = 'mail@consentz.com';
if ($clinic_email != '') {
$from = $clinic_email;
}
$subject = "Appointment Reminder - Email";
$to = $user_email;
$id_msg = $subject . '-' . $user_email;
$status = $this->SESManager->sendEmailToProspectForReminder($content, $to, $id_msg, $subject, $from);
$returnArray['status'] = $status;
$returnArray['content'] = $content;
return $returnArray;
}
return $returnArray;
//email
}
public function returnEmailTemplateSendEmailReminderOlllld($appointment_id, $clinic_id, $clinic_email, $mail_verirfy, $user_email, $patient_name, $appointment_date, $appointment_time, $practitioner_name)
{
$appointmentStatus = $this->getDoctrine()
->getRepository(Appointment::class)
->find($appointment_id);
$em = $this->getDoctrine()->getManager();
$genericEmail = $em->getRepository(GenericSystemEmails::class)->findOneBy(['title' => 'Appointment Reminder Email']);
$systemEmail = $em->getRepository(SystemEmails::class)->findOneBy(['clinic' => $clinic_id, 'email_key' => $genericEmail->getId()]);
if ($systemEmail) {
$body = $systemEmail;
} else {
$body = $genericEmail;
}
$body = $em->getRepository(Appointment::class)->replaceMetaTags($body, $appointmentStatus);
$returnArray['status'] = '';
$returnArray['content'] = '';
// $em = $this->getDoctrine()->getManager();
// $appo_query = "SELECT content from system_emails where email_key = 2 and clinic_id = 3";
// $appointment = $em->getConnection()->prepare($appo_query);
// $appointment->execute();
// $email_template = $appointment->fetchAllAssociative();
if (!empty($body)) {
// if (!empty($email_template[0]['content'])) {
// $template = $email_template[0]['content'];
// }
// $mixed_search = array("[Patient Name]", "[Appointment Date]", "[Appointment Time]", "[Practitioner Name]");
// $mixed_replace = array($patient_name, $appointment_date, $appointment_time, $practitioner_name);
// $messagebody = str_replace($mixed_search, $mixed_replace, $template);
$content = $body;
$from = $clinic_email;
$subject = "Appointment Reminder Email";
// $email_body = $this->returnEmailTemplateSendEmailReminder($patient_name, $appointment_date, $appointment_time, $practitioner_name);
$to = $user_email;
$id_msg = $subject . '-' . $user_email;
$status = $this->SESManager->sendEmailToProspectForReminder($content, $to, $id_msg, $subject, $from);
$returnArray['status'] = $status;
$returnArray['content'] = $content;
return $returnArray;
}
return $returnArray;
//email
}
//mail template for post appoitment reminder
public function returnEmailTemplateSendEmailReminderByRahul($user_email, $patient_name, $appointment_date, $appointment_time, $practitioner_name)
{
$returnArray['status'] = '';
$returnArray['content'] = '';
$em = $this->getDoctrine()->getManager();
$appo_query = "SELECT content from system_emails where email_key = 2 and clinic_id = 3";
$appointment = $em->getConnection()->prepare($appo_query);
$appointment->execute();
$email_template = $appointment->fetchAllAssociative();
if (!empty($email_template)) {
if (!empty($email_template[0]['content'])) {
$template = $email_template[0]['content'];
}
$mixed_search = array("[Patient Name]", "[Appointment Date]", "[Appointment Time]", "[Practitioner Name]");
$mixed_replace = array($patient_name, $appointment_date, $appointment_time, $practitioner_name);
$messagebody = str_replace($mixed_search, $mixed_replace, $template);
$content = $messagebody;
$from = 'mail@consentz.com';
$subject = "Appointment Reminder Email";
// $email_body = $this->returnEmailTemplateSendEmailReminder($patient_name, $appointment_date, $appointment_time, $practitioner_name);
$to = $user_email;
$id_msg = $subject . '-' . $user_email;
$status = $this->SESManager->sendEmailToProspectForReminder($content, $to, $id_msg, $subject, $from);
$returnArray['status'] = $status;
$returnArray['content'] = $content;
return $returnArray;
}
return $returnArray;
//email
}
//mail template for otp
public function returnEmailTemplateForOTP($username = '', $otp)
{
$mail_template = "<p>Dear $username,</p>
<br/>
<p>We received a request to access your Consentz Account which requires a one time passcode in order to verify your identity.</p>
<br/>
<p>Your Consentz OTP is:</p>
<p><strong>$otp</strong></p>
<br/>
<p>If you did not request this code, it is possible that someone else is trying to access the Consentz Account. Do not forward or give this code to anyone.</p>
<p>You received this message because this email address is listed as your user's contact email address. Should this need updating, please contact your account’s administrator and request an update to your user’s email address which can be found on the Control Centre under Settings - Team.</p>
<br/>
<p>Sincerely yours,</p>
<p>Team Consentz</p>";
return $mail_template;
}
// public function sendLoginSmsOtpMessage(){
// }
// public function sendLoginEmailOtpMail(){
// }
//==============================for otp auth and login =========================================================//
/**
* @Route("/webhook", name="webhook")
* @Template
*
* @return array
*/
public function webhook()
{
$input = @file_get_contents("php://input");
$data = (array) json_decode($input, true);
$type = isset($data['type']) ? $data['type'] : '';
if ($type == 'customer.subscription.created') {
$latestInvId = $data['data']['object']['latest_invoice'];
$sId = $data['data']['object']['id'];
$metaData = $data['data']['object']['items']['data'][0]['price']['metadata'];
$cuId = $metaData['cuid'];
$id = $metaData['mid'];
$cId = $metaData['cid'];
$pId = $metaData['pid'];
$userId = $metaData['userId'];
$this->logger->error('m-chec-11');
if ($cuId != '' && $id != '' && $cId != '' && $pId != '' && $userId != '') {
$practitioner = $this->getDoctrine()->getRepository(ClinicUser::class)->findOneBy(['id' => $cuId]);
$members = $this->getDoctrine()->getRepository(Membership::class)->findOneBy(['id' => $id]);
$clinic = $this->getDoctrine()->getRepository(Clinic::class)->findOneBy(['id' => $cId]);
$patient = $this->getDoctrine()->getRepository(Patient::class)->find($pId);
$checkIfAlreadyMember = $this->getDoctrine()->getRepository(UsedMembership::class)->selectMembershipData($clinic, $members, $practitioner, $patient);
$mInvId = isset($checkIfAlreadyMember['id']) ? $checkIfAlreadyMember['id'] : '';
if (!$mInvId) {
$monthsCount = $members->getMonthsCount();
$user = $this->getDoctrine()->getRepository(User::class)->find($userId);
$membership = new UsedMembership();
$membership->setClinic($clinic);
$membership->setPatient($patient);
$membership->setClinicUser($practitioner);
$membership->setMembership($members);
$membership->setStripeRecurringId($sId);
$membership->setMembershipcount($monthsCount);
$membership->setActive(true);
$em = $this->getDoctrine()->getManager();
$invoice = $this->membershipService->newInvoiceForMembership($patient, $clinic, $membership, $user);
$membership->setInvoice($invoice);
//$em = $this->getDoctrine()->getManager();
$em->persist($membership);
$em->flush();
foreach ($membership->getMembership()->getItems() as $key) {
$em = $this->getDoctrine()->getManager();
$usedMembershipItems = new UsedMembershipItems();
if ($key->getType() == 'product') {
$usedMembershipItems->setProduct($key->getProduct());
} else {
$usedMembershipItems->setTreatment($key->getTreatment());
}
$usedMembershipItems->setUsedMembership($membership);
$usedMembershipItems->setType($key->getType());
$usedMembershipItems->setQtyTotal($key->getQuantityTotal());
$usedMembershipItems->setQtyUsed(0);
$usedMembershipItems->setCreatedAt(new \DateTime('now'));
$usedMembershipItems->setUpdatedAt(new \DateTime('now'));
$em->persist($usedMembershipItems);
// Add history..
/*$description = "First time, Quantity for ". $key->getType() ." (". $key->getQuantityTotal() .") is added";
$membershipHistory = new UsedMembershipHistory();
$membershipHistory->setUsedMembershipItems($usedMembershipItems);
$membershipHistory->setUsedMembership($membership);
$membershipHistory->setType($key->getType());
$membershipHistory->setDescription($description);
$membershipHistory->setCreatedAt(new \DateTime('now'));
$membershipHistory->setUpdatedAt(new \DateTime('now'));
$em->persist($membershipHistory);*/
$em->flush();
}
/*$kind = new Kind();
$kind
->setClinic($clinic)
->setType(Kind::DEFAULT_STRIPE_CONNECT)
->setDisabled(false);
$this->getDoctrine()->getManager()->persist($kind);
$this->getDoctrine()->getManager()->flush();
$invId = $invoice->getId();
$payment = new Payment();
$payment->setInvoice($invoice);
$payment->setAmount($members->getDepositAmount());
$payment->setPaymentIntentId($latestInvId);
$payment->setType($kind);
$em = $this->getDoctrine()->getManager();
$em->persist($payment);
$em->flush();
$this->historyService->createHistoryInvoicePayment($invoice, $payment, InvoiceHistory::TYPE_HISTORY_INVOICE_PAYMENT_NEW);
$this->historyService->createHistoryInvoiceVoucher($invoice, InvoiceHistory::TYPE_HISTORY_INVOICE_VOUCHER_NEW);*/
}
}
} else if ($type == 'invoice.paid') {
$metaData = $data['data']['object']['lines']['data'][0]['price']['metadata'];
$this->logger->error('yess ');
$this->logger->error(serialize($data));
$this->logger->error('boo ');
$cuId = $metaData['cuid'];
$id = $metaData['mid'];
$cId = $metaData['cid'];
$pId = $metaData['pid'];
$userId = $metaData['userId'];
$this->logger->error(' check-1 ');
if ($cuId != '' && $id != '' && $cId != '' && $pId != '' && $userId != '') {
$practitioner = $this->getDoctrine()->getRepository(ClinicUser::class)->findOneBy(['id' => $cuId]);
$members = $this->getDoctrine()->getRepository(Membership::class)->findOneBy(['id' => $id]);
$clinic = $this->getDoctrine()->getRepository(Clinic::class)->findOneBy(['id' => $cId]);
$patient = $this->getDoctrine()->getRepository(Patient::class)->find($pId);
sleep(2);
$checkIfAlreadyMember = $this->getDoctrine()->getRepository(UsedMembership::class)->selectMembershipData($clinic, $members, $practitioner, $patient);
$memberId = isset($checkIfAlreadyMember['id']) ? $checkIfAlreadyMember['id'] : '';
$this->logger->error(' check-2 ');
$this->logger->error($memberId);
if ($memberId) {
$latestInvId = $data['data']['object']['id'];
$paymentIntant = $data['data']['object']['payment_intent'];
$user = $this->getDoctrine()->getRepository(User::class)->find($userId);
$invoice = $this->getDoctrine()->getRepository(Invoice::class)->find($memberId);
$getPaymentDetail = $this->getDoctrine()->getRepository(Payment::class)->checkPaymentIntant($invoice, $paymentIntant);
$paymentId = isset($getPaymentDetail['id']) ? $getPaymentDetail['id'] : 0;
$this->logger->error(' check-3 ');
$this->logger->error($paymentId);
if (!$paymentId) {
$this->logger->error(' check-4 ');
$rcount = isset($checkIfAlreadyMember['rcount']) ? (empty($checkIfAlreadyMember['rcount']) ? 0 : $checkIfAlreadyMember['rcount']) : 0;
$membershipcount = isset($checkIfAlreadyMember['membershipcount']) ? $checkIfAlreadyMember['membershipcount'] : 0;
$usedMemberId = (isset($checkIfAlreadyMember['memberId']) && !empty($checkIfAlreadyMember['memberId'])) ? $checkIfAlreadyMember['memberId'] : 0;
$subscribeId = (isset($checkIfAlreadyMember['stripe_recurring_id']) && !empty($checkIfAlreadyMember['stripe_recurring_id'])) ? $checkIfAlreadyMember['stripe_recurring_id'] : 0;
$rcount = $rcount + 1;
if ($rcount == $membershipcount) {
// unsubscribe this subscription.
$this->stripeService->cancelSubscription($subscribeId);
$this->logger->error(' cancelSubscription ');
$this->logger->error($subscribeId);
}
if ($rcount <= $membershipcount) {
$this->logger->error(' update count ');
$this->logger->error($rcount);
$this->getDoctrine()->getRepository(UsedMembership::class)->updateRecurringCount($usedMemberId, $rcount);
}
$kind = $this->doctrine->getRepository(Kind::class)->findOneBy(['clinic' => $clinic, 'type' => Kind::DEFAULT_STRIPE_CONNECT]);
if (!$kind) {
$kind = new Kind();
$kind
->setClinic($clinic)
->setType(Kind::DEFAULT_STRIPE_CONNECT)
->setDisabled(false);
$this->getDoctrine()->getManager()->persist($kind);
$this->getDoctrine()->getManager()->flush();
}
$payment = new Payment();
$payment->setInvoice($invoice);
$payment->setAmount(($data['data']['object']['total'] / 100));
$payment->setPaymentIntentId($paymentIntant);
$payment->setStripeInvId($latestInvId);
$payment->setType($kind);
$em = $this->getDoctrine()->getManager();
$em->persist($payment);
$em->flush();
$this->historyService->createHistoryInvoicePayment($invoice, $payment, InvoiceHistory::TYPE_HISTORY_INVOICE_PAYMENT_NEW);
$this->historyService->createHistoryInvoiceVoucher($invoice, InvoiceHistory::TYPE_HISTORY_INVOICE_VOUCHER_NEW);
}
}
}
}
die;
}
/**
* @Route("/admin/password/{hash}", name="password_hash", requirements={"hash": "^[a-zA-Z0-9]{0,32}$"}, methods={"GET", "POST"})
* @Template()
*/
public function passwordHash(Request $request, $hash)
{
$em = $this->getDoctrine()->getManager();
/** @var User $user */
$user = $em->getRepository(User::class)->findOneBy(['hash' => $hash]);
if (!$user) {
return $this->redirectToRoute('app_error_hash');
}
if (isset($_REQUEST['isad']) && $_REQUEST['isad'] == 1) {
$user->setEnabled(true);
$user->setHash();
$em->flush();
if ($user instanceof Patient) {
return new RedirectResponse('https://itunes.apple.com/us/app/consentz-patient-app/id1273682006?ls=1&mt=8');
}
$this->addFlash('success', 'You have successfully completed the registration process and confirmed your account');
return $this->redirectToRoute('login');
}
$form = $this->createForm(AddPasswordType::class, $user, ['encoderPassword' => $this->userPasswordEncoder]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user->setEnabled(true);
$user->setHash();
$em->flush();
if ($user instanceof Patient) {
return new RedirectResponse('https://itunes.apple.com/us/app/consentz-patient-app/id1273682006?ls=1&mt=8');
}
if (isset($_REQUEST['forget']) && $_REQUEST['forget'] == 1) {
$this->addFlash('success', 'You have successfully updated your account password');
} else {
$this->addFlash('success', 'You have successfully completed the registration process and confirmed your account');
}
return $this->redirectToRoute('login');
} else if ($form->isSubmitted() && !$form->isValid()) {
$this->addFlash('danger', 'The password must be at least 8 characters long and match the confirmation field.');
}
$this->breadcrumbs->addItem('Set New Password');
return [
'form' => $form->createView(),
'isPatient' => $user instanceof Patient
];
}
/**
* @Route("/admin/forgot", name="forgot_password")
* @Template("default/forgot.html.twig")
*/
public function forgot(Request $request)
{
$userDTO = new Admin();
$form = $this->createForm(RecoveryType::class, $userDTO);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
/** @var User $user */
$user = $em->getRepository('App:Person\User')->findOneBy(['username' => $userDTO->getUsername()]);
if ($user && $user->isAccountNonLocked()) {
$user->setHash(md5($user->getUsername()));
$em->flush();
$this->SESManager->sendEmail($user, UserManager::USER_RECOVERY);
}
$this->addFlash('success', 'Success! Check your email to reset your password.');
return $this->redirectToRoute('dashboard_index');
}
$breadcrumbs = $this->breadcrumbs;
$breadcrumbs->addRouteItem('Sign In', 'login');
$breadcrumbs->addItem('Forgot Password');
return ['form' => $form->createView()];
}
/**
* @Route("/admin/registration1", name="registration1", methods={"GET", "POST"})
* @Template("default/registration1.html.twig")
*/
public function registration1(Request $request, CreateClinicGiftVoucher $clinicGiftVoucher)
{
return $this->registration($request, $clinicGiftVoucher);
}
/**
* @Route("/admin/registration2", name="registration2", methods={"GET", "POST"})
* @Template("default/registration2.html.twig")
*/
public function registration2(Request $request, CreateClinicGiftVoucher $clinicGiftVoucher)
{
return $this->registration($request, $clinicGiftVoucher);
}
/**
* @Route("/admin/registration", name="registration", methods={"GET", "POST"})
* @Template("default/registration.html.twig")
*/
public function registration(Request $request, CreateClinicGiftVoucher $clinicGiftVoucher)
{
/** @var User $user */
if (($user = $this->getUser()) && ($user instanceof User)) {
if ($user->getUsername()) {
$this->addFlash('danger', 'User ' . $user->getUsername() . ' is already logged in. Logout please before registering.');
} else {
$this->addFlash('danger', 'Any user is already logged in. Logout please before registering.');
}
return $this->redirectToRoute('dashboard_index');
}
$redirect = $request->query->get('redirect');
$redirectParams = $redirect ? ['redirect' => $redirect] : [];
$formUrl = $this->generateUrl('registration', ['redirect' => $redirectParams]);
$organisation = new Organisation();
$admin = new SuperClinicAdmin();
$clinic = $this->clinicManager->createNewClinic();
$organisation->addAdmin($admin);
$organisation->addClinic($clinic);
$form = $this->createForm(RegistrationType::class, $organisation, [
'password_encoder' => $this->userPasswordEncoder,
'action' => $formUrl,
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$admin->setEmail($organisation->getClinicEmail());
if ($form->isValid()) {
$admin->setHash(md5($admin->getUsername()));
$password = $this->userPasswordEncoder->encodePassword($admin, $_POST['plain_password_first']);
$admin->setPassword($password);
$clinic->setTrialEndDate(date('Ymd', strtotime("+14 days")));
$clinic->setName($organisation->getName());
$clinic->setEmail($organisation->getClinicEmail());
$em = $this->getDoctrine()->getManager();
$em->persist($organisation);
$em->flush();
foreach ($organisation->getAdmins() as $admin) {
try{
$this->SESManager->sendEmail($admin, UserManager::USER_ADMIN_NEW);
}catch(Exception $e){}
}
$this->createDefaultPaymentType->create($clinic, Kind::DEFAULT_KINDS);
$this->createDefaultDataClinic->createPatient($clinic, $admin);
$this->createDefaultDataClinic->createStock($clinic);
$this->createDefaultDataClinic->createQuestionnaire($clinic);
$this->createDefaultDataClinic->createDefaultVatOptions($clinic);
$this->createDefaultDataClinic->createTAndC($clinic);
$this->createDefaultDataClinic->createLearnAboutSources($clinic);
$this->createDefaultDataClinic->createDefaultPmData($clinic);
$clinicGiftVoucher->createVoucher($clinic);
$this->createDefaultDataClinic->createDefaultPatientStatuses($clinic);
$this->createDefaultDataClinic->createDefaultTreatmentAndDefaultTeamMember($clinic);
//$this->SESManager->verifyEmail($clinic, true);
if ($promoCodeValue = $form->get('promoCodeValue')->getData()) {
/** @var PromoCode $promoCode */
$promoCode = $this->getDoctrine()->getRepository(PromoCode::class)->findOneBy([
'value' => $promoCodeValue,
'clinicEmail' => $clinic->getEmail()
]);
if ($promoCode) {
$clinic->setPromoCode($promoCode);
$em->flush();
}
}
$this->addClinicInChats($clinic,$organisation);
$this->addFlash('success', 'Your "Super Clinic Admin" profile has been created. Please check your inbox for a confirmation email and follow the link contained to confirm this account.');
if ($redirect) {
return new RedirectResponse($redirect);
}
return $this->redirectToRoute('dashboard_index');
} else {
// Handle errors
$hasNameError = false;
foreach ($form->getErrors(true) as $error) {
// You can either log them, display them, or handle them as needed
//echo $error->getMessage(); // This will output the error message
if (strpos($error->getMessage(), 'already') !== false) {
if(strpos($error->getMessage(), 'Username')) {
$this->addFlash('username_error', 'Username already taken.');
}else if(strpos($error->getMessage(), 'Clinic')) {
$form->get('name')->addError(new \Symfony\Component\Form\FormError("Clinic name already taken."));
}
} else {
$this->addFlash('error', $error->getMessage());
}
}
}
}
$breadcrumbs = $this->breadcrumbs;
$breadcrumbs->addRouteItem('Sign In', 'dashboard_index');
$breadcrumbs->addItem('Registration');
return [
'form' => $form->createView(),
];
}
/**
* @Route("/admin/confirm-event/{hash}", name="confirm-event-outside", methods={"GET", "POST"})
* @Template()
*/
public function confirmGoogleEvent(Request $request, $hash)
{
/** @var GoogleEvent $event */
$event = $this->getDoctrine()->getRepository(GoogleEvent::class)->findEventToConfirmPageByHash($hash);
if (!$event) {
return ['error' => true];
}
$form = $this->createFormBuilder()
->setAction($this->generateUrl('confirm-event-outside', [
'hash' => $hash,
]))
->setMethod('POST')
->getForm();
if (Request::METHOD_GET == $request->getMethod()) {
return [
'form' => $form->createView(),
'event' => $event
];
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$event->setStatus(Appointment::STATUS_CONFIRMED);
$this->getDoctrine()->getManager()->flush();
}
return $this->redirectToRoute('app_confirm_event');
}
/**
* @Route("/calendar/{hash}", name="redirect_from_short_url_for_google_calendar", requirements={"hash": "^[a-zA-Z0-9]{0,12}$"})
*/
public function redirectForGoogleCalendar($hash): RedirectResponse
{
/** @var ClinicUser $user */
$user = $this->getDoctrine()->getRepository(ClinicUser::class)
->findOneBy(['hashUserShortUrl' => $hash]);
if (!($user instanceof ClinicUser)) {
throw $this->createNotFoundException('Calendar not found');
}
if (!$user->getICalendar() || !$user->isPractitioner()) {
throw $this->createNotFoundException('Calendar not found');
}
return $this->redirect($user->getICalendar()->getUrl());
}
private function addAutomatedPatientMessage($em, $patient_id, $clinic_id, $subject, $message, $type = 5)
{
try {
$sql = "select * from patient_conversation where user_id =? and clinic_id =? and type=?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$patient_id, $clinic_id, 0]);
$conversation = $ap->fetchAssociative();
if (!empty($conversation)) {
$communicationModel = new Communication();
$communicationModel->setFromUserId(0);
$communicationModel->setPatientId($patient_id);
$communicationModel->setConversationId($conversation['id']);
$communicationModel->setSenderType(0);
if ($type == 6) {
$communicationModel->setEmailTemplate($message);
$communicationModel->setMessage($subject);
} else {
$communicationModel->setEmailTemplate(NULL);
$communicationModel->setMessage($message);
}
$communicationModel->setType($type);
$communicationModel->setCreatedAt(time());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($communicationModel);
$entityManager->flush();
$time = time();
$sql = "UPDATE `patient_conversation` SET `updated_at`=? WHERE `id`=?";
$appointment = $em->getConnection()->prepare($sql);
$appointment->execute([$time, $conversation['id']]);
}
} catch (Exception $e) {
}
return true;
}
/**
* @Route("/mailchimp/webhook", name="api_mail_chimp_webhook")
*/
public function mailChimpWebhook(Request $request, MailChimpClientImpl $mailChimpClientImpl): JsonResponse
{
$key = $request->query->get('key');
if (Request::METHOD_POST == $request->getMethod() && $key == sha1(MailChimpClientImpl::KEY_WEBHOOK)) {
$req = new MailChimpWebhookRequest();
$form = $this->createForm(MailChimpWebhookRequestType::class, $req);
$form->handleRequest($request);
try {
$patients = $this->getDoctrine()->getRepository(Patient::class)->findPatientByMailChimpWebhook($req);
} catch (MailChimpException $exception) {
$this->logger->error('MailChimp webhook find patient', [
'mes' => $exception->getTitle(),
'detail' => $exception->getDetail()
]);
return $this->json([]);
}
if (count($patients) > 0) {
/** @var Patient $patient */
foreach ($patients as $patient) {
if ($patient->isReceiveSpecialOfferEmail()) {
$patient->setReceiveSpecialOfferEmail(false);
try {
$mailChimpClientImpl->deleteMember($patient);
} catch (MailChimpException $exception) {
$this->logger->error('MailChimp delete member error', [
'patientId' => $patient->getId(),
'patientEmail' => $patient->getEmail(),
'mes' => $exception->getTitle(),
'detail' => $exception->getDetail()
]);
}
}
}
$this->getDoctrine()->getManager()->flush();
}
}
return $this->json([]);
}
/**
* @Route("/random", name="add_random")
*/
public function randomAction()
{
return 'hi';
}
private function addClinicInChats($clinic,$organisation){
try{
$em = $this->getDoctrine()->getManager();
$clinic = $this->getDoctrine()->getRepository(Clinic::class)
->find($clinic->getId());
$clinicId = $clinic->getId();
$sql = "SELECT role,id,username FROM user WHERE deleted=? and role =? order by id desc";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([0, 'ROLE_CONSENTZ_ADMIN']);
$admins = $ap->fetchAll();
$consentzAdmins = [];
foreach ($admins as $ad) {
$consentzAdmins[] = $ad['id'];
}
$roles = ['ROLE_CLINIC_ADMIN', 'ROLE_PRACTITIONER', 'ROLE_SUPER_CLINIC_ADMIN'];
$rolesPlaceholder = implode(',', array_fill(0, count($roles), '?'));
$sql = "SELECT role,id FROM user WHERE clinic_id = ? and deleted= ? AND role IN ($rolesPlaceholder)";
$ap = $em->getConnection()->prepare($sql);
$params = array_merge([$clinicId, 0], $roles);
$ap->execute($params);
$users = $ap->fetchAll();
$sql = "SELECT role,id FROM user WHERE organisation_id=? and deleted= ?";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$organisation->getId(), 0]);
$adminData = $ap->fetchAll();
if (count($adminData) > 0) {
$fromuserId = $adminData[0]['id'];
$userIds = [];
$title = $clinic->getName();
$g_image = $clinic->getProfileImg();
$userIds = array_merge($consentzAdmins, $userIds);
foreach (array_merge($users, $adminData) as $us) {
if ($us['id'] != $fromuserId) {
$userIds[] = $us['id'];
}
}
$userIds = array_unique($userIds);
$userIds = (count($userIds) > 0) ? implode(',', $userIds) . ',' . $fromuserId : $fromuserId;
$time = time();
$status = 1;
$sql = "INSERT INTO conversation (type, from_user_id, title, g_image, user_ids, status,clinic_id, created_at, updated_at)VALUES (?,?,?,?,?,?,?,?,?)";
$messageInsert = $em->getConnection()->prepare($sql);
$messageInsert->execute([1, $fromuserId, $title, $g_image, $userIds, $status, $clinicId, $time, $time]);
$userIdsArray = explode(',', $userIds);
foreach ($userIdsArray as $userId) {
if (!in_array($userId, $consentzAdmins)) {
$opponenetIds = [];
foreach ($userIdsArray as $uId) {
if ($uId != $userId) {
$opponenetIds[] = $uId;
}
}
foreach ($opponenetIds as $opponenetId) {
$sql = "select * from conversation where type=0 and (user_ids=? or user_ids=?)";
$ap = $em->getConnection()->prepare($sql);
$ap->execute([$opponenetId . ',' . $userId, $userId . ',' . $opponenetId]);
$conversation = $ap->fetchAssociative();
if (!$conversation) {
$time = time();
$sql = "INSERT INTO conversation (type, from_user_id,to_user_id, user_ids, status,created_at, updated_at)VALUES (?,?,?,?,?,?,?)";
$messageInsert = $em->getConnection()->prepare($sql);
$messageInsert->execute([0, $userId, $opponenetId, $userId . ',' . $opponenetId, 1, $time, $time]);
}
}
}
}
}
}catch(\Exception $e){}
}
}