src/Controller/DefaultController.php line 169

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Aws\SESManager;
  4. use App\Entity\Clinic\Appointment;
  5. use App\Entity\Clinic\Appointment\GoogleEvent;
  6. use App\Entity\Clinic\Person\ClinicUser;
  7. use App\Entity\Clinic\PriceTier\PromoCode;
  8. use App\Entity\Organisation\Organisation;
  9. use App\Entity\Patient\Payment\Kind;
  10. use App\Entity\Person\Admin;
  11. use App\Entity\Person\Patient;
  12. use App\Entity\Person\SuperClinicAdmin;
  13. use App\Entity\Person\User;
  14. use App\Form\Model\MailChimpWebhookRequestType;
  15. use App\Form\Type\AddPasswordType;
  16. use App\Form\Type\LoginType;
  17. use App\Form\Type\RecoveryType;
  18. use App\Form\Type\RegistrationType;
  19. use App\Model\MailChimp\MailChimpWebhookRequest;
  20. use App\Services\AppHelper;
  21. use App\Services\ClinicManager;
  22. use App\Services\CreateClinicGiftVoucher;
  23. use App\Services\CreateDefaultDataClinic;
  24. use App\Services\CreateDefaultPaymentType;
  25. use App\Services\MailChimp\MailChimpClientImpl;
  26. use App\Services\MailChimp\MailChimpException;
  27. use App\Services\UserManager;
  28. use Psr\Log\LoggerInterface;
  29. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  30. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  31. use Symfony\Component\HttpFoundation\JsonResponse;
  32. use Symfony\Component\HttpFoundation\RedirectResponse;
  33. use Symfony\Component\HttpFoundation\Request;
  34. use Symfony\Component\HttpFoundation\Response;
  35. use Symfony\Component\Routing\Annotation\Route;
  36. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  37. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  38. use WhiteOctober\BreadcrumbsBundle\Model\Breadcrumbs;
  39. use App\Entity\Clinic\Membership\Membership;
  40. use App\Entity\Clinic\Clinic;
  41. use App\Entity\Website;
  42. use App\Services\MembershipService;
  43. use App\Entity\Patient\UsedMembership;
  44. use App\Entity\Patient\Payment;
  45. use App\Services\InvoiceHistoryService;
  46. use App\Entity\Patient\Invoice\InvoiceHistory;
  47. use App\Entity\Patient\Invoice;
  48. use App\Services\StripeService;
  49. use App\Entity\UsedMembershipItems;
  50. use App\Entity\Patient\UsedMembershipHistory;
  51. use App\Entity\Clinic\GenericSystemEmails;
  52. use App\Entity\Clinic\Stock\TreatmentClinic;
  53. use App\Entity\Clinic\SystemEmails;
  54. use App\Entity\Domain;
  55. use App\Form\Model\SearchFilter;
  56. use App\Entity\Communication;
  57. use App\Services\Plivo;
  58. use App\Services\Twilio;
  59. use App\Services\SmsService;
  60. use Exception;
  61. /**
  62.  * Class DefaultController.
  63.  */
  64. class DefaultController extends AbstractController
  65. {
  66.     /**
  67.      * @var Breadcrumbs
  68.      */
  69.     private $breadcrumbs;
  70.     /**
  71.      * @var UserPasswordEncoderInterface
  72.      */
  73.     private $userPasswordEncoder;
  74.     /**
  75.      * @var SESManager
  76.      */
  77.     private $SESManager;
  78.     /**
  79.      * @var CreateDefaultDataClinic
  80.      */
  81.     private $createDefaultDataClinic;
  82.     /**
  83.      * @var CreateDefaultPaymentType
  84.      */
  85.     private $createDefaultPaymentType;
  86.     /**
  87.      * @var ClinicManager
  88.      */
  89.     private $clinicManager;
  90.     /**
  91.      * @var LoggerInterface
  92.      */
  93.     private $logger;
  94.     /**
  95.      * @var MembershipService
  96.      */
  97.     private $membershipService;
  98.     /**
  99.      * @var InvoiceHistoryService
  100.      */
  101.     private $historyService;
  102.     /**
  103.      * @var StripeService
  104.      */
  105.     private $stripeService;
  106.     /**
  107.      * @var Twilio
  108.      */
  109.     private $twilio;
  110.      /**
  111.      * @var Plivo
  112.      */
  113.     private $plivo;
  114.      /**
  115.      * @var SmsService
  116.      */
  117.     private $smsService;
  118.     public function __construct(
  119.         Breadcrumbs $breadcrumbs,
  120.         UserPasswordEncoderInterface $userPasswordEncoder,
  121.         SESManager $SESManager,
  122.         CreateDefaultDataClinic $createDefaultDataClinic,
  123.         CreateDefaultPaymentType $createDefaultPaymentType,
  124.         ClinicManager $clinicManager,
  125.         LoggerInterface $logger,
  126.         MembershipService $membershipService,
  127.         InvoiceHistoryService $historyService,
  128.         StripeService $stripeService,
  129.         Twilio $twilio,
  130.         Plivo $plivo,
  131.         SmsService $smsService
  132.     ) {
  133.         $this->breadcrumbs $breadcrumbs;
  134.         $this->userPasswordEncoder $userPasswordEncoder;
  135.         $this->SESManager $SESManager;
  136.         $this->createDefaultDataClinic $createDefaultDataClinic;
  137.         $this->createDefaultPaymentType $createDefaultPaymentType;
  138.         $this->clinicManager $clinicManager;
  139.         $this->logger $logger;
  140.         $this->membershipService $membershipService;
  141.         $this->historyService $historyService;
  142.         $this->stripeService $stripeService;
  143.         $this->twilio $twilio;
  144.         $this->plivo $plivo;
  145.         $this->smsService $smsService;
  146.     }
  147.     /**
  148.      * @Route("/", name="indexPage")
  149.      */
  150.     public function index(AppHelper $appHelper)
  151.     {
  152.         $user $this->getUser();
  153.         // $mainDomain='consentz.tribital.com';
  154.         $mainDomain = @$_ENV['APP_DOMAIN'];
  155.         $websiteDomain = @$_ENV['WEBSITE_DOMAIN'];
  156.         $domain $_SERVER['HTTP_HOST'];
  157.         $subdomain str_replace([$websiteDomain'.'], ''$domain);  
  158.         if ($domain != $mainDomain) {
  159.             $checkdomain $this->getDoctrine()->getRepository(Domain::class)
  160.                 ->findOneBy(['domain' => $domain]);
  161.             if ($checkdomain && $checkdomain->getStatus() == 1) {
  162.                 $website $this->getDoctrine()->getRepository(Website::class)
  163.                     ->findOneBy(['clinic_id' => $checkdomain->getClinicId() ,'parent_id' => null'status' => 1]);
  164.                 if ($website) {
  165.                     $html $website->getContent();
  166.                 } else {
  167.                     header('Location: ' $_ENV['APP_URl']);
  168.                     exit;
  169.                 }
  170.                 $getwidgeturl $this->getDoctrine()->getRepository(Clinic::class)->findOneBy(['id' => $checkdomain->getClinicId()]);
  171.                 $widgetUrl $this->generateUrl('widget', ['subDomain' => $getwidgeturl->getSubDomain()]);
  172.                 $html str_replace('{BOOKING_SECTION}''<iframe src="' $widgetUrl '" frameborder="0" id="builder_iframe" style="height: 100%; width: 100%;min-height: 945px;"></iframe>'$html);
  173.                 $html str_replace('{title}'$website->getTitle(), $html);
  174.                 $html str_replace('{faviconicon}'$website->getLogo(), $html);
  175.                 $html .= '<style>'.$website->getCss().'</style>';
  176.                 echo $html;
  177.                 exit;
  178.             } elseif ($checkdomain && ($checkdomain->getStatus() || $checkdomain->getStatus() != 1)) {
  179.                 header('Location: ' $_ENV['APP_URl']);
  180.                 exit;
  181.             } else {
  182.                 header('Location: ' $_ENV['APP_URl'] . 'booking/' $subdomain);
  183.                 exit;
  184.                 // $subdomain=trim($domain,$mainDomain);
  185.                 /*
  186.                 $clinic=$this->getDoctrine()->getRepository(Clinic::class)
  187.                 ->findOneBy(['sub_domain'=>$subdomain ]);
  188.                 if (!$clinic){
  189.                     return new JsonResponse(['status' => 'error','message' => 'Clinic Not Exist' ]);
  190.                 }
  191.                 $em=$this->getDoctrine()->getManager();
  192.                 $superClinincAdmin = new SuperClinicAdmin();
  193.                 $appointment = $superClinincAdmin->getAppointmentData($em,$clinic->getId());
  194.                 $filter = new SearchFilter();
  195.                 $filter->setClinic($clinic);
  196.                 $isPermission = false;
  197.                 if($user){
  198.                     $isPermission = $this->isGranted('edit', $clinic);
  199.                 } 
  200.                 $isOnline = null;
  201.                 $clinicId = $clinic->getId();
  202.                 $repository = $em->getRepository('App:Clinic\Person\ClinicUser');
  203.                 $queryBuilder = $repository->createQueryBuilder('user');
  204.                 $queryBuilder->where('user.clinic = :clinicId')
  205.                     ->andWhere('user.deleted = FALSE')
  206.                     ->setParameter('clinicId', $clinicId)
  207.                     ->orderBy('user.createdAt', 'DESC');
  208.                 $team = $queryBuilder->getQuery()->getResult();
  209.                 if($user){
  210.                     return $this->render('publicProfile.html.twig', [
  211.                         'clinic' => $clinic,
  212.                         'isOnline' => $isOnline,
  213.                         'treatments' => $appointment['treatments'],
  214.                         'isPermission' => $isPermission,
  215.                         'users' =>$team,
  216.                     ]);
  217.                 }
  218.                 else{
  219.                     return $this->render('newPublicProfile.html.twig', [
  220.                         'clinic' => $clinic,
  221.                         'isOnline' => $isOnline,
  222.                         'treatments' => $appointment['treatments'],
  223.                         'isPermission' => $isPermission,
  224.                         'users' =>$team,
  225.                     ]);
  226.                 }
  227.                 */
  228.             }
  229.         }
  230.         // $clinics = $this->getDoctrine()->getRepository(User::Class)->find(3229);
  231.         //  $clinicData = $this->getDoctrine()->getRepository(Clinic::Class)->find(3);
  232.         // $clinics->setCurrentClinic($clinicData);
  233.         // $em = $this->getDoctrine()->getManager();
  234.         //             $em->persist($clinics);
  235.         //             $em->flush();
  236.         // dump($clinics); die;
  237.         return $appHelper->handleDefaultRoute($this->getUser());
  238.     }
  239.     /**
  240.      * @Route("/{slug}", name="indexPage")
  241.     */
  242.     public function indexslug($slug){
  243.         $user $this->getUser();
  244.         
  245.         $mainDomain = @$_ENV['APP_DOMAIN'];
  246.         $websiteDomain = @$_ENV['WEBSITE_DOMAIN'];
  247.         $domain $_SERVER['HTTP_HOST'];
  248.         $subdomain str_replace([$websiteDomain'.'], ''$domain);
  249.         if ($domain != $mainDomain) {
  250.             $checkdomain $this->getDoctrine()->getRepository(Domain::class)
  251.                 ->findOneBy(['domain' => $domain]);
  252.             if ($checkdomain && $checkdomain->getStatus() == 1) {
  253.                 $website $this->getDoctrine()->getRepository(Website::class)
  254.                     ->findOneBy(['clinic_id' => $checkdomain->getClinicId(),'url'=>$slug'status' => 1]);
  255.                 if ($website) {
  256.                     $html $website->getContent();
  257.                 } else {
  258.                     header('Location: ' $_ENV['APP_URl']);
  259.                     exit;
  260.                 }
  261.                 $parentWebsite $this->getDoctrine()->getRepository(Website::class)
  262.                 ->findOneBy(['id' => $website->getParentId(),'parent_id' => null'status' => 1]);
  263.                 $getwidgeturl $this->getDoctrine()->getRepository(Clinic::class)->findOneBy(['id' => $checkdomain->getClinicId()]);
  264.                 $widgetUrl $this->generateUrl('widget', ['subDomain' => $getwidgeturl->getSubDomain()]);
  265.                 $html str_replace('{BOOKING_SECTION}''<iframe src="' $widgetUrl '" frameborder="0" id="builder_iframe" style="height: 100%; width: 100%;min-height: 945px;"></iframe>'$html);
  266.                if($parentWebsite){
  267.                 $html str_replace('{title}'$parentWebsite->getTitle(), $html);
  268.                 $html str_replace('{faviconicon}'$parentWebsite->getLogo(), $html);
  269.                }else{
  270.                 $html str_replace('{title}''Consentz'$html);
  271.                 $html str_replace('{faviconicon}'''$html);
  272.                }
  273.                 // $html = str_replace('{title}', $parentWebsite->getTitle(), $html);
  274.                 // $html = str_replace('{faviconicon}', $parentWebsite->getLogo(), $html);
  275.                 echo $html;
  276.                 exit;
  277.             } elseif ($checkdomain && ($checkdomain->getStatus() || $checkdomain->getStatus() != 1)) {
  278.                 header('Location: ' $_ENV['APP_URl']);
  279.                 exit;
  280.             } else {
  281.                 header('Location: ' $_ENV['APP_URl'] . 'booking/' $subdomain);
  282.                 exit;
  283.             }
  284.             
  285.         }
  286.         return $appHelper->handleDefaultRoute($this->getUser());
  287.     }   
  288.     /**
  289.      * @Route("/admin/login", name="login")
  290.      * @Template("default/login.html.twig")
  291.      *
  292.      * @return array
  293.      */
  294.     public function login(AuthenticationUtils $authenticationUtils)
  295.     {
  296.         $user $this->getUser();
  297.         // dd($user);
  298.         if($user){
  299.             if($user->getLoginFrom() == 0){
  300.                 $em $this->getDoctrine()->getManager();
  301.                 $user->setLoginFrom(1);
  302.                 $em->persist($user);
  303.                 $em->flush();
  304.             } 
  305.             if ($user->getRole() == 'ROLE_CONSENTZ_ADMIN') {
  306.                 return $this->redirectToRoute('organisation_list');
  307.             }else{
  308.                 if ($user->getClinic() != null) {
  309.                     $clinic $this->getDoctrine()->getRepository(Clinic::class)
  310.                         ->find($user->getClinic());
  311.                 } else if ($user->getOrganisation() && $user->getOrganisation()->getClinics()->count() > && $user->getRole() == 'ROLE_SUPER_CLINIC_ADMIN') {
  312.                     $clinic $user->getOrganisation()->getClinics()->first();
  313.                 }
  314.                 if ($clinic) {
  315.                     return new RedirectResponse($this->generateUrl('appointments_calendar', ['clinicId' => $clinic->getId()]));
  316.                 }
  317.             }
  318.             
  319.         }
  320.         $form $this->createForm(LoginType::class, ['username' => $authenticationUtils->getLastUsername()], [
  321.             'action' => $this->generateUrl('login_check'),
  322.         ]);
  323.         if ($error $authenticationUtils->getLastAuthenticationError()) {
  324.             $this->addFlash('danger'$error->getMessage());
  325.         }
  326.         $this->breadcrumbs->addItem('Welcome to Consentz');
  327.         return ['form' => $form->createView()];
  328.     }
  329.     //==============================for SMS reminder =========================================================(14-03-2023)//
  330.     /**
  331.      * @Route("/admin/send-sms-reminder", name="send_sms_reminder", options={"expose"=true},  methods={"GET"})
  332.      */
  333.     public function sendSMSReminder(Request $request)
  334.     {
  335.         date_default_timezone_set('Europe/London');
  336.         $todayDat date('Y-m-d');
  337.         $em $this->getDoctrine()->getManager();
  338.         $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` 
  339.         left join clinics on clinics.id = appointment.clinic_id
  340.         left join user on user.id = appointment.patient_id
  341.         left join user as a on a.id = appointment.clinic_user_id
  342.         WHERE start >= '" $todayDat "' and user.phone IS NOT NULL and appointment.status!='patientCanceled' group by appointment.id";
  343.         //echo $appo_query;exit;
  344.         $appointment $em->getConnection()->prepare($appo_query);
  345.         $appointment->execute();
  346.         $appointmentList $appointment->fetchAllAssociative();
  347.         $currentDate date('d-m-Y H:i:s');
  348.         //echo $currentDate;
  349.         //echo "<br>";
  350.         foreach ($appointmentList as $list) {
  351.             $dt = new \DateTime($list['start'], new \DateTimeZone($list['clinic_timezone']));
  352.             // change the timezone of the object without changing its time
  353.             $dt->setTimezone(new \DateTimeZone('Europe/London'));
  354.             $list['start'] = $dt->format('Y-m-d H:i:s');
  355.             $appoitmentDate date('d-m-Y H:i'strtotime($list['start']));
  356.             $d1 = new \DateTime($currentDate); // first date
  357.             $d2 = new \DateTime($appoitmentDate); // second date
  358.             $diff $d1->diff($d2); // get difference between two dates
  359.             $years $diff->y;
  360.             $months $diff->m;
  361.             echo $days $diff->d;
  362.             echo "<br>";
  363.             echo $hours $diff->h;
  364.             echo "<br>";
  365.             echo $minutes $diff->i;
  366.             echo "<br>";
  367.             echo $list['appo_id'] . 'clinic(' $list['clinic_id'] . ')';
  368.             echo "<br>";
  369.             echo "====================";
  370.             echo "<br>";
  371.             $hourDiff 1;
  372.             $cronHours date('H:i'strtotime($currentDate));
  373.             $appoitmentHours date('H:i'strtotime($appoitmentDate));
  374.             $sendingDate date('l d M') . ' ' $appoitmentHours;
  375.             $sendingDateForEmail date('l d M');
  376.             $sendingDateForEmail date('l d M'strtotime($list['start']));
  377.             //echo $sendingDate;exit;
  378.             if ($cronHours $appoitmentHours) {
  379.                 $hourDiff 0;
  380.             }
  381.             //$hourDiff = 1;
  382.             if ($hourDiff == 1) {
  383.                 if ($days == && $years == && $months == && $minutes == && $hours 0) {
  384.                     if ($hours == 1) {
  385.                         $selectHours '1 hour';
  386.                     } else {
  387.                         $selectHours $hours ' hours';
  388.                     }
  389.                     $reminder_query "SELECT time,treatment_id FROM `reminder` WHERE time='" $selectHours "' and clinic_id = " $list['clinic_id']; //reminder table
  390.                     $reminder $em->getConnection()->prepare($reminder_query);
  391.                     $reminder->execute();
  392.                     $reminderList $reminder->fetchAllAssociative();
  393.                     //==========new code for check treatment==============//
  394.                     $checkRemindSendStatus = array();
  395.                     foreach ($reminderList as $relist) {
  396.                         array_push($checkRemindSendStatus$relist['treatment_id']);
  397.                     }
  398.                     $arrayContainsNull in_array(null$checkRemindSendStatus);
  399.                     //==========new code for check treatment==============//
  400.                     //dd($checkRemindSendStatus);
  401.                     if (!empty($reminderList)) {
  402.                         if ($arrayContainsNull) {
  403.                            
  404.                             //$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
  405.                             if ($list['reminder_header'] !== '' && $list['reminder_footer'] != '') {
  406.                                 $message "" $list['reminder_header'] . " " $sendingDate " with " $list['name'] . " . " $list['reminder_footer'] . "";
  407.                             } else {
  408.                                 $message "A reminder for you next appointment: " $sendingDate " with " $list['name'] . ".Please contact us to confirm";
  409.                             }
  410.                             $to $list['country_code'] . '' $list['phone'];
  411.                             $clinic $this->getDoctrine()->getRepository(Clinic::class)
  412.                             ->find($list['clinic_id']);
  413.                             $response =  $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
  414.                 
  415.                             //$returnMsgStatus = $this->twilio->sendMessageForReminder($sid, $token, $from, $to, $message);
  416.                             if ($response['status'] == 1) {
  417.                                 $review_name "Appointment Reminder Sms";
  418.                                 $this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name$message$list['appo_id']);
  419.                                 // $em->flush();
  420.                                 $RAW_QUERY5 "UPDATE `google_event` SET `status` = 'reminderSent' WHERE appointment_id = " $list['appo_id'];;
  421.                                 $statements5 $em->getConnection()->prepare($RAW_QUERY5);
  422.                                 $statements5->execute();
  423.                                 $RAW_QUERY6 "UPDATE `appointment` SET `status` = 'reminderSent' WHERE id = " $list['appo_id'];;
  424.                                 $statements6 $em->getConnection()->prepare($RAW_QUERY6);
  425.                                 $statements6->execute();
  426.                             }
  427.                             if ($list['email'] != '' && $list['verified_email'] == 1) {
  428.                                 $user_email $list['email'];
  429.                                 $user_name $list['first_name'] . ' ' $list['last_name'];
  430.                                 $pract_name $list['pract_first_name'] . ' ' $list['pract_last_name'];
  431.                                 //$email_body = $this->returnEmailTemplateSendEmailReminder($user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
  432.                                 $email_body $this->returnEmailTemplateSendEmailReminder($list['appo_id'], $list['clinic_id'], $list['clinic_email'], $list['verified_email'], $user_email$user_name$sendingDateForEmail$appoitmentHours$pract_name);
  433.                                 if ($email_body['status'] != 0) {
  434.                                     $review_name "Appointment Reminder - Email";
  435.                                     $message json_encode($email_body['content']);
  436.                                     $this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name$message$list['appo_id'], 6);
  437.                                 }
  438.                             }
  439.                             echo "need to " $hours " reminder call";
  440.                         } else {
  441.                             $arrayContainsId in_array($list['treatment_clinic_id'], $checkRemindSendStatus);
  442.                             if ($arrayContainsId) {
  443.                           
  444.                                 //$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
  445.                                 if ($list['reminder_header'] !== '' && $list['reminder_footer'] != '') {
  446.                                     $message "" $list['reminder_header'] . " " $sendingDate " with " $list['name'] . " . " $list['reminder_footer'] . "";
  447.                                 } else {
  448.                                     $message "A reminder for you next appointment: " $sendingDate " with " $list['name'] . ".Please contact us to confirm";
  449.                                 }
  450.                             
  451.                                 $to $list['country_code'] . '' $list['phone'];
  452.                                 $clinic $this->getDoctrine()->getRepository(Clinic::class)
  453.                             ->find($list['clinic_id']);
  454.                                   $returnMsgStatus =  $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
  455.                       
  456.                              //   $returnMsgStatus = $this->twilio->sendMessageForReminder($sid, $token, $from, $to, $message);
  457.                                 if ($returnMsgStatus['status'] == 1) {
  458.                                     $review_name "Appointment Reminder Sms";
  459.                                     $this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name$message$list['appo_id']);
  460.                                     // $em->flush();
  461.                                     $RAW_QUERY5 "UPDATE `google_event` SET `status` = 'reminderSent' WHERE appointment_id = " $list['appo_id'];;
  462.                                     $statements5 $em->getConnection()->prepare($RAW_QUERY5);
  463.                                     $statements5->execute();
  464.                                     $RAW_QUERY6 "UPDATE `appointment` SET `status` = 'reminderSent' WHERE id = " $list['appo_id'];;
  465.                                     $statements6 $em->getConnection()->prepare($RAW_QUERY6);
  466.                                     $statements6->execute();
  467.                                 }
  468.                                 if ($list['email'] != '' && $list['verified_email'] == 1) {
  469.                                     $user_email $list['email'];
  470.                                     $user_name $list['first_name'] . ' ' $list['last_name'];
  471.                                     $pract_name $list['pract_first_name'] . ' ' $list['pract_last_name'];
  472.                                     //$email_body = $this->returnEmailTemplateSendEmailReminder($user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
  473.                                     $email_body $this->returnEmailTemplateSendEmailReminder($list['appo_id'], $list['clinic_id'], $list['clinic_email'], $list['verified_email'], $user_email$user_name$sendingDateForEmail$appoitmentHours$pract_name);
  474.                                     if ($email_body['status'] != 0) {
  475.                                         $review_name "Appointment Reminder - Email";
  476.                                         $message json_encode($email_body['content']);
  477.                                         $this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name$message$list['appo_id'], 6);
  478.                                     }
  479.                                 }
  480.                                 echo "need to " $hours " reminder call";
  481.                             }
  482.                         }
  483.                     }
  484.                     //echo $selectHours;exit;
  485.                 }
  486.                 if ($days && $years == && $months == && $minutes == && $hours == 0) {
  487.                     if ($days == 1) {
  488.                         $selectDay '1 Day';
  489.                     } else {
  490.                         $selectDay $days ' Days';
  491.                     }
  492.                     $reminder_query "SELECT time,treatment_id FROM `reminder` WHERE time='" $selectDay "' and clinic_id = " $list['clinic_id']; //reminder table
  493.                     $reminder $em->getConnection()->prepare($reminder_query);
  494.                     $reminder->execute();
  495.                     $reminderList $reminder->fetchAllAssociative();
  496.                     //==========new code for check treatment==============//
  497.                     $checkRemindSendStatus = array();
  498.                     foreach ($reminderList as $relist) {
  499.                         array_push($checkRemindSendStatus$relist['treatment_id']);
  500.                     }
  501.                     $arrayContainsNull in_array(null$checkRemindSendStatus);
  502.                     //==========new code for check treatment==============//
  503.                     if (!empty($reminderList)) {
  504.                         if ($arrayContainsNull) {
  505.                  
  506.                             $sendingDate date('l d M H-i'strtotime($list['start']));
  507.                             $sendingDateForEmail date('l d M'strtotime($list['start']));
  508.                             //$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
  509.                             if ($list['reminder_header'] !== '' && $list['reminder_footer'] != '') {
  510.                                 $message "" $list['reminder_header'] . " " $sendingDate " with " $list['name'] . " . " $list['reminder_footer'] . "";
  511.                             } else {
  512.                                 $message "A reminder for you next appointment: " $sendingDate " with " $list['name'] . ".Please contact us to confirm";
  513.                             }
  514.                        
  515.                             $to $list['country_code'] . '' $list['phone'];
  516.                             $clinic $this->getDoctrine()->getRepository(Clinic::class)
  517.                             ->find($list['clinic_id']);
  518.                             $returnMsgStatus =  $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
  519.                            // $returnMsgStatus = $this->twilio->sendMessageForReminder($sid, $token, $from, $to, $message);
  520.                             if ($returnMsgStatus['status'] == 1) {
  521.                                 $review_name "Appointment Reminder Sms";
  522.                                 $this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name$message$list['appo_id']);
  523.                                 // $em->flush();
  524.                                 $RAW_QUERY5 "UPDATE `google_event` SET `status` = 'reminderSent' WHERE appointment_id = " $list['appo_id'];;
  525.                                 $statements5 $em->getConnection()->prepare($RAW_QUERY5);
  526.                                 $statements5->execute();
  527.                                 $RAW_QUERY6 "UPDATE `appointment` SET `status` = 'reminderSent' WHERE id = " $list['appo_id'];;
  528.                                 $statements6 $em->getConnection()->prepare($RAW_QUERY6);
  529.                                 $statements6->execute();
  530.                             }
  531.                             if ($list['email'] != '' && $list['verified_email'] == 1) {
  532.                                 $user_email $list['email'];
  533.                                 $user_name $list['first_name'] . ' ' $list['last_name'];
  534.                                 $pract_name $list['pract_first_name'] . ' ' $list['pract_last_name'];
  535.                                 //$email_body = $this->returnEmailTemplateSendEmailReminder($user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
  536.                                 $email_body $this->returnEmailTemplateSendEmailReminder($list['appo_id'], $list['clinic_id'], $list['clinic_email'], $list['verified_email'], $user_email$user_name$sendingDateForEmail$appoitmentHours$pract_name);
  537.                                 if ($email_body['status'] != 0) {
  538.                                     $review_name "Appointment Reminder - Email";
  539.                                     $message json_encode($email_body['content']);
  540.                                     $this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name$message$list['appo_id'], 6);
  541.                                 }
  542.                             }
  543.                             echo "need to " $selectDay " day reminder call";
  544.                         } else {
  545.                             $arrayContainsId in_array($list['treatment_clinic_id'], $checkRemindSendStatus);
  546.                             if ($arrayContainsId) {
  547.                         
  548.                                 $sendingDate date('l d M H-i'strtotime($list['start']));
  549.                                 $sendingDateForEmail date('l d M'strtotime($list['start']));
  550.                                 //$message = "A reminder for you next appointment: " . $sendingDate . " with " . $list['name'] . ".Please contact us to confirm";
  551.                                 if ($list['reminder_header'] !== '' && $list['reminder_footer'] != '') {
  552.                                     $message "" $list['reminder_header'] . " " $sendingDate " with " $list['name'] . " . " $list['reminder_footer'] . "";
  553.                                 } else {
  554.                                     $message "A reminder for you next appointment: " $sendingDate " with " $list['name'] . ".Please contact us to confirm";
  555.                                 }
  556.                            
  557.                                 $to $list['country_code'] . '' $list['phone'];
  558.                                     $clinic $this->getDoctrine()->getRepository(Clinic::class)
  559.                                 ->find($list['clinic_id']);
  560.                                 $returnMsgStatus =  $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
  561.                             
  562.                                 //$returnMsgStatus = $this->twilio->sendMessageForReminder($sid, $token, $from, $to, $message);
  563.                                 if ($returnMsgStatus['status'] == 0) {
  564.                                     $review_name "Appointment Reminder Sms";
  565.                                     $this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name$message$list['appo_id']);
  566.                                     // $em->flush();
  567.                                     $RAW_QUERY5 "UPDATE `google_event` SET `status` = 'reminderSent' WHERE appointment_id = " $list['appo_id'];;
  568.                                     $statements5 $em->getConnection()->prepare($RAW_QUERY5);
  569.                                     $statements5->execute();
  570.                                     $RAW_QUERY6 "UPDATE `appointment` SET `status` = 'reminderSent' WHERE id = " $list['appo_id'];;
  571.                                     $statements6 $em->getConnection()->prepare($RAW_QUERY6);
  572.                                     $statements6->execute();
  573.                                 }
  574.                                 if ($list['email'] != '' && $list['verified_email'] == 1) {
  575.                                     $user_email $list['email'];
  576.                                     $user_name $list['first_name'] . ' ' $list['last_name'];
  577.                                     $pract_name $list['pract_first_name'] . ' ' $list['pract_last_name'];
  578.                                     //$email_body = $this->returnEmailTemplateSendEmailReminder($user_email, $user_name, $sendingDateForEmail, $appoitmentHours, $pract_name);
  579.                                     $email_body $this->returnEmailTemplateSendEmailReminder($list['appo_id'], $list['clinic_id'], $list['clinic_email'], $list['verified_email'], $user_email$user_name$sendingDateForEmail$appoitmentHours$pract_name);
  580.                                     if ($email_body['status'] != 0) {
  581.                                         $review_name "Appointment Reminder - Email";
  582.                                         $message json_encode($email_body['content']);
  583.                                         $this->addSendReminderCorrespondence($list['patient_id'], $list['clinic_id'], $review_name$message$list['appo_id'], 6);
  584.                                     }
  585.                                 }
  586.                                 echo "need to " $selectDay " day reminder call";
  587.                             }
  588.                         }
  589.                     }
  590.                 }
  591.             }
  592.         }
  593.         echo "<br>";
  594.         exit;
  595.         return $this->json(['status' => "success"'msg' => 'OK']);
  596.         exit;
  597.     }
  598.     public function addSendReminderCorrespondence($patient_id$clinic_id$review_name$message$appointment_id$type 5)
  599.     {
  600.         $message mysqli_real_escape_string($message);
  601.         $em $this->getDoctrine()->getManager();
  602.         $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 "')";
  603.         $statements $em->getConnection()->prepare($RAW_QUERY);
  604.         $statements->execute();
  605.         $this->addAutomatedPatientMessage($em$patient_id$clinic_id,  $review_name$message$type);
  606.         return true;
  607.     }
  608.     public function sendSMSReminderCreatedByOthers(Request $request)
  609.     {
  610.         //get clinic_id
  611.         $this->logger->error('cron job is working fine');
  612.         // $message = "Test Message";
  613.         // $sid = "AC7c4fcd71a8000f9b3150e96da80ed494";
  614.         // $token = "fc58ee2a75a71a71138d783deafacdc4";
  615.         // $from = "+17622543122";
  616.         // $to = "+918233922863";
  617.         // $this->twilio->send($sid, $token, $from, $to, $message);
  618.         $em $this->getDoctrine()->getManager();
  619.         $RAW_QUERY1 "SELECT DISTINCT clinic_id FROM `reminder`"//reminder table
  620.         $statements1 $em->getConnection()->prepare($RAW_QUERY1);
  621.         if ($statements1->execute()) {
  622.             $res1 $statements1->fetchAllAssociative();
  623.             foreach ($res1 as $clinic_id) {
  624.                 //appointment table
  625.                 $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'];
  626.                 $statements2 $em->getConnection()->prepare($RAW_QUERY2);
  627.                 $statements2->execute();
  628.                 $res2 $statements2->fetchAllAssociative();
  629.                 $now_time '';
  630.                 $clinic $this->getDoctrine()->getRepository(Clinic::class)->find($clinic_id['clinic_id']);
  631.                 if (!empty($res2)) {
  632.                     foreach ($res2 as $res) {
  633.                         //get time
  634.                         $RAW_QUERY3 "SELECT time,treatment_id FROM `reminder` WHERE clinic_id = " $res['clinic_id']; //reminder table
  635.                         $statements3 $em->getConnection()->prepare($RAW_QUERY3);
  636.                         $statements3->execute();
  637.                         $res3 $statements3->fetchAllAssociative();
  638.                         if (!empty($res3)) {
  639.                             foreach ($res3 as $time) {
  640.                                 if ($time['time']) {
  641.                                     $a explode(" "$time['time']);
  642.                                     if ($a[0] && $a[1]) {
  643.                                         $number_time $a[0];
  644.                                         $string_time $a[1];
  645.                                         if (!empty($a[0]) && $a[1] == 'hour' || $a[1] == 'hours') {
  646.                                             $now_time date('Y-m-d H:i'strtotime('+' $a[0] . ' hour')); // today time - time
  647.                                         } else {
  648.                                             $now_time date('Y-m-d H:i'strtotime('+' $a[0] . ' day')); // today time - date
  649.                                         }
  650.                                         $match_date date('Y-m-d H:i'strtotime($res['start'])); //Actual Appointment date
  651.                                         //====================================================New
  652.                                         $subSevenMin strtotime($now_time '- 6 minute');
  653.                                         $subSevenMinTime date('Y-m-d H:i'$subSevenMin);
  654.                                         $addSevenMin strtotime($now_time '+ 6 minute');
  655.                                         $addSevenMinTime date('Y-m-d H:i'$addSevenMin);
  656.                                         //=====================================================New
  657.                                         if ($match_date >= $subSevenMinTime && $match_date <= $addSevenMinTime) {
  658.                                             //get twilio id using clinic_id
  659.                                             $RAW_QUERY5 "SELECT country_code,phone FROM `user` WHERE id=" $res['patient_id'];
  660.                                             $statements5 $em->getConnection()->prepare($RAW_QUERY5);
  661.                                             $statements5->execute();
  662.                                             $res5 $statements5->fetchAllAssociative();
  663.                                             $message "Hi, You have an appointment in " $time['time'];
  664.                                             $to $res5[0]['country_code'] . '' $res5[0]['phone'];
  665.                                             $this->smsService->sendSMSNumber($clinic,$to ,$message,'patient');
  666.                                         }
  667.                                     }
  668.                                 }
  669.                             }
  670.                         }
  671.                     }
  672.                 }
  673.             }
  674.         }
  675.         return $this->json(['status' => "success"'msg' => 'OK']);
  676.     }
  677.     //==============================for SMS reminder =========================================================(14-03-2023)//
  678.     //==============================for otp auth and login =========================================================//
  679.     /**
  680.      * @Route("/admin/custom-login-otp", name="custom_login_otp", options={"expose"=true},  methods={"GET"})
  681.      */
  682.     public function checkLoginOtpCustom(Request $requestUserPasswordEncoderInterface $passwordEncoder): JsonResponse
  683.     {
  684.         $json = [];
  685.         $json['username'] = $request->get('username');
  686.         $json['password'] = $request->get('password');
  687.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy(['username' => $json['username']]); //get user details
  688.         if (!empty($user) && !empty($user->getLastOTPVerified())) //check last otp verified
  689.         {
  690.             $last_verified_time $user->getLastOTPVerified(); //get
  691.             $now strtotime(date('Y-m-d H:i:s')); // today date
  692.             $your_date strtotime($last_verified_time);
  693.             $datediff $now $your_date;
  694.             $date_diff round($datediff / (60 60 24));
  695.             if ($date_diff <= 5) {
  696.                 return $this->json(['status' => "success"'msg' => 'Please Login']);
  697.             }
  698.         }
  699.         
  700.         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') {
  701.           return $this->json(['status' => "success"'msg' => 'Please Login']);
  702.         }
  703.         
  704.         if (!empty($user) && (!empty($user->getEmail()) || (!empty($user->getPhone())))) //check phone no. or email
  705.         {
  706.             $user_id $user->getid();
  707.             $otp_code random_int(100000999999);
  708.             $em $this->getDoctrine()->getManager();
  709.             
  710.             if($json['username'] == 'demo') {
  711.               $otp_code '1234';
  712.             }
  713.             
  714.             
  715.             $RAW_QUERY "UPDATE `user` set otp = '" $otp_code "', otp_sent_at = '" date('Y-m-d H:i:s') . "' WHERE id =" $user_id;
  716.             $statements $em->getConnection()->prepare($RAW_QUERY);
  717.             if ($statements->execute()) {
  718.                 $user_name '';
  719.                 if (!empty($user->getUsername())) {
  720.                     $user_name $user->getUsername();
  721.                 }
  722.                 $message "Hi " $user_name ", Your Consentz login OTP is " $otp_code;
  723.                 try {
  724.                     if (!empty($user->getEmail())) //send email code
  725.                     {
  726.                         $from 'mail@consentz.com';
  727.                         $id_msg $message '-' $user->getEmail();
  728.                         $to $user->getEmail();
  729.                         $subject "Consentz One Time Passcode Verification";
  730.                         $email_body $this->returnEmailTemplateForOTP($user_name$otp_code);
  731.                         $this->SESManager->sendEmailToProspect($email_body$to$id_msg$subject$from); //email
  732.                     }
  733.                     $this->logger->info('inside sms passwpord');
  734.                     if (!empty($user->getPhone())) {
  735.                         $country_code '';
  736.                         if (empty($user->getCountryCode())) {
  737.                             $country_code '+44';
  738.                         } else {
  739.                             $country_code $user->getCountryCode();
  740.                         }
  741.                         $to $country_code $user->getPhone();
  742.                         $sid $user->getClinic()->getTwilio()->getSid();
  743.                         $token $user->getClinic()->getTwilio()->getToken();
  744.                         $from $user->getClinic()->getTwilio()->getNumberFrom();
  745.             
  746.                         $this->twilio->send($sid$token$from$to$message);
  747.                     }
  748.                 } finally {
  749.                     return $this->json(['status' => 'success''success' => $otp_code '@' $user_id'msg' => 'OTP send successfully']);
  750.                 }
  751.             }
  752.         } else {
  753.             return $this->json(['status' => 'error''msg' => 'Invalid Credentials']);
  754.         }
  755.     }
  756.     /**
  757.      * @Route("/admin/check-custom-otp", name="check_custom_otp", options={"expose"=true},  methods={"GET"})
  758.      */
  759.     public function checkCustomOTP(Request $request//Need to check otp there
  760.     {
  761.         $json = [];
  762.         $json['otp'] = $request->get('otp');
  763.         $json['userid'] = $request->get('userid');
  764.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy(['id' => $json['userid']]);
  765.         $otp $user->getOtp();
  766.         if (!empty($otp)) {
  767.             if ($otp == $json['otp']) {
  768.                 $em $this->getDoctrine()->getManager();
  769.                 $RAW_QUERY "UPDATE `user` set last_otp_verified = '" date('Y-m-d H:i:s') . "' WHERE id =" $json['userid'];
  770.                 $statements $em->getConnection()->prepare($RAW_QUERY);
  771.                 $statements->execute();
  772.                 return $this->json(['status' => "success"'msg' => 'OTP Matched']);
  773.             } else {
  774.                 return $this->json(['status' => 'error''msg' => 'OTP does not mach']);
  775.             }
  776.         } else {
  777.             return $this->json(['status' => 'error''msg' => 'Something went wrong']);
  778.         }
  779.     }
  780.     /**
  781.      * @Route("/admin/resend-otp", name="resned_otp", options={"expose"=true},  methods={"GET"})
  782.      */
  783.     public function resendOTP(Request $request//Need to check otp there
  784.     {
  785.         $json = [];
  786.         $json['userid'] = $request->get('uid');
  787.         $user_id $json['userid'];
  788.         if (!empty($user_id)) {
  789.             $user $this->getDoctrine()->getRepository(User::class)->findOneBy(['id' => $user_id]);
  790.             $otp_code random_int(100000999999); //generate otp
  791.             $em $this->getDoctrine()->getManager();
  792.             $RAW_QUERY "UPDATE `user` set otp = '" $otp_code "', otp_sent_at = '" date('Y-m-d H:i:s') . "' WHERE id =" $user_id;
  793.             $statements $em->getConnection()->prepare($RAW_QUERY);
  794.             if ($statements->execute()) {
  795.                 $user_name '';
  796.                 if (!empty($user->getUsername())) {
  797.                     $user_name $user->getUsername();
  798.                 }
  799.                 $message "Hi " $user_name ", Your Consentz login OTP is " $otp_code;
  800.                 try {
  801.                     $this->logger->info('inside sms pss verig');
  802.                     if (!empty($user->getEmail())) //send email code
  803.                     {
  804.                         $from 'mail@consentz.com';
  805.                         $id_msg $message '-' $user->getEmail();
  806.                         $to $user->getEmail();
  807.                         $subject "Consentz One Time Passcode Verification";
  808.                         $email_body $this->returnEmailTemplateForOTP($user_name$otp_code);
  809.                         $this->SESManager->sendEmailToProspect($email_body$to$id_msg$subject$from); //email
  810.                     }
  811.                     if (!empty($user->getPhone())) {
  812.                         $country_code '';
  813.                         if (empty($user->getCountryCode())) {
  814.                             $country_code '+44';
  815.                         } else {
  816.                             $country_code $user->getCountryCode();
  817.                         }
  818.                         $to $country_code $user->getPhone();
  819.                         $sid $user->getClinic()->getTwilio()->getSid();
  820.                         $token $user->getClinic()->getTwilio()->getToken();
  821.                         $from $user->getClinic()->getTwilio()->getNumberFrom();
  822.                       
  823.                         $this->twilio->send($sid$token$from$to$message); //send sms
  824.                     }
  825.                 } finally {
  826.                     return $this->json(['status' => 'success''success' => $otp_code '@' $user_id'msg' => 'OTP resend successfully']);
  827.                 }
  828.             }
  829.         } else {
  830.             return $this->json(['status' => 'error''msg' => 'Something went wrong']);
  831.         }
  832.     }
  833.     public function returnEmailTemplateSendEmailReminder($appointment_id$clinic_id$clinic_email$mail_verirfy$user_email$patient_name$appointment_date$appointment_time$practitioner_name)
  834.     {
  835.         $returnArray['status'] = '';
  836.         $returnArray['content'] = '';
  837.         $em $this->getDoctrine()->getManager();
  838.         $appo_query "SELECT content from system_emails where email_key = 2 and clinic_id = 3";
  839.         //$appo_query = "SELECT content from generic_system_emails where id = 2";
  840.         $appointment $em->getConnection()->prepare($appo_query);
  841.         $appointment->execute();
  842.         $email_template $appointment->fetchAllAssociative();
  843.         if (!empty($email_template)) {
  844.             if (!empty($email_template[0]['content'])) {
  845.                 $template $email_template[0]['content'];
  846.             }
  847.             $mixed_search = array("[Patient Name]""[Appointment Date]""[Appointment Time]""[Practitioner Name]");
  848.             $mixed_replace = array($patient_name$appointment_date$appointment_time$practitioner_name);
  849.             $messagebody str_replace($mixed_search$mixed_replace$template);
  850.             $content $messagebody;
  851.             $from 'mail@consentz.com';
  852.             if ($clinic_email != '') {
  853.                 $from $clinic_email;
  854.             }
  855.             $subject "Appointment Reminder - Email";
  856.             $to $user_email;
  857.             $id_msg $subject '-' $user_email;
  858.             $status $this->SESManager->sendEmailToProspectForReminder($content$to$id_msg$subject$from);
  859.             $returnArray['status'] = $status;
  860.             $returnArray['content'] = $content;
  861.             return $returnArray;
  862.         }
  863.         return $returnArray;
  864.         //email
  865.     }
  866.     public function returnEmailTemplateSendEmailReminderOlllld($appointment_id$clinic_id$clinic_email$mail_verirfy$user_email$patient_name$appointment_date$appointment_time$practitioner_name)
  867.     {
  868.         $appointmentStatus $this->getDoctrine()
  869.             ->getRepository(Appointment::class)
  870.             ->find($appointment_id);
  871.         $em $this->getDoctrine()->getManager();
  872.         $genericEmail $em->getRepository(GenericSystemEmails::class)->findOneBy(['title' => 'Appointment Reminder Email']);
  873.         $systemEmail $em->getRepository(SystemEmails::class)->findOneBy(['clinic' => $clinic_id'email_key' => $genericEmail->getId()]);
  874.         if ($systemEmail) {
  875.             $body $systemEmail;
  876.         } else {
  877.             $body $genericEmail;
  878.         }
  879.         $body $em->getRepository(Appointment::class)->replaceMetaTags($body$appointmentStatus);
  880.         $returnArray['status'] = '';
  881.         $returnArray['content'] = '';
  882.         // $em = $this->getDoctrine()->getManager();
  883.         // $appo_query = "SELECT content from system_emails where email_key = 2 and clinic_id = 3";
  884.         // $appointment = $em->getConnection()->prepare($appo_query);
  885.         // $appointment->execute();
  886.         // $email_template = $appointment->fetchAllAssociative();
  887.         if (!empty($body)) {
  888.             // if (!empty($email_template[0]['content'])) {
  889.             //     $template = $email_template[0]['content'];
  890.             // }
  891.             // $mixed_search = array("[Patient Name]", "[Appointment Date]", "[Appointment Time]", "[Practitioner Name]");
  892.             // $mixed_replace = array($patient_name, $appointment_date, $appointment_time, $practitioner_name);
  893.             // $messagebody = str_replace($mixed_search, $mixed_replace, $template);
  894.             $content $body;
  895.             $from $clinic_email;
  896.             $subject "Appointment Reminder Email";
  897.             // $email_body = $this->returnEmailTemplateSendEmailReminder($patient_name, $appointment_date, $appointment_time, $practitioner_name);
  898.             $to $user_email;
  899.             $id_msg $subject '-' $user_email;
  900.             $status $this->SESManager->sendEmailToProspectForReminder($content$to$id_msg$subject$from);
  901.             $returnArray['status'] = $status;
  902.             $returnArray['content'] = $content;
  903.             return $returnArray;
  904.         }
  905.         return $returnArray;
  906.         //email
  907.     }
  908.     //mail template for post appoitment reminder
  909.     public function returnEmailTemplateSendEmailReminderByRahul($user_email$patient_name$appointment_date$appointment_time$practitioner_name)
  910.     {
  911.         $returnArray['status'] = '';
  912.         $returnArray['content'] = '';
  913.         $em $this->getDoctrine()->getManager();
  914.         $appo_query "SELECT content from system_emails where email_key = 2 and clinic_id = 3";
  915.         $appointment $em->getConnection()->prepare($appo_query);
  916.         $appointment->execute();
  917.         $email_template $appointment->fetchAllAssociative();
  918.         if (!empty($email_template)) {
  919.             if (!empty($email_template[0]['content'])) {
  920.                 $template $email_template[0]['content'];
  921.             }
  922.             $mixed_search = array("[Patient Name]""[Appointment Date]""[Appointment Time]""[Practitioner Name]");
  923.             $mixed_replace = array($patient_name$appointment_date$appointment_time$practitioner_name);
  924.             $messagebody str_replace($mixed_search$mixed_replace$template);
  925.             $content $messagebody;
  926.             $from 'mail@consentz.com';
  927.             $subject "Appointment Reminder Email";
  928.             // $email_body = $this->returnEmailTemplateSendEmailReminder($patient_name, $appointment_date, $appointment_time, $practitioner_name);
  929.             $to $user_email;
  930.             $id_msg $subject '-' $user_email;
  931.             $status $this->SESManager->sendEmailToProspectForReminder($content$to$id_msg$subject$from);
  932.             $returnArray['status'] = $status;
  933.             $returnArray['content'] = $content;
  934.             return $returnArray;
  935.         }
  936.         return $returnArray;
  937.         //email
  938.     }
  939.     //mail template for otp
  940.     public function returnEmailTemplateForOTP($username ''$otp)
  941.     {
  942.         $mail_template "<p>Dear $username,</p>
  943.         <br/>
  944.         <p>We received a request to access your Consentz Account which requires a one time passcode in order to verify your identity.</p>
  945.         <br/>
  946.         <p>Your Consentz OTP is:</p>
  947.         <p><strong>$otp</strong></p>
  948.         <br/>
  949.         <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>
  950.         
  951.         <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>
  952.         <br/>
  953.         <p>Sincerely yours,</p>
  954.         <p>Team Consentz</p>";
  955.         return $mail_template;
  956.     }
  957.     // public function sendLoginSmsOtpMessage(){
  958.     // }
  959.     // public function sendLoginEmailOtpMail(){
  960.     // }
  961.     //==============================for otp auth and login =========================================================//
  962.     /**
  963.      * @Route("/webhook", name="webhook")
  964.      * @Template
  965.      *
  966.      * @return array
  967.      */
  968.     public function webhook()
  969.     {
  970.         $input = @file_get_contents("php://input");
  971.         $data = (array) json_decode($inputtrue);
  972.         $type = isset($data['type']) ? $data['type'] : '';
  973.         if ($type == 'customer.subscription.created') {
  974.             $latestInvId $data['data']['object']['latest_invoice'];
  975.             $sId $data['data']['object']['id'];
  976.             $metaData $data['data']['object']['items']['data'][0]['price']['metadata'];
  977.             $cuId $metaData['cuid'];
  978.             $id $metaData['mid'];
  979.             $cId $metaData['cid'];
  980.             $pId $metaData['pid'];
  981.             $userId $metaData['userId'];
  982.             $this->logger->error('m-chec-11');
  983.             if ($cuId != '' && $id != '' && $cId != '' && $pId != '' && $userId != '') {
  984.                 $practitioner $this->getDoctrine()->getRepository(ClinicUser::class)->findOneBy(['id' => $cuId]);
  985.                 $members $this->getDoctrine()->getRepository(Membership::class)->findOneBy(['id' => $id]);
  986.                 $clinic $this->getDoctrine()->getRepository(Clinic::class)->findOneBy(['id' => $cId]);
  987.                 $patient $this->getDoctrine()->getRepository(Patient::class)->find($pId);
  988.                 $checkIfAlreadyMember $this->getDoctrine()->getRepository(UsedMembership::class)->selectMembershipData($clinic$members$practitioner$patient);
  989.                 $mInvId = isset($checkIfAlreadyMember['id']) ? $checkIfAlreadyMember['id'] : '';
  990.                 if (!$mInvId) {
  991.                     $monthsCount $members->getMonthsCount();
  992.                     $user $this->getDoctrine()->getRepository(User::class)->find($userId);
  993.                     $membership = new UsedMembership();
  994.                     $membership->setClinic($clinic);
  995.                     $membership->setPatient($patient);
  996.                     $membership->setClinicUser($practitioner);
  997.                     $membership->setMembership($members);
  998.                     $membership->setStripeRecurringId($sId);
  999.                     $membership->setMembershipcount($monthsCount);
  1000.                     $membership->setActive(true);
  1001.                     $em $this->getDoctrine()->getManager();
  1002.                     $invoice $this->membershipService->newInvoiceForMembership($patient$clinic$membership$user);
  1003.                     $membership->setInvoice($invoice);
  1004.                     //$em = $this->getDoctrine()->getManager();
  1005.                     $em->persist($membership);
  1006.                     $em->flush();
  1007.                     foreach ($membership->getMembership()->getItems() as $key) {
  1008.                         $em $this->getDoctrine()->getManager();
  1009.                         $usedMembershipItems = new UsedMembershipItems();
  1010.                         if ($key->getType() == 'product') {
  1011.                             $usedMembershipItems->setProduct($key->getProduct());
  1012.                         } else {
  1013.                             $usedMembershipItems->setTreatment($key->getTreatment());
  1014.                         }
  1015.                         $usedMembershipItems->setUsedMembership($membership);
  1016.                         $usedMembershipItems->setType($key->getType());
  1017.                         $usedMembershipItems->setQtyTotal($key->getQuantityTotal());
  1018.                         $usedMembershipItems->setQtyUsed(0);
  1019.                         $usedMembershipItems->setCreatedAt(new \DateTime('now'));
  1020.                         $usedMembershipItems->setUpdatedAt(new \DateTime('now'));
  1021.                         $em->persist($usedMembershipItems);
  1022.                         // Add history..
  1023.                         /*$description = "First time, Quantity for ". $key->getType() ." (". $key->getQuantityTotal() .") is added";
  1024.                         $membershipHistory = new UsedMembershipHistory();
  1025.                         $membershipHistory->setUsedMembershipItems($usedMembershipItems);
  1026.                         $membershipHistory->setUsedMembership($membership);
  1027.                         $membershipHistory->setType($key->getType());
  1028.                         $membershipHistory->setDescription($description);
  1029.                         $membershipHistory->setCreatedAt(new \DateTime('now'));
  1030.                         $membershipHistory->setUpdatedAt(new \DateTime('now'));
  1031.                         $em->persist($membershipHistory);*/
  1032.                         $em->flush();
  1033.                     }
  1034.                     /*$kind = new Kind();
  1035.                     $kind
  1036.                     ->setClinic($clinic)
  1037.                     ->setType(Kind::DEFAULT_STRIPE_CONNECT)
  1038.                     ->setDisabled(false);
  1039.                     $this->getDoctrine()->getManager()->persist($kind);
  1040.                     $this->getDoctrine()->getManager()->flush();
  1041.                     $invId = $invoice->getId();
  1042.                     $payment = new Payment();
  1043.                     $payment->setInvoice($invoice);
  1044.                     $payment->setAmount($members->getDepositAmount());
  1045.                     $payment->setPaymentIntentId($latestInvId);
  1046.                     $payment->setType($kind);
  1047.                     $em = $this->getDoctrine()->getManager();
  1048.                     $em->persist($payment);
  1049.                     $em->flush();
  1050.                     $this->historyService->createHistoryInvoicePayment($invoice, $payment, InvoiceHistory::TYPE_HISTORY_INVOICE_PAYMENT_NEW);
  1051.                     $this->historyService->createHistoryInvoiceVoucher($invoice, InvoiceHistory::TYPE_HISTORY_INVOICE_VOUCHER_NEW);*/
  1052.                 }
  1053.             }
  1054.         } else if ($type == 'invoice.paid') {
  1055.             $metaData $data['data']['object']['lines']['data'][0]['price']['metadata'];
  1056.             $this->logger->error('yess ');
  1057.             $this->logger->error(serialize($data));
  1058.             $this->logger->error('boo ');
  1059.             $cuId $metaData['cuid'];
  1060.             $id $metaData['mid'];
  1061.             $cId $metaData['cid'];
  1062.             $pId $metaData['pid'];
  1063.             $userId $metaData['userId'];
  1064.             $this->logger->error(' check-1 ');
  1065.             if ($cuId != '' && $id != '' && $cId != '' && $pId != '' && $userId != '') {
  1066.                 $practitioner $this->getDoctrine()->getRepository(ClinicUser::class)->findOneBy(['id' => $cuId]);
  1067.                 $members $this->getDoctrine()->getRepository(Membership::class)->findOneBy(['id' => $id]);
  1068.                 $clinic $this->getDoctrine()->getRepository(Clinic::class)->findOneBy(['id' => $cId]);
  1069.                 $patient $this->getDoctrine()->getRepository(Patient::class)->find($pId);
  1070.                 sleep(2);
  1071.                 $checkIfAlreadyMember $this->getDoctrine()->getRepository(UsedMembership::class)->selectMembershipData($clinic$members$practitioner$patient);
  1072.                 $memberId = isset($checkIfAlreadyMember['id']) ? $checkIfAlreadyMember['id'] : '';
  1073.                 $this->logger->error(' check-2 ');
  1074.                 $this->logger->error($memberId);
  1075.                 if ($memberId) {
  1076.                     $latestInvId $data['data']['object']['id'];
  1077.                     $paymentIntant $data['data']['object']['payment_intent'];
  1078.                     $user $this->getDoctrine()->getRepository(User::class)->find($userId);
  1079.                     $invoice $this->getDoctrine()->getRepository(Invoice::class)->find($memberId);
  1080.                     $getPaymentDetail $this->getDoctrine()->getRepository(Payment::class)->checkPaymentIntant($invoice$paymentIntant);
  1081.                     $paymentId = isset($getPaymentDetail['id']) ? $getPaymentDetail['id'] : 0;
  1082.                     $this->logger->error(' check-3 ');
  1083.                     $this->logger->error($paymentId);
  1084.                     if (!$paymentId) {
  1085.                         $this->logger->error(' check-4 ');
  1086.                         $rcount = isset($checkIfAlreadyMember['rcount']) ? (empty($checkIfAlreadyMember['rcount']) ? $checkIfAlreadyMember['rcount']) : 0;
  1087.                         $membershipcount = isset($checkIfAlreadyMember['membershipcount']) ? $checkIfAlreadyMember['membershipcount'] : 0;
  1088.                         $usedMemberId = (isset($checkIfAlreadyMember['memberId']) && !empty($checkIfAlreadyMember['memberId'])) ? $checkIfAlreadyMember['memberId'] : 0;
  1089.                         $subscribeId = (isset($checkIfAlreadyMember['stripe_recurring_id']) && !empty($checkIfAlreadyMember['stripe_recurring_id'])) ? $checkIfAlreadyMember['stripe_recurring_id'] : 0;
  1090.                         $rcount $rcount 1;
  1091.                         if ($rcount == $membershipcount) {
  1092.                             // unsubscribe this subscription.
  1093.                             $this->stripeService->cancelSubscription($subscribeId);
  1094.                             $this->logger->error(' cancelSubscription ');
  1095.                             $this->logger->error($subscribeId);
  1096.                         }
  1097.                         if ($rcount <= $membershipcount) {
  1098.                             $this->logger->error(' update count ');
  1099.                             $this->logger->error($rcount);
  1100.                             $this->getDoctrine()->getRepository(UsedMembership::class)->updateRecurringCount($usedMemberId$rcount);
  1101.                         }
  1102.             $kind $this->doctrine->getRepository(Kind::class)->findOneBy(['clinic' => $clinic'type' => Kind::DEFAULT_STRIPE_CONNECT]);
  1103.                         
  1104.                         if (!$kind) {
  1105.                         $kind = new Kind();
  1106.                         $kind
  1107.                             ->setClinic($clinic)
  1108.                             ->setType(Kind::DEFAULT_STRIPE_CONNECT)
  1109.                             ->setDisabled(false);
  1110.                         $this->getDoctrine()->getManager()->persist($kind);
  1111.                         $this->getDoctrine()->getManager()->flush();
  1112.             }
  1113.                         $payment = new Payment();
  1114.                         $payment->setInvoice($invoice);
  1115.                         $payment->setAmount(($data['data']['object']['total'] / 100));
  1116.                         $payment->setPaymentIntentId($paymentIntant);
  1117.                         $payment->setStripeInvId($latestInvId);
  1118.                         $payment->setType($kind);
  1119.                         $em $this->getDoctrine()->getManager();
  1120.                         $em->persist($payment);
  1121.                         $em->flush();
  1122.                         $this->historyService->createHistoryInvoicePayment($invoice$paymentInvoiceHistory::TYPE_HISTORY_INVOICE_PAYMENT_NEW);
  1123.                         $this->historyService->createHistoryInvoiceVoucher($invoiceInvoiceHistory::TYPE_HISTORY_INVOICE_VOUCHER_NEW);
  1124.                     }
  1125.                 }
  1126.             }
  1127.         }
  1128.         die;
  1129.     }
  1130.     /**
  1131.      * @Route("/admin/password/{hash}", name="password_hash", requirements={"hash": "^[a-zA-Z0-9]{0,32}$"}, methods={"GET", "POST"})
  1132.      * @Template()
  1133.      */
  1134.     public function passwordHash(Request $request$hash)
  1135.     {
  1136.         $em $this->getDoctrine()->getManager();
  1137.         /** @var User $user */
  1138.         $user $em->getRepository(User::class)->findOneBy(['hash' => $hash]);
  1139.         if (!$user) {
  1140.             return $this->redirectToRoute('app_error_hash');
  1141.         }
  1142.         if (isset($_REQUEST['isad']) && $_REQUEST['isad'] == 1) {
  1143.             $user->setEnabled(true);
  1144.             $user->setHash();
  1145.             $em->flush();
  1146.             if ($user instanceof Patient) {
  1147.                 return new RedirectResponse('https://itunes.apple.com/us/app/consentz-patient-app/id1273682006?ls=1&mt=8');
  1148.             }
  1149.             $this->addFlash('success''You have successfully completed the registration process and confirmed your account');
  1150.             return $this->redirectToRoute('login');
  1151.         }
  1152.         $form $this->createForm(AddPasswordType::class, $user, ['encoderPassword' => $this->userPasswordEncoder]);
  1153.         $form->handleRequest($request);
  1154.         if ($form->isSubmitted() && $form->isValid()) {
  1155.             $user->setEnabled(true);
  1156.             $user->setHash();
  1157.             $em->flush();
  1158.             if ($user instanceof Patient) {
  1159.                 return new RedirectResponse('https://itunes.apple.com/us/app/consentz-patient-app/id1273682006?ls=1&mt=8');
  1160.             }
  1161.             if (isset($_REQUEST['forget']) && $_REQUEST['forget'] == 1) {
  1162.               $this->addFlash('success''You have successfully updated your account password');
  1163.               
  1164.             } else {
  1165.               $this->addFlash('success''You have successfully completed the registration process and confirmed your account');
  1166.             }
  1167.             return $this->redirectToRoute('login');
  1168.         } else if ($form->isSubmitted() && !$form->isValid()) {
  1169.           $this->addFlash('danger''The password must be at least 8 characters long and match the confirmation field.');
  1170.           
  1171.         }
  1172.         $this->breadcrumbs->addItem('Set New Password');
  1173.         return [
  1174.             'form' => $form->createView(),
  1175.             'isPatient' => $user instanceof Patient
  1176.         ];
  1177.     }
  1178.     /**
  1179.      * @Route("/admin/forgot", name="forgot_password")
  1180.      * @Template("default/forgot.html.twig")
  1181.      */
  1182.     public function forgot(Request $request)
  1183.     {
  1184.         $userDTO = new Admin();
  1185.         $form $this->createForm(RecoveryType::class, $userDTO);
  1186.         $form->handleRequest($request);
  1187.         if ($form->isSubmitted() && $form->isValid()) {
  1188.             $em $this->getDoctrine()->getManager();
  1189.             /** @var User $user */
  1190.             $user $em->getRepository('App:Person\User')->findOneBy(['username' => $userDTO->getUsername()]);
  1191.             if ($user && $user->isAccountNonLocked()) {
  1192.                 $user->setHash(md5($user->getUsername()));
  1193.                 $em->flush();
  1194.                 $this->SESManager->sendEmail($userUserManager::USER_RECOVERY);
  1195.             }
  1196.             $this->addFlash('success''Success! Check your email to reset your password.');
  1197.             return $this->redirectToRoute('dashboard_index');
  1198.         }
  1199.         $breadcrumbs $this->breadcrumbs;
  1200.         $breadcrumbs->addRouteItem('Sign In''login');
  1201.         $breadcrumbs->addItem('Forgot Password');
  1202.         return ['form' => $form->createView()];
  1203.     }
  1204.  /**
  1205.      * @Route("/admin/registration1", name="registration1", methods={"GET", "POST"})
  1206.      * @Template("default/registration1.html.twig")
  1207.      */
  1208.     public function registration1(Request $requestCreateClinicGiftVoucher $clinicGiftVoucher)
  1209.     {
  1210.       return $this->registration($request$clinicGiftVoucher);
  1211.     }
  1212.     
  1213.     /**
  1214.      * @Route("/admin/registration2", name="registration2", methods={"GET", "POST"})
  1215.      * @Template("default/registration2.html.twig")
  1216.      */
  1217.     public function registration2(Request $requestCreateClinicGiftVoucher $clinicGiftVoucher)
  1218.     {
  1219.       return $this->registration($request$clinicGiftVoucher);
  1220.     }
  1221.     /**
  1222.      * @Route("/admin/registration", name="registration", methods={"GET", "POST"})
  1223.      * @Template("default/registration.html.twig")
  1224.      */
  1225.     public function registration(Request $requestCreateClinicGiftVoucher $clinicGiftVoucher)
  1226.     {
  1227.         /** @var User $user */
  1228.         if (($user $this->getUser()) && ($user instanceof User)) {
  1229.             if ($user->getUsername()) {
  1230.                 $this->addFlash('danger''User ' $user->getUsername() . ' is already logged in. Logout please before registering.');
  1231.             } else {
  1232.                 $this->addFlash('danger''Any user is already logged in. Logout please before registering.');
  1233.             }
  1234.             return $this->redirectToRoute('dashboard_index');
  1235.         }
  1236.         $redirect $request->query->get('redirect');
  1237.         $redirectParams $redirect ? ['redirect' => $redirect] : [];
  1238.         $formUrl $this->generateUrl('registration', ['redirect' => $redirectParams]);
  1239.         $organisation = new Organisation();
  1240.         $admin = new SuperClinicAdmin();
  1241.         $clinic $this->clinicManager->createNewClinic();
  1242.         $organisation->addAdmin($admin);
  1243.         $organisation->addClinic($clinic);
  1244.         $form $this->createForm(RegistrationType::class, $organisation, [
  1245.             'password_encoder' => $this->userPasswordEncoder,
  1246.             'action' => $formUrl,
  1247.         ]);
  1248.         $form->handleRequest($request);
  1249.          
  1250.         if ($form->isSubmitted()) {
  1251.           $admin->setEmail($organisation->getClinicEmail());
  1252.             if ($form->isValid()) {
  1253.                 $admin->setHash(md5($admin->getUsername()));
  1254.                 $password $this->userPasswordEncoder->encodePassword($admin$_POST['plain_password_first']);
  1255.                 $admin->setPassword($password);
  1256.                 $clinic->setTrialEndDate(date('Ymd'strtotime("+14 days")));
  1257.                 $clinic->setName($organisation->getName());
  1258.                 $clinic->setEmail($organisation->getClinicEmail());
  1259.                 $em $this->getDoctrine()->getManager();
  1260.                 $em->persist($organisation);
  1261.                 $em->flush();
  1262.                 foreach ($organisation->getAdmins() as $admin) {
  1263.                     try{
  1264.                     $this->SESManager->sendEmail($adminUserManager::USER_ADMIN_NEW);
  1265.                     }catch(Exception $e){}
  1266.                 }
  1267.                 $this->createDefaultPaymentType->create($clinicKind::DEFAULT_KINDS);
  1268.                 $this->createDefaultDataClinic->createPatient($clinic$admin);
  1269.                 $this->createDefaultDataClinic->createStock($clinic);
  1270.                 $this->createDefaultDataClinic->createQuestionnaire($clinic);
  1271.                 $this->createDefaultDataClinic->createDefaultVatOptions($clinic);
  1272.                 $this->createDefaultDataClinic->createTAndC($clinic);
  1273.                 $this->createDefaultDataClinic->createLearnAboutSources($clinic);
  1274.                 $this->createDefaultDataClinic->createDefaultPmData($clinic);
  1275.                 $clinicGiftVoucher->createVoucher($clinic);
  1276.                 $this->createDefaultDataClinic->createDefaultPatientStatuses($clinic);
  1277.                 
  1278.                 $this->createDefaultDataClinic->createDefaultTreatmentAndDefaultTeamMember($clinic);
  1279.                  
  1280.                  
  1281.                 //$this->SESManager->verifyEmail($clinic, true);
  1282.                 if ($promoCodeValue $form->get('promoCodeValue')->getData()) {
  1283.                     /** @var PromoCode $promoCode */
  1284.                     $promoCode $this->getDoctrine()->getRepository(PromoCode::class)->findOneBy([
  1285.                         'value' => $promoCodeValue,
  1286.                         'clinicEmail' => $clinic->getEmail()
  1287.                     ]);
  1288.                     if ($promoCode) {
  1289.                         $clinic->setPromoCode($promoCode);
  1290.                         $em->flush();
  1291.                     }
  1292.                 }
  1293.                 $this->addClinicInChats($clinic,$organisation);
  1294.                 $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.');
  1295.                 if ($redirect) {
  1296.                     return new RedirectResponse($redirect);
  1297.                 }
  1298.                 return $this->redirectToRoute('dashboard_index');
  1299.             } else {
  1300.                 // Handle errors
  1301.                 $hasNameError false;
  1302.                 foreach ($form->getErrors(true) as $error) {
  1303.                     // You can either log them, display them, or handle them as needed
  1304.                     //echo $error->getMessage(); // This will output the error message
  1305.                     
  1306.                     if (strpos($error->getMessage(), 'already') !== false) {
  1307.                       if(strpos($error->getMessage(), 'Username')) {
  1308.                          $this->addFlash('username_error''Username already taken.');
  1309.                         
  1310.                        }else if(strpos($error->getMessage(), 'Clinic')) {
  1311.                         $form->get('name')->addError(new \Symfony\Component\Form\FormError("Clinic name already taken."));
  1312.                         
  1313.                       }
  1314.                     } else {
  1315.                       $this->addFlash('error'$error->getMessage());
  1316.                     }
  1317.                 }
  1318.             }
  1319.         }
  1320.         $breadcrumbs $this->breadcrumbs;
  1321.         $breadcrumbs->addRouteItem('Sign In''dashboard_index');
  1322.         $breadcrumbs->addItem('Registration');
  1323.         return [
  1324.             'form' => $form->createView(),
  1325.          ];
  1326.     }
  1327.     /**
  1328.      * @Route("/admin/confirm-event/{hash}", name="confirm-event-outside", methods={"GET", "POST"})
  1329.      * @Template()
  1330.      */
  1331.     public function confirmGoogleEvent(Request $request$hash)
  1332.     {
  1333.         /** @var GoogleEvent $event */
  1334.         $event $this->getDoctrine()->getRepository(GoogleEvent::class)->findEventToConfirmPageByHash($hash);
  1335.         if (!$event) {
  1336.             return ['error' => true];
  1337.         }
  1338.         $form $this->createFormBuilder()
  1339.             ->setAction($this->generateUrl('confirm-event-outside', [
  1340.                 'hash' => $hash,
  1341.             ]))
  1342.             ->setMethod('POST')
  1343.             ->getForm();
  1344.         if (Request::METHOD_GET == $request->getMethod()) {
  1345.             return [
  1346.                 'form' => $form->createView(),
  1347.                 'event' => $event
  1348.             ];
  1349.         }
  1350.         $form->handleRequest($request);
  1351.         if ($form->isSubmitted() && $form->isValid()) {
  1352.             $event->setStatus(Appointment::STATUS_CONFIRMED);
  1353.             $this->getDoctrine()->getManager()->flush();
  1354.         }
  1355.         return $this->redirectToRoute('app_confirm_event');
  1356.     }
  1357.     /**
  1358.      * @Route("/calendar/{hash}", name="redirect_from_short_url_for_google_calendar", requirements={"hash": "^[a-zA-Z0-9]{0,12}$"})
  1359.      */
  1360.     public function redirectForGoogleCalendar($hash): RedirectResponse
  1361.     {
  1362.         /** @var ClinicUser $user */
  1363.         $user $this->getDoctrine()->getRepository(ClinicUser::class)
  1364.             ->findOneBy(['hashUserShortUrl' => $hash]);
  1365.         if (!($user instanceof ClinicUser)) {
  1366.             throw $this->createNotFoundException('Calendar not found');
  1367.         }
  1368.         if (!$user->getICalendar() || !$user->isPractitioner()) {
  1369.             throw $this->createNotFoundException('Calendar not found');
  1370.         }
  1371.         return $this->redirect($user->getICalendar()->getUrl());
  1372.     }
  1373.     private function addAutomatedPatientMessage($em$patient_id$clinic_id$subject$message$type 5)
  1374.     {
  1375.         try {
  1376.             $sql "select * from patient_conversation where user_id =? and clinic_id =? and type=?";
  1377.             $ap $em->getConnection()->prepare($sql);
  1378.             $ap->execute([$patient_id$clinic_id0]);
  1379.             $conversation $ap->fetchAssociative();
  1380.             if (!empty($conversation)) {
  1381.                 $communicationModel = new Communication();
  1382.                 $communicationModel->setFromUserId(0);
  1383.                 $communicationModel->setPatientId($patient_id);
  1384.                 $communicationModel->setConversationId($conversation['id']);
  1385.                 $communicationModel->setSenderType(0);
  1386.                 if ($type == 6) {
  1387.                     $communicationModel->setEmailTemplate($message);
  1388.                     $communicationModel->setMessage($subject);
  1389.                 } else {
  1390.                     $communicationModel->setEmailTemplate(NULL);
  1391.                     $communicationModel->setMessage($message);
  1392.                 }
  1393.                 $communicationModel->setType($type);
  1394.                 $communicationModel->setCreatedAt(time());
  1395.                 $entityManager $this->getDoctrine()->getManager();
  1396.                 $entityManager->persist($communicationModel);
  1397.                 $entityManager->flush();
  1398.                 $time  time();
  1399.                 $sql "UPDATE `patient_conversation` SET `updated_at`=? WHERE `id`=?";
  1400.                 $appointment $em->getConnection()->prepare($sql);
  1401.                 $appointment->execute([$time$conversation['id']]);
  1402.             }
  1403.         } catch (Exception $e) {
  1404.         }
  1405.         return true;
  1406.     }
  1407.     /**
  1408.      * @Route("/mailchimp/webhook", name="api_mail_chimp_webhook")
  1409.      */
  1410.     public function mailChimpWebhook(Request $requestMailChimpClientImpl $mailChimpClientImpl): JsonResponse
  1411.     {
  1412.         $key $request->query->get('key');
  1413.         if (Request::METHOD_POST == $request->getMethod() && $key == sha1(MailChimpClientImpl::KEY_WEBHOOK)) {
  1414.             $req = new MailChimpWebhookRequest();
  1415.             $form $this->createForm(MailChimpWebhookRequestType::class, $req);
  1416.             $form->handleRequest($request);
  1417.             try {
  1418.                 $patients $this->getDoctrine()->getRepository(Patient::class)->findPatientByMailChimpWebhook($req);
  1419.             } catch (MailChimpException $exception) {
  1420.                 $this->logger->error('MailChimp webhook find patient', [
  1421.                     'mes' => $exception->getTitle(),
  1422.                     'detail' => $exception->getDetail()
  1423.                 ]);
  1424.                 return $this->json([]);
  1425.             }
  1426.             if (count($patients) > 0) {
  1427.                 /** @var Patient $patient */
  1428.                 foreach ($patients as $patient) {
  1429.                     if ($patient->isReceiveSpecialOfferEmail()) {
  1430.                         $patient->setReceiveSpecialOfferEmail(false);
  1431.                         try {
  1432.                             $mailChimpClientImpl->deleteMember($patient);
  1433.                         } catch (MailChimpException $exception) {
  1434.                             $this->logger->error('MailChimp delete member error', [
  1435.                                 'patientId' => $patient->getId(),
  1436.                                 'patientEmail' => $patient->getEmail(),
  1437.                                 'mes' => $exception->getTitle(),
  1438.                                 'detail' => $exception->getDetail()
  1439.                             ]);
  1440.                         }
  1441.                     }
  1442.                 }
  1443.                 $this->getDoctrine()->getManager()->flush();
  1444.             }
  1445.         }
  1446.         return $this->json([]);
  1447.     }
  1448.     /**
  1449.      * @Route("/random", name="add_random")
  1450.      */
  1451.     public function randomAction()
  1452.     {
  1453.         return 'hi';
  1454.     }
  1455.     
  1456.     private function addClinicInChats($clinic,$organisation){
  1457.         try{
  1458.         $em $this->getDoctrine()->getManager();
  1459.         $clinic $this->getDoctrine()->getRepository(Clinic::class)
  1460.         ->find($clinic->getId());
  1461.         $clinicId $clinic->getId();
  1462.      
  1463.             $sql "SELECT role,id,username FROM user WHERE deleted=? and role =? order by id desc";
  1464.             $ap $em->getConnection()->prepare($sql);
  1465.             $ap->execute([0'ROLE_CONSENTZ_ADMIN']);
  1466.             $admins $ap->fetchAll();
  1467.             $consentzAdmins = [];
  1468.             foreach ($admins as $ad) {
  1469.                 $consentzAdmins[] = $ad['id'];
  1470.             }
  1471.             $roles = ['ROLE_CLINIC_ADMIN''ROLE_PRACTITIONER''ROLE_SUPER_CLINIC_ADMIN'];
  1472.     
  1473.             $rolesPlaceholder implode(','array_fill(0count($roles), '?'));
  1474.             $sql "SELECT role,id FROM user WHERE clinic_id = ? and deleted= ? AND role IN ($rolesPlaceholder)";
  1475.             $ap $em->getConnection()->prepare($sql);
  1476.             $params array_merge([$clinicId0], $roles);
  1477.             $ap->execute($params);
  1478.             $users $ap->fetchAll();
  1479.             $sql "SELECT role,id FROM user WHERE organisation_id=? and deleted= ?";
  1480.             $ap $em->getConnection()->prepare($sql);
  1481.             $ap->execute([$organisation->getId(), 0]);
  1482.             $adminData $ap->fetchAll();
  1483.         if (count($adminData) > 0) {
  1484.             $fromuserId $adminData[0]['id'];
  1485.             $userIds = [];
  1486.             $title $clinic->getName();
  1487.             $g_image $clinic->getProfileImg();
  1488.             $userIds =  array_merge($consentzAdmins$userIds);
  1489.             foreach (array_merge($users$adminData) as $us) {
  1490.                 if ($us['id'] != $fromuserId) {
  1491.                     $userIds[] = $us['id'];
  1492.                 }
  1493.             }
  1494.             $userIds array_unique($userIds);
  1495.             $userIds = (count($userIds) > 0) ? implode(','$userIds) . ',' $fromuserId $fromuserId;
  1496.                 $time time();
  1497.                 $status 1;
  1498.                 $sql "INSERT INTO conversation (type, from_user_id,  title, g_image, user_ids, status,clinic_id, created_at, updated_at)VALUES (?,?,?,?,?,?,?,?,?)";
  1499.                 $messageInsert $em->getConnection()->prepare($sql);
  1500.                 $messageInsert->execute([1$fromuserId$title$g_image$userIds$status$clinicId$time$time]);
  1501.                 $userIdsArray explode(','$userIds);
  1502.                 foreach ($userIdsArray as $userId) {
  1503.                     if (!in_array($userId$consentzAdmins)) {
  1504.                         $opponenetIds = [];
  1505.                         foreach ($userIdsArray as  $uId) {
  1506.                             if ($uId != $userId) {
  1507.                                 $opponenetIds[] = $uId;
  1508.                             }
  1509.                         }
  1510.                         foreach ($opponenetIds as $opponenetId) {
  1511.                             $sql "select * from conversation where type=0 and (user_ids=? or user_ids=?)";
  1512.                             $ap $em->getConnection()->prepare($sql);
  1513.                             $ap->execute([$opponenetId ',' $userId$userId ',' $opponenetId]);
  1514.                             $conversation $ap->fetchAssociative();
  1515.                             if (!$conversation) {
  1516.                                 $time time();
  1517.                                 $sql "INSERT INTO conversation (type, from_user_id,to_user_id, user_ids, status,created_at, updated_at)VALUES (?,?,?,?,?,?,?)";
  1518.                                 $messageInsert $em->getConnection()->prepare($sql);
  1519.                                 $messageInsert->execute([0$userId$opponenetId$userId ',' $opponenetId1$time$time]);
  1520.                             }
  1521.                         }
  1522.                     }
  1523.                 }
  1524.             }
  1525.         }catch(\Exception $e){}
  1526.       
  1527.     }
  1528. }