src/Controller/ClinicsController.php line 54

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Addresses;
  4. use App\Entity\AiSpecies;
  5. use App\Entity\Baskets;
  6. use App\Entity\ClinicCommunicationMethods;
  7. use App\Entity\Clinics;
  8. use App\Entity\ClinicUserPermissions;
  9. use App\Entity\ClinicUsers;
  10. use App\Entity\CommunicationMethods;
  11. use App\Entity\Countries;
  12. use App\Entity\Distributors;
  13. use App\Entity\DistributorUsers;
  14. use App\Entity\Lists;
  15. use App\Entity\RestrictedDomains;
  16. use App\Entity\Species;
  17. use App\Entity\UserPermissions;
  18. use App\Form\AddressesFormType;
  19. use App\Form\ClinicCommunicationMethodsFormType;
  20. use App\Form\ClinicFormType;
  21. use App\Form\ClinicUsersFormType;
  22. use App\Services\PaginationManager;
  23. use Doctrine\ORM\EntityManagerInterface;
  24. use Nzo\UrlEncryptorBundle\Encryptor\Encryptor;
  25. use phpDocumentor\Reflection\Types\This;
  26. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  27. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  28. use Symfony\Component\HttpFoundation\HeaderUtils;
  29. use Symfony\Component\HttpFoundation\JsonResponse;
  30. use Symfony\Component\HttpFoundation\Request;
  31. use Symfony\Component\HttpFoundation\Response;
  32. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  33. use Symfony\Component\Mailer\MailerInterface;
  34. use Symfony\Component\Mime\Email;
  35. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  36. use Symfony\Component\Routing\Annotation\Route;
  37. class ClinicsController extends AbstractController
  38. {
  39. const ITEMS_PER_PAGE = 12;
  40. private $em;
  41. private $plainPassword;
  42. private $encryptor;
  43. private $mailer;
  44. private $pageManager;
  45. public function __construct(EntityManagerInterface $em, Encryptor $encryptor, MailerInterface $mailer, PaginationManager $pageManager)
  46. {
  47. $this->em = $em;
  48. $this->encryptor = $encryptor;
  49. $this->mailer = $mailer;
  50. $this->pageManager = $pageManager;
  51. }
  52. #[Route('/clinics/register', name: 'clinic_reg')]
  53. public function clinicReg(Request $request): Response
  54. {
  55. $clinics = new Clinics();
  56. $clinicUsers = new ClinicUsers();
  57. $clinics->getClinicUsers()->add($clinicUsers);
  58. $form = $this->createForm(ClinicFormType::class, $clinics)->createView();
  59. $countries = $this->em->getRepository(Countries::class)->findBy([
  60. 'isActive' => 1,
  61. ]);
  62. return $this->render('frontend/clinics/register.html.twig', [
  63. 'form' => $form,
  64. 'countries' => $countries,
  65. ]);
  66. }
  67. #[Route('/clinics/register/check-email', name: 'clinic_check_email')]
  68. public function clinicsCheckEmailAction(Request $request): Response
  69. {
  70. $email = $request->request->get('email');
  71. $domainName = explode('@', $email);
  72. $response['response'] = true;
  73. $restrictedDomains = $this->em->getRepository(RestrictedDomains::class)->arrayFindAll();
  74. $firstName = '';
  75. foreach($restrictedDomains as $restrictedDomain)
  76. {
  77. if(md5($domainName[1]) == md5($restrictedDomain->getName()))
  78. {
  79. $response['response'] = false;
  80. $response['restricted'] = true;
  81. return new JsonResponse($response);
  82. }
  83. }
  84. $distributor = $this->em->getRepository(Distributors::class)->findOneBy([
  85. 'hashedEmail' => md5($email),
  86. ]);
  87. $distributorDomain = $this->em->getRepository(Distributors::class)->findOneBy([
  88. 'domainName' => md5($domainName[1]),
  89. ]);
  90. $distributorUsers = $this->em->getRepository(DistributorUsers::class)->findOneBy([
  91. 'hashedEmail' => md5($email),
  92. ]);
  93. $clinic = $this->em->getRepository(Clinics::class)->findOneBy([
  94. 'hashedEmail' => md5($email),
  95. ]);
  96. $clinicDomain = $this->em->getRepository(Clinics::class)->findOneBy([
  97. 'domainName' => md5($domainName[1]),
  98. ]);
  99. $clinicUsers = $this->em->getRepository(ClinicUsers::class)->findOneBy([
  100. 'hashedEmail' => md5($email),
  101. ]);
  102. if($clinicDomain != null)
  103. {
  104. $user = $this->em->getRepository(ClinicUsers::class)->findOneBy([
  105. 'clinic' => $clinicDomain->getId(),
  106. 'isPrimary' => 1
  107. ]);
  108. if($user != null)
  109. {
  110. $firstName = $this->encryptor->decrypt($user->getFirstName());
  111. }
  112. }
  113. if($distributorDomain != null)
  114. {
  115. $user = $this->em->getRepository(DistributorUsers::class)->findOneBy([
  116. 'distributor' => $distributorDomain->getId(),
  117. 'isPrimary' => 1
  118. ]);
  119. if($user != null)
  120. {
  121. $firstName = $this->encryptor->decrypt($user->getFirstName());
  122. }
  123. }
  124. $response['firstName'] = $firstName;
  125. if($distributor != null || $distributorUsers != null || $clinic != null || $clinicUsers != null || $clinicDomain != null || $distributorDomain != null){
  126. $response['response'] = false;
  127. }
  128. return new JsonResponse($response);
  129. }
  130. #[Route('/clinics/register/create', name: 'clinic_create')]
  131. public function clinicsCreateAction(Request $request, UserPasswordHasherInterface $passwordHasher, MailerInterface $mailer): Response
  132. {
  133. $data = $request->request;
  134. $clinics = $this->em->getRepository(Clinics::class)->findOneBy(['hashedEmail' => md5($data->get('email'))]);
  135. if($clinics == null) {
  136. $clinics = new Clinics();
  137. $plainTextPwd = $this->generatePassword();
  138. if (!empty($plainTextPwd)) {
  139. $domainName = explode('@', $data->get('email'));
  140. $country = $this->em->getRepository(Countries::class)->find($data->get('country'));
  141. $clinics->setClinicName($this->encryptor->encrypt($data->get('clinicName')));
  142. $clinics->setEmail($this->encryptor->encrypt($data->get('email')));
  143. $clinics->setHashedEmail(md5($data->get('email')));
  144. $clinics->setDomainName(md5($domainName[1]));
  145. $clinics->setTelephone($this->encryptor->encrypt($data->get('telephone')));
  146. $clinics->setIntlCode($this->encryptor->encrypt($data->get('business-intl-code')));
  147. $clinics->setIsoCode($this->encryptor->encrypt($data->get('business-iso-code')));
  148. $clinics->setCountry($country);
  149. $clinics->setIsApproved(0);
  150. $this->em->persist($clinics);
  151. $this->em->flush();
  152. // Create user
  153. $clinic = $this->em->getRepository(Clinics::class)->findOneBy([
  154. 'hashedEmail' => md5($data->get('email')),
  155. ]);
  156. $clinicUsers = new ClinicUsers();
  157. $hashedPwd = $passwordHasher->hashPassword($clinicUsers, $plainTextPwd);
  158. $clinicUsers->setClinic($clinic);
  159. $clinicUsers->setFirstName($this->encryptor->encrypt($data->get('firstName')));
  160. $clinicUsers->setLastName($this->encryptor->encrypt($data->get('lastName')));
  161. $clinicUsers->setPosition($this->encryptor->encrypt($data->get('position')));
  162. $clinicUsers->setEmail($this->encryptor->encrypt($data->get('email')));
  163. $clinicUsers->setHashedEmail(md5($data->get('email')));
  164. $clinicUsers->setTelephone($this->encryptor->encrypt($data->get('mobile-telephone')));
  165. $clinicUsers->setIntlCode($this->encryptor->encrypt($data->get('mobile-intl-code')));
  166. $clinicUsers->setIsoCode($this->encryptor->encrypt($data->get('mobile-iso-code')));
  167. $clinicUsers->setRoles(['ROLE_CLINIC']);
  168. $clinicUsers->setPassword($hashedPwd);
  169. $clinicUsers->setIsPrimary(1);
  170. $this->em->persist($clinicUsers);
  171. // Assign Full Permissions
  172. $userPermissions = $this->em->getRepository(UserPermissions::class)->findBy([
  173. 'isClinic' => 1,
  174. ]);
  175. foreach($userPermissions as $userPermission){
  176. $clinicUserPermissions = new ClinicUserPermissions();
  177. $clinicUserPermissions->setClinic($clinic);
  178. $clinicUserPermissions->setUser($clinicUsers);
  179. $clinicUserPermissions->setPermission($userPermission);
  180. $this->em->persist($clinicUserPermissions);
  181. }
  182. // Create Default Basket
  183. $basket = new Baskets();
  184. $firstName = $this->encryptor->decrypt($clinicUsers->getFirstName());
  185. $lastName = $this->encryptor->decrypt($clinicUsers->getLastName());
  186. $basket->setClinic($clinic);
  187. $basket->setName('Fluid Commerce');
  188. $basket->setTotal(0);
  189. $basket->setStatus('active');
  190. $basket->setIsDefault(1);
  191. $basket->setSavedBy($this->encryptor->encrypt($firstName .' '. $lastName));
  192. $this->em->persist($basket);
  193. // Create In App Communication Method
  194. $clinicCommunicationMethod = new ClinicCommunicationMethods();
  195. $communicationMethod = $this->em->getRepository(CommunicationMethods::class)->find(1);
  196. $clinicCommunicationMethod->setClinic($clinic);
  197. $clinicCommunicationMethod->setCommunicationMethod($communicationMethod);
  198. $clinicCommunicationMethod->setSendTo($this->encryptor->encrypt($data->get('email')));
  199. $clinicCommunicationMethod->setIsDefault(1);
  200. $clinicCommunicationMethod->setIsActive(1);
  201. $this->em->persist($clinicCommunicationMethod);
  202. // Create Favourites List
  203. $favourite = new Lists();
  204. $favourite->setClinic($clinic);
  205. $favourite->setListType('favourite');
  206. $favourite->setName('Favourite Items');
  207. $favourite->setItemCount(0);
  208. $favourite->setIsProtected(1);
  209. $this->em->persist($favourite);
  210. $this->em->flush();
  211. // Send Email
  212. $body = $this->render('frontend/clinics/emails/login_credentials.html.twig', [
  213. 'user' => $clinicUsers,
  214. 'password' => $plainTextPwd,
  215. ])->getContent();
  216. $subject = 'Fluid Login Credentials';
  217. $to = $data->get('email');
  218. exec(__DIR__ . '/../../bin/console app:send-email "'. $subject .'" "'. addslashes($body) .'" "'. $to .'" "" "" "'. true .'" > /dev/null 2>&1 &');
  219. }
  220. $response = 'Your Fluid account was successfully created, an email with your login credentials has been sent to your inbox.';
  221. } else {
  222. $response = false;
  223. }
  224. return new JsonResponse($response);
  225. }
  226. #[Route('/clinics/get-company-information', name: 'get_clinic_company_information')]
  227. public function clinicsGetCompanyInformationAction(Request $request): Response
  228. {
  229. $response = json_decode($this->forward('App\Controller\AiProductsController::isAuthenticated')->getContent(), true);
  230. if(!$response['isAuthenticated'])
  231. {
  232. return $this->redirectToRoute('clinics_login');
  233. }
  234. $species = $this->em->getRepository(AiSpecies::class)->findByNameAsc();
  235. $permissions = json_decode($request->request->get('permissions'), true);
  236. $countries = $this->em->getRepository(Countries::class)->findBy([
  237. 'isActive' => 1,
  238. ]);
  239. $clinic = $this->em->getRepository(Clinics::class)->find($this->getUser()->getClinic()->getId());
  240. $response = $this->render('frontend/clinics/company_information.html.twig', [
  241. 'permissions' => $permissions,
  242. 'species' => $species,
  243. 'countries' => $countries,
  244. 'clinic' => $clinic,
  245. ])->getContent();
  246. return new JsonResponse($response);
  247. }
  248. #[Route('/clinics/update/company-information', name: 'clinic_update_company_information')]
  249. public function clinicsUpdateCompanyInformationAction(Request $request): Response
  250. {
  251. $response = json_decode($this->forward('App\Controller\AiProductsController::isAuthenticated')->getContent(), true);
  252. if(!$response['isAuthenticated'])
  253. {
  254. $response = [
  255. 'isAuthenticated' => false,
  256. ];
  257. return new JsonResponse($response);
  258. }
  259. $data = $request->request->all('clinic_form');
  260. $clinicId = $this->getUser()->getClinic()->getId();
  261. $clinics = $this->em->getRepository(Clinics::class)->find($clinicId);
  262. $isApproved = (bool) $clinics->getIsApproved() ?? false;
  263. $tradeLicense = $_FILES['clinic_form']['name']['trade-license-file'];
  264. $tradeLicenseNo = $data['trade-license-no'];
  265. $tradeLicenseExpDate = $data['trade-license-exp-date'];
  266. // Account approval required if reg docs change
  267. if(
  268. !empty($tradeLicense) || $tradeLicenseNo != $this->encryptor->decrypt($clinics->getTradeLicenseNo()) ||
  269. $tradeLicenseExpDate != $clinics->getTradeLicenseExpDate()->format('Y-m-d')
  270. )
  271. {
  272. $clinics->setIsApproved(0);
  273. $isApproved = false;
  274. }
  275. if($clinics != null)
  276. {
  277. $domainName = explode('@', $data['email']);
  278. $clinics->setClinicName($this->encryptor->encrypt($data['clinic-name']));
  279. $clinics->setEmail($this->encryptor->encrypt($data['email']));
  280. $clinics->setDomainName(md5($domainName[1]));
  281. $clinics->setTelephone($this->encryptor->encrypt($data['telephone']));
  282. $clinics->setIsoCode($this->encryptor->encrypt($data['iso-code']));
  283. $clinics->setIntlCode($this->encryptor->encrypt($data['intl-code']));
  284. $clinics->setManagerFirstName($this->encryptor->encrypt($data['manager-first-name']));
  285. $clinics->setManagerLastName($this->encryptor->encrypt($data['manager-last-name']));
  286. $clinics->setManagerIdNo($this->encryptor->encrypt($data['manager-id-no']));
  287. $clinics->setManagerIdExpDate(new \DateTime($data['manager-id-exp-date']));
  288. $clinics->setTradeLicenseNo($this->encryptor->encrypt($data['trade-license-no']));
  289. $clinics->setTradeLicenseExpDate(new \DateTime($data['trade-license-exp-date']));
  290. // Trade License
  291. if(!empty($_FILES['clinic_form']['name']['trade-license-file']))
  292. {
  293. $extension = pathinfo($_FILES['clinic_form']['name']['trade-license-file'], PATHINFO_EXTENSION);
  294. $file = $clinics->getId() . '-' . uniqid() . '.' . $extension;
  295. $targetFile = __DIR__ . '/../../public/documents/' . $file;
  296. if(move_uploaded_file($_FILES['clinic_form']['tmp_name']['trade-license-file'], $targetFile)) {
  297. $clinics->setTradeLicense($file);
  298. }
  299. }
  300. // Logo
  301. if(!empty($_FILES['clinic_form']['name']['logo']))
  302. {
  303. $extension = pathinfo($_FILES['clinic_form']['name']['logo'], PATHINFO_EXTENSION);
  304. $file = $clinics->getId() . '-' . uniqid() . '.' . $extension;
  305. $targetFile = __DIR__ . '/../../public/images/logos/' . $file;
  306. if(move_uploaded_file($_FILES['clinic_form']['tmp_name']['logo'], $targetFile)) {
  307. $clinics->setLogo($file);
  308. }
  309. }
  310. $this->em->persist($clinics);
  311. $this->em->flush();
  312. // Send Approval Email
  313. if(!$isApproved)
  314. {
  315. $orderUrl = $this->getParameter('app.base_url') . '/admin/clinic/'. $clinics->getId();
  316. $html = '<p>Please <a href="'. $orderUrl .'">click here</a> the clinics details.</p><br>';
  317. $html = $this->forward('App\Controller\ResetPasswordController::emailFooter', [
  318. 'html' => $html,
  319. ])->getContent();
  320. $subject = 'Fluid - Account Approval Request';
  321. $to = $this->getParameter('app.email_admin');
  322. exec(__DIR__ . '/../../bin/console app:send-email "'. $subject .'" "'. addslashes($html) .'" "'. $to .'" "" "" "'. true .'" > /dev/null 2>&1 &');
  323. }
  324. $response = [
  325. 'flash' => '<b><i class="fa-solid fa-circle-check"></i></i></b> Company details successfully updated.<div class="flash-close"><i class="fa-solid fa-xmark"></i></div>',
  326. 'isAuthenticated' => true,
  327. ];
  328. }
  329. else
  330. {
  331. $response = [
  332. 'flash' => '<b><i class="fas fa-check-circle"></i> An error occurred.<div class="flash-close"><i class="fa-solid fa-xmark"></i></div>',
  333. 'isAuthenticated' => true,
  334. ];
  335. }
  336. return new JsonResponse($response);
  337. }
  338. #[Route('/clinics/download/trade-license/{tradeLicense}', name: 'clinics_download_trade_license')]
  339. public function downloadTradeLicenseAction(Request $request)
  340. {
  341. $path = __DIR__ . '/../../public/documents/';
  342. $tradeLicense = $path . $request->get('tradeLicense');
  343. $response = new BinaryFileResponse($tradeLicense);
  344. $response->setContentDisposition(
  345. ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  346. basename($tradeLicense)
  347. );
  348. return $response;
  349. }
  350. #[Route('/clinics/update/copy', name: 'clinic_update_copy')]
  351. public function clinicsUpdateCopyAction(Request $request): Response
  352. {
  353. $response = json_decode($this->forward('App\Controller\AiProductsController::isAuthenticated')->getContent(), true);
  354. if(!$response['isAuthenticated'])
  355. {
  356. $response = [
  357. 'isAuthenticated' => false,
  358. ];
  359. return new JsonResponse($response);
  360. }
  361. $response = [];
  362. if($this->getUser() == null)
  363. {
  364. return new JsonResponse('Please login..');
  365. }
  366. $clinic = $this->getUser()->getClinic();
  367. $copy = $request->request->get('copy');
  368. $method = $request->request->get('method');
  369. $clinic->$method($copy);
  370. $this->em->persist($clinic);
  371. $this->em->flush();
  372. $response['flash'] = '<b><i class="fa-solid fa-circle-check"></i></i></b> Successfully saved.<div class="flash-close"><i class="fa-solid fa-xmark"></i></div>';
  373. $response['isAuthenticated'] = true;
  374. return new JsonResponse($response);
  375. }
  376. #[Route('/admin/get/clinics-list', name: 'get_clinics_list')]
  377. public function getClinicsList(Request $request): Response
  378. {
  379. $isApproved = $request->request->get('status') ?? 1;
  380. $searchString = $request->request->get('search-string') ?? '';
  381. $pageId = $request->request->get('page-id') ?? 1;
  382. $clinics = $this->em->getRepository(Clinics::class)->adminFindAll($isApproved, $searchString);
  383. $results = $this->pageManager->paginate($clinics[0], $request, self::ITEMS_PER_PAGE, $pageId);
  384. $dataAction = 'data-action="click->admin--clinics#onClickGetList"';
  385. $pagination = $this->getPagination($pageId, $results, $dataAction, self::ITEMS_PER_PAGE);
  386. $isStatusChange = $request->request->get('is-status-change') ?? 0;
  387. $html = $this->render('Admin/clinics/clinics_list.html.twig', [
  388. 'clinics' => $results,
  389. 'pagination' => $pagination,
  390. 'isStatusChange' => $isStatusChange,
  391. ])->getContent();
  392. return new JsonResponse($html);
  393. }
  394. #[Route('/admin/get/clinic-form', name: 'get_clinic_form')]
  395. public function getClinicForm(Request $request): Response
  396. {
  397. $clinicId = $request->request->get('clinic-id') ?? 0;
  398. $clinic = $this->em->getRepository(Clinics::class)->find($clinicId);
  399. $clinicUsers = $this->em->getRepository(ClinicUsers::class)->findBy([
  400. 'clinic' => $clinicId,
  401. 'isApproved' => true
  402. ]);
  403. $userPermissions = $this->em->getRepository(UserPermissions::class)->findBy([
  404. 'isClinic' => 1
  405. ]);
  406. if($clinic == null){
  407. $clinic = new Clinics();
  408. }
  409. $html = $this->render('Admin/clinics/clinics.html.twig',[
  410. 'clinic' => $clinic,
  411. 'clinicUsers' => $clinicUsers,
  412. 'userPermissions' => $userPermissions
  413. ])->getContent();
  414. return new JsonResponse($html);
  415. }
  416. private function generatePassword()
  417. {
  418. $sets = [];
  419. $sets[] = 'abcdefghjkmnpqrstuvwxyz';
  420. $sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ';
  421. $sets[] = '23456789';
  422. $sets[] = '!@$%*?';
  423. $all = '';
  424. $password = '';
  425. foreach ($sets as $set) {
  426. $password .= $set[array_rand(str_split($set))];
  427. $all .= $set;
  428. }
  429. $all = str_split($all);
  430. for ($i = 0; $i < 16 - count($sets); $i++) {
  431. $password .= $all[array_rand($all)];
  432. }
  433. $this->plainPassword = str_shuffle($password);
  434. return $this->plainPassword;
  435. }
  436. #[Route('/clinics/error', name: 'clinic_error_500')]
  437. public function clinic500ErrorAction(Request $request): Response
  438. {
  439. $username = $this->getUser();
  440. $id = '';
  441. if($username != null) {
  442. $id = $this->getUser()->getClinic()->getId();
  443. }
  444. return $this->render('bundles/TwigBundle/Exception/error500.html.twig', [
  445. 'type' => 'clinics',
  446. 'id' => $id,
  447. ]);
  448. }
  449. #[Route('/admin/submit/clinic/crud', name: 'admin_submit_clinic_crud')]
  450. public function submitClinicCrud(Request $request): Response
  451. {
  452. $data = $request->request;
  453. $clinicId = $request->get('clinic-id') ?? $data->get('delete');
  454. $clinic = $this->em->getRepository(Clinics::class)->find($clinicId);
  455. $response['clinicUsers'] = $this->em->getRepository(ClinicUsers::class)->findBy([
  456. 'clinic' => $clinicId,
  457. ]);
  458. if($data->get('delete') != null)
  459. {
  460. $response = $this->deleteUser($data->get('delete'));
  461. return new JsonResponse($response);
  462. }
  463. $response['flash'] = '';
  464. if(!empty($data))
  465. {
  466. // Clinic Details
  467. $this->saveClinic($data, $clinic);
  468. // Clinic Users
  469. $this->saveClinicUsers($data, $clinic);
  470. $response['flash'] = 'Clinic Successfully Updated.';
  471. $response['clinicName'] = $data->get('clinic_name');
  472. }
  473. return new JsonResponse($response);
  474. }
  475. public function deleteUser($userId): array
  476. {
  477. $user = $this->em->getRepository(ClinicUsers::class)->find($userId);
  478. $response['flash'] = 'User Not Found!';
  479. $response['type'] = 'danger';
  480. if($user != null)
  481. {
  482. $user->setIsApproved(false);
  483. $this->em->persist($user);
  484. $this->em->flush();
  485. $response['flash'] = 'User Successfully Deleted.';
  486. $response['type'] = 'success';
  487. }
  488. return $response;
  489. }
  490. public function saveClinic($data, Clinics $clinic)
  491. {
  492. $clinic->setIsApproved($data->get('is-approved'));
  493. $clinic->setClinicName($this->encryptor->encrypt($data->get('clinic_name')));
  494. $clinic->setEmail($this->encryptor->encrypt($data->get('email')));
  495. $clinic->setTelephone($this->encryptor->encrypt($data->get('telephone')));
  496. $clinic->setManagerFirstName($this->encryptor->encrypt($data->get('manager-first-name')));
  497. $clinic->setManagerLastName($this->encryptor->encrypt($data->get('manager-last-name')));
  498. $clinic->setManagerIdNo($this->encryptor->encrypt($data->get('manager-id-no')));
  499. $clinic->setManagerIdExpDate(new \DateTime($data->get('manager-id-exp-date')));
  500. $this->em->persist($clinic);
  501. $this->em->flush();
  502. }
  503. public function saveClinicUsers($data, $clinic)
  504. {
  505. if(count($data->all('user_id')) > 0)
  506. {
  507. // Loop users
  508. for($i = 0; $i < count($data->all('user_id')); $i++)
  509. {
  510. $userId = $data->all('user_id')[$i];
  511. // Save user
  512. $clinicUser = $this->saveUser($data, $i, $userId);
  513. // User Permissions
  514. $userPermissions = $this->em->getRepository(ClinicUserPermissions::class)->findBy([
  515. 'user' => $userId
  516. ]);
  517. // Remove currently saved
  518. $this->deleteUserPermissions($userPermissions);
  519. // Save new permissions
  520. $this->createUserPermissions($data, $clinic, $clinicUser);
  521. }
  522. $this->em->flush();
  523. }
  524. }
  525. public function saveUser($data, $i, $userId): object
  526. {
  527. $firstName = $data->all('user_first_name')[$i];
  528. $lastName = $data->all('user_last_name')[$i];
  529. $userEmail = $data->all('user_email')[$i];
  530. $userTelephone = $data->all('user_telephone')[$i];
  531. $clinicUser = $this->em->getRepository(ClinicUsers::class)->find($userId);
  532. $clinicUser->setFirstName($this->encryptor->encrypt($firstName));
  533. $clinicUser->setLastName($this->encryptor->encrypt($lastName));
  534. $clinicUser->setEmail($this->encryptor->encrypt($userEmail));
  535. $clinicUser->setTelephone($this->encryptor->encrypt($userTelephone));
  536. $this->em->persist($clinicUser);
  537. $this->em->flush();
  538. return $clinicUser;
  539. }
  540. public function deleteUserPermissions($userPermissions)
  541. {
  542. foreach($userPermissions as $userPermission)
  543. {
  544. $this->em->remove($userPermission);
  545. }
  546. $this->em->flush();
  547. }
  548. public function createUserPermissions($data, $clinic, $clinicUsers)
  549. {
  550. if($data->all('user_permissions') != null)
  551. {
  552. foreach ($data->all('user_permissions') as $permissionId)
  553. {
  554. $pieces = explode('_', $permissionId);
  555. if ($pieces[1] == $clinicUsers->getId())
  556. {
  557. $userPermission = new ClinicUserPermissions();
  558. $permission = $this->em->getRepository(UserPermissions::class)->find($permissionId);
  559. $userPermission->setPermission($permission);
  560. $userPermission->setClinic($clinic);
  561. $userPermission->setUser($clinicUsers);
  562. $this->em->persist($userPermission);
  563. }
  564. }
  565. $this->em->flush();
  566. }
  567. }
  568. public function getPagination($currentPage, $results, $dataAction = '', $itemsPerPage = 10): string
  569. {
  570. return $this->render('pagination.html.twig', [
  571. 'currentPage' => $currentPage,
  572. 'results' => $results,
  573. 'dataAction' => $dataAction,
  574. 'itemsPerPage' => $itemsPerPage,
  575. 'lastPage' => $this->pageManager->lastPage($results),
  576. 'totalPages' => ceil(count($results) / $itemsPerPage),
  577. 'i' => max(1, $currentPage - 5),
  578. 'forLimit' => min($currentPage + 5, ceil(count($results) / $itemsPerPage)),
  579. ])->getContent();
  580. }
  581. }