src/Controller/DefaultController.php line 269

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