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