src/Controller/DefaultController.php line 75

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. #use Symfony\Component\HTTPFoundation\Response;
  4. #use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use App\Entity\DialogueAccessLog;
  9. use App\Entity\DialogueNotes;
  10. use App\Entity\Patient;
  11. use App\Entity\Dialogue;
  12. use App\Entity\User;
  13. use App\Entity\Family;
  14. use App\Entity\PredefinedCaseCard;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use App\Form\DialogueCaseCardType;
  17. use App\Entity\DialogueCaseCard;
  18. use App\Entity\PatientInformation;
  19. use App\Entity\PatientInformationDetails;
  20. use App\Entity\PredefinedAttachmentType;
  21. use App\Entity\DialogueAttachmentDetails;
  22. use App\Entity\DialogueAttachments;
  23. use App\Entity\DialogueCasecardMeasure;
  24. use App\Entity\DialogueConsentInfo;
  25. use App\Entity\PredefinedTemplate;
  26. use App\Entity\TravelNeedsDetails;
  27. use App\Entity\Category;
  28. use App\Entity\DialogueCaseCardHistory;
  29. use App\Entity\JoGroup;
  30. use App\Form\JoGroupType;
  31. use App\Entity\JoMasterInformation;
  32. use App\Entity\JoMasterInformationLocation;
  33. use App\Entity\DialogueMultipleAttachment;
  34. use App\Lib\SoapClientDebug;
  35. use App\Entity\PatientSibling;
  36. use App\Entity\JoCaseCardEvent;
  37. use Symfony\Component\HttpClient\HttpClient;
  38. use App\Entity\JoPostMail;
  39. use App\Entity\JoCaseCardHold;
  40. use App\Entity\JoGroupWaitinglist;
  41. use App\Entity\JoCaseComments;
  42. use App\Entity\JoCaseCommentsLog;
  43. use App\Entity\JoNotification;
  44. use App\Entity\JoNotificationLog;
  45. use App\Entity\JoActivitySharing;
  46. use App\Entity\JoActivitySharingParticipant;
  47. use App\Entity\JoParticipantNotification;
  48. use App\Entity\JoParticipantSharingActivity;
  49. use App\Entity\JoCaseMemos;
  50. use App\Entity\JoPatientIsdeceasedLog;
  51. use App\Entity\RbRental;
  52. use App\Entity\JoCaseCardEventBrevActivity;
  53. use App\Entity\User as Relative;
  54. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  55. use App\Entity\SepoTunnelliste;
  56. use App\Entity\IstElev;
  57. use App\Entity\IstElevUdv;
  58. use App\Entity\ScalingProgression;
  59. use App\Entity\ScalingGraph;
  60. use App\Entity\CaseCardMeasure;
  61. use App\Entity\JoActivityTemplate;
  62. use App\Entity\PredefinedTravelsType;
  63. use App\Entity\UserCaseLogger;
  64. use App\Entity\UserCaseCardLogger;
  65. use App\Entity\UserCaseActivityLogger;
  66. use App\Entity\SkebelonEbookLog;
  67. use App\Entity\StilInstitution;
  68. use App\Entity\StilPerson;
  69. class DefaultController extends AbstractController {
  70.     public function index(Request $request) {
  71.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  72.         $em $this->getDoctrine()->getManager();
  73.         $session $request->getSession();
  74.         ini_set('memory_limit''-1');
  75.         if($this->get('security.authorization_checker')->isGranted('ROLE_PARENT')) {
  76.             $session->set("isCitizenLogin"true);
  77.             return $this->redirect($this->generateUrl('parentIndex'));
  78.         } else {
  79.             $session->set("isCitizenLogin"false);
  80.         }
  81.         $selectedPatient $session->get("selectedPatient"null);
  82.         $selectedDialogue $session->get("selectedDialogue"null);
  83.         $isCprLookupActive $this->container->getParameter('isCprLookupActive');
  84.         $pagelimit $this->container->getParameter('pageResultLimit');
  85.         $isTestServer $this->container->getParameter('isTestServer');
  86.         $session->set("isTestServer"$isTestServer);
  87.         $isJoGroupExist $session->get("isJoGroupExist"null);
  88.         $selectedJoGroup $session->get("selectedJoGroup"null);
  89.         $session->set('waitingListCount',null);
  90.         $session->set('postMailCnt',null);
  91.         $showRapportUrl $this->container->getParameter('showRapportUrl');
  92.         $session->set('showRapportUrl'$showRapportUrl);
  93.         $isCopenhagen $this->container->getParameter('isCopenhagen');
  94.         $session->set('isCopenhagen'$isCopenhagen);
  95.         $session->set("komunneName"null);
  96.         $session->set("komunneId",null);
  97.         $session->set('rentalItemCnt',null);
  98.         $isTestServer $this->container->getParameter('isTestServer');
  99.         
  100.         
  101.         $this->checkUserAgent($request$session);
  102.         $templateVersion $session->get('templateVersion');
  103.         /*if($templateVersion == "mobile" && $isCopenhagen == "0") {
  104.             return $this->render('site/maintenance.html.twig', array(
  105.             ));
  106.         }*/
  107.         
  108.         if ($selectedDialogue) {
  109.             $selectedDialogue $em->getRepository(Dialogue::class)->find($selectedDialogue);
  110.             if ($selectedDialogue) {
  111.                 $selectedPatient $em->getRepository(Patient::class)->find($selectedDialogue->getPatient()->getId());
  112.             }
  113.         }
  114.         
  115.         if ($isJoGroupExist) {
  116.             $selectedJoGroup $em->getRepository(JoGroup::class)->find($selectedJoGroup);
  117.         }
  118.         $isDialogueExist $session->get("isDialogueExist"false);
  119.         $session->set("isDialogueExist"false);
  120.         $session->set("selectedPatient"null);
  121.         $session->set("selectedDialogue"null);
  122.         $session->set("isJoGroupExist"false);
  123.         $session->set("selectedJoGroup"null);
  124.         $user $this->get('security.token_storage')->getToken()->getUser();
  125.         $isTestUser $user->getIsTestUser();
  126.         $isDummyPatient $isTestUser 0;
  127.         $loginUserCat $user->getCategory()->getName();
  128.         
  129.         //$loginUserInstitutions 
  130.         /*$loginUserInstitutionsArray = $em->createQuery("SELECT  distinct (sp.institutionId)  FROM App\Entity\StilPerson sp                  
  131.                    left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser 
  132.                    WHERE ac.user =".$user->getId() )
  133.                 ->getScalarResult();
  134.         $loginUserInstitutions = array_map('current', $loginUserInstitutionsArray);
  135.         if(count($loginUserInstitutions) == 0){
  136.             $loginUserInstitutions[] = 0;
  137.         }*/ 
  138.         $loginUserInstitutions $this->loginUserInstitutions($em$user);
  139.         $currentSelectedInstitution $session->get('selectedInstitutionId') ? $session->get('selectedInstitutionId') : $loginUserInstitutions[0];
  140.         $loginUserGroups $this->loginUserGroups($em$user);
  141.         //echo $loginUserGroups;die;
  142.         
  143.         //fetch dialogues of matching user role i.e  dialogut_type 1->csv   : 2->
  144.         $dialogueType $user->hasRole('ROLE_CSV') ? : ($user->hasRole('ROLE_DTS') ? 0);
  145.         $userRoleTypeText $user->hasRole('ROLE_CSV') ? 'ROLE_CSV' : ($user->hasRole('ROLE_DTS') ? 'ROLE_DTS' 0);
  146.         $indexSearch trim($request->get('indexSearch'));
  147.         $sortBy trim($request->get('sortBy'));
  148.         $orderBy trim($request->get('orderBy'));
  149.         $listType trim($request->get('listType'));
  150.         $searchTerm trim($request->get('searchTxt'));
  151.         $indexCaseCardIds trim($request->get('indexCaseCardIds'));
  152.         $indexAreaIds trim($request->get('indexAreaIds'));
  153.         $indexStatusIds trim($request->get('indexStatusIds'));
  154.         $indexFilterAdUserId trim($request->get('indexFilterAdUserId'));
  155.         $indexSchoolIds trim($request->get('indexSchoolIds'));
  156.         $indexInstIds trim($request->get('indexInstIds'));
  157.         $indexdocumentIds trim($request->get('indexdocumentIds'));
  158.         $isResultWithoutFilter false;
  159.         if($searchTerm !="" || $indexAreaIds !="" || $indexStatusIds !="" || $indexFilterAdUserId != "" || $indexSchoolIds !="" || $indexInstIds !="") {
  160.             $isResultWithoutFilter true;
  161.         }
  162.          if($searchTerm =="" && $indexAreaIds =="" && $indexStatusIds =="" && $indexFilterAdUserId == "" && $indexSchoolIds =="" && $indexInstIds =="") {
  163.             $pagelimit $this->container->getParameter('pageResultLimit');
  164.         }
  165.         if ($request->isXmlHttpRequest()) {
  166.             $pagelimit NULL;
  167.             if($searchTerm =="" && $indexAreaIds =="" && $indexStatusIds =="" && $indexFilterAdUserId == "" && $indexSchoolIds =="" && $indexInstIds =="") {
  168.                 $pagelimit $this->container->getParameter('pageResultLimit');
  169.             }
  170.         }
  171.         if($indexCaseCardIds == ""){
  172.             $isResultWithoutFilter false;
  173.         }
  174.         
  175.             //$fetchAllDialogues = $em->getRepository(Dialogue::class)->findBy(array('deleted' => false, 'status' => 1, 'dialogueType' => $dialogueType));           
  176.             if (strlen($searchTerm) > && $searchTerm[6] == '-') {//when search by cpr number and 7th char is - then replace it and pass the search string
  177.                 $searchTerm str_replace('-'''$searchTerm);
  178.             } else {
  179.                 $searchTerm $searchTerm;
  180.             }
  181.             if ($request->isXmlHttpRequest()) {
  182.                 //No need to reset the paramenter array while doing ajax call
  183.             } else {
  184.                 $parameters = [];
  185.             }
  186.             $parameters['dialogueType'] = $dialogueType;
  187.             $instiId $session->get('institutionId');
  188.           
  189.             $searchSqlStr "SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d                   
  190.                    left join App\Entity\Patient p with p.id = d.patient 
  191.                    left join App\Entity\User u with u.id = p.user
  192.                    left join App\Entity\DialogueCaseCard dc with d.id = dc.dialogue
  193.                    left join App\Entity\DialogueCaseCardMeasure dcm with dc.id = dcm.DialogueCaseCard
  194.                    left join App\Entity\User a with a.id = d.anchor 
  195.                    left join App\Entity\User ar with ar.id = dc.createdBy 
  196.                    left join App\Entity\User arm with arm.id = dcm.responsiblePerson
  197.                    left join App\Entity\PatientInformation pi with p.id = pi.patient
  198.                    left join App\Entity\Category c with a.category = c.id
  199.                    left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  200.                    left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  201.                    WHERE d.deleted = false and d.status = 1 and d.dialogueType= :dialogueType  and p.isDummyPatient = ".$isDummyPatient." and sp.institutionId in (".$currentSelectedInstitution.")";
  202.             
  203.             if (strlen($indexCaseCardIds) > 0) {
  204.                 $searchSqlStr $searchSqlStr " and (dc.pCaseCardId in (:caseCardId) ) ";
  205.                 $parameters['caseCardId'] = explode(","$indexCaseCardIds);
  206.             }
  207.             if (strlen($searchTerm) > 0) {
  208.                 $searchSqlStr $searchSqlStr " and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText or u.fullName  LIKE :searchText) ";
  209.                 $parameters['searchText'] = '%' $searchTerm '%';
  210.             }
  211.             if (strlen($indexAreaIds) > 0) {
  212.                 if($user->hasRole('ROLE_CSV')){
  213.                     if($indexAreaIds == 'Børnecenter København'){
  214.                         $searchSqlStr $searchSqlStr " and (c.name LIKE :areaTxt) ";
  215.                         $parameters['areaTxt'] = '%' $indexAreaIds '%';
  216.                     }else{
  217.                         $areaName explode(',',$indexAreaIds);
  218.                         $i 0;
  219.                         foreach($areaName as $area){
  220.                             if($i == 0){
  221.                                 $searchSqlStr $searchSqlStr " and ( ";
  222.                                 $searchSqlStr $searchSqlStr " (a.area LIKE :areaTxt) ";
  223.                             }else{
  224.                                 $searchSqlStr $searchSqlStr " OR (a.area LIKE :areaTxt) ";
  225.                             }
  226.                             $i++;
  227.                             $parameters['areaTxt'] = '%' $area '%';
  228.                         }
  229.                         $searchSqlStr $searchSqlStr " )";
  230.     //                    $searchSqlStr = $searchSqlStr . " and (a.area LIKE :areaTxt) ";
  231.                     }
  232.                 }else{
  233.                     if($indexAreaIds == 'Børnecenter København'){
  234.                         $searchSqlStr $searchSqlStr " and (c.name LIKE :areaTxt) ";
  235.                         $parameters['areaTxt'] = '%' $indexAreaIds '%';
  236.                     }else{
  237.                         $areaName explode(',',$indexAreaIds);
  238.                         $i 0;
  239.                         foreach($areaName as $area){
  240.                             if($i == 0){
  241.                                 //$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  242.                                 $searchSqlStr $searchSqlStr " and ( ";
  243.                                 $searchSqlStr $searchSqlStr " (d.dialogueArea LIKE :areaTxt_$i) ";
  244.                             }else{
  245.                                 //$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  246.                                 $searchSqlStr $searchSqlStr " OR ( d.dialogueArea LIKE :areaTxt_$i) ";
  247.                             }
  248.                             $parameters["areaTxt_$i"] = '%' $area '%';
  249.                             $i++;
  250.                         }
  251.                         $searchSqlStr $searchSqlStr " )";
  252.     //                    $searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt) ";
  253.                     }
  254.                 }
  255.             }
  256.             if (strlen($indexSchoolIds) > 0) {
  257. //                $searchSqlStr = $searchSqlStr . " and (pi.citizenSchoolName LIKE :schoolText) ";
  258. //                $parameters['schoolText'] = '%' . $indexSchoolIds . '%';
  259.                 $schoolName explode(',',$indexSchoolIds);
  260.                 $i 0;
  261.                 foreach($schoolName as $school){
  262.                     if($i == 0){
  263.                         //$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  264.                         $searchSqlStr $searchSqlStr " and (pi.citizenSchoolName LIKE :schoolText_$i) ";
  265.                     }else{
  266.                         //$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  267.                         $searchSqlStr $searchSqlStr " OR ( pi.citizenSchoolName LIKE :schoolText_$i) ";
  268.                     }
  269.                     $parameters["schoolText_$i"] = '%' $school '%';
  270.                     $i++;
  271.                 }
  272.             }
  273. //            if (strlen($indexInstIds) > 0) {
  274. //                $searchSqlStr = $searchSqlStr . " and (pi.citizenInstitutionName LIKE :instText) and pi.citizenInstitutionToDate IS NULL";
  275. //                $parameters['instText'] = '%' . $indexInstIds . '%';
  276. //            }
  277.             if (strlen($indexInstIds) > 0) {
  278.                 $InstIds explode(','$indexInstIds);
  279.                 $searchSqlStr $searchSqlStr ." and (";
  280.                 $count 0;
  281.                 if( count($InstIds) > 0) {
  282.                     unset($parameters['instText']);;
  283.                 }
  284.                 foreach($InstIds as $InstId){
  285.                     //echo "*".$count.$InstId."*";
  286.                     if($count){
  287.                         $searchSqlStr $searchSqlStr " or ";
  288.                     }
  289.                     $searchSqlStr $searchSqlStr " (pi.citizenInstitutionName LIKE :instText_$count) ";
  290.                     $parameters["instText_$count"] = '%' $InstId '%';
  291.                     $count++;
  292.                     
  293.                 }
  294.                 $searchSqlStr $searchSqlStr ." ) and pi.citizenInstitutionToDate IS NULL";
  295.             }
  296.             if (strlen($indexdocumentIds) > 0) {
  297. //                $searchSqlStr = $searchSqlStr . " and (dad.templateHeading LIKE :templateName)";
  298. //                $parameters['templateName'] = '%' . $indexdocumentIds . '%';
  299.                 
  300.                 $documentName explode(',',$indexdocumentIds);
  301.                 $i 0;
  302.                 foreach($documentName as $document){
  303.                     if($i == 0){
  304.                         //$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  305.                         $searchSqlStr $searchSqlStr " and (dad.templateHeading LIKE :templateName_$i) ";
  306.                         $searchSqlStr $searchSqlStr " and dad.activityType < 5 ";
  307.                     }else{
  308.                         //$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  309.                         $searchSqlStr $searchSqlStr " OR ( dad.templateHeading LIKE :templateName_$i) ";
  310.                         $searchSqlStr $searchSqlStr " and dad.activityType < 5 ";
  311.                     }
  312.                     $parameters["templateName_$i"] = '%' $document '%';
  313.                     $i++;
  314.                 }
  315.             }
  316.             if (strlen($indexStatusIds) > 0) {
  317.                 $isDraftTempArray explode(","$indexStatusIds);
  318.                 //if (in_array(0, $isDraftTempArray) && (in_array(1, $isDraftTempArray)) && (in_array(2, $isDraftTempArray))) {
  319.                     if (in_array(0$isDraftTempArray)) {
  320.                     //$searchSqlStr = $searchSqlStr . " and dc.toDate IS NULL OR dc.toDate IS NOT NULL ";
  321.                     $searchSqlStr $searchSqlStr " and (dc.isClosed = false OR dc.isClosed = true) ";
  322.                     //$qb->andWhere('dc.toDate IS NULL OR dc.toDate IS NOT NULL');
  323.                 //} else if (in_array(1, $isDraftTempArray) && (!in_array(2, $isDraftTempArray))) {
  324.                 } else if (in_array(1$isDraftTempArray)) {
  325.                     //$searchSqlStr = $searchSqlStr . " and dc.toDate IS NULL ";
  326.                     $searchSqlStr $searchSqlStr " and dc.isClosed = false ";
  327.                     //$qb->andWhere('dc.toDate IS NULL');
  328.                 //} else if (in_array(2, $isDraftTempArray) && (!in_array(1, $isDraftTempArray))) {
  329.                 } else if (in_array(2$isDraftTempArray)) {
  330.                     //$searchSqlStr = $searchSqlStr . " and dc.toDate IS NOT NULL ";
  331.                     $searchSqlStr str_replace(" AND dc.toDate IS NULL "" "$searchSqlStr);
  332.                     $searchSqlStr $searchSqlStr " and dc.isClosed = true ";
  333.                     //$qb->andWhere('dc.toDate IS NOT NULL');
  334.                 }
  335.             }
  336.             if(strlen($indexFilterAdUserId)) {
  337.                  if($user->hasRole('ROLE_CSV')){
  338.                     $searchSqlStr $searchSqlStr " and dcm.responsiblePerson    = :indexFilterAdUserId ";
  339.                     $parameters['indexFilterAdUserId'] = '' $indexFilterAdUserId '';
  340.                 }else{
  341.                      $searchSqlStr $searchSqlStr " and (dcm.responsiblePerson    = :indexFilterAdUserId  or dc.createdBy    = :indexFilterAdUserId)";
  342.                     $parameters['indexFilterAdUserId'] = '' $indexFilterAdUserId '';
  343.                 }
  344.             }
  345.             $searchSqlStr $searchSqlStr " order by d.latestGrade desc";
  346.             //if(($user->getIsTestUser() == "1" || $isTestServer == "1" || count($parameters) > 1) || ($indexSearch != '') ) { //Do not display “Alle sager” in overview.(5th list)
  347.             //echo $dialogueType." ".$searchSqlStr;
  348.             $fetchAllDialogues $em->createQuery($searchSqlStr)
  349.                     ->setParameters($parameters//send multiple paramenters
  350.                     //->setMaxResults($pagelimit)
  351.                     ->execute();
  352.             /*}else{
  353.                 $fetchAllDialogues = array();
  354.             }*/
  355.             
  356.         if ($request->isXmlHttpRequest()) {
  357.             //No need to reset the paramenter array while doing ajax call
  358.         } else {
  359.             $parameters = [];
  360.         }
  361.         $parameters['dialogueType'] = $dialogueType;
  362.             $searchSqlStr "SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d                   
  363.                    left join App\Entity\Patient p with p.id = d.patient 
  364.                    left join App\Entity\User u with u.id = p.user
  365.                    left join App\Entity\DialogueCaseCard dc with d.id = dc.dialogue
  366.                    left join App\Entity\DialogueCaseCardMeasure dcm with dc.id = dcm.DialogueCaseCard
  367.                    left join App\Entity\User a with a.id = d.anchor 
  368.                    left join App\Entity\User ar with ar.id = dc.createdBy 
  369.                    left join App\Entity\User arm with arm.id = dcm.responsiblePerson
  370.                    left join App\Entity\PatientInformation pi with p.id = pi.patient
  371.                    left join App\Entity\Category c with a.category = c.id
  372.                    left join App\Entity\DialogueAttachmentDetails dad with dad.dialogue = d.id
  373.                    left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  374.                    left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  375.                    WHERE d.deleted = false and d.status = 1 and d.dialogueType= :dialogueType  and p.isDummyPatient = ".$isDummyPatient." and sp.institutionId in (".$currentSelectedInstitution.")";
  376.             
  377.         if ($request->isXmlHttpRequest()) {
  378.             if (strlen($indexCaseCardIds) > 0) {
  379.                 $searchSqlStr $searchSqlStr " and (dc.pCaseCardId in (:caseCardId) ) ";
  380.                 $parameters['caseCardId'] = explode(","$indexCaseCardIds);
  381.             }
  382.             if (strlen($searchTerm) > 0) {
  383.                 $searchSqlStr $searchSqlStr " and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText or u.fullName  LIKE :searchText) ";
  384.                 $parameters['searchText'] = '%' $searchTerm '%';
  385.             }
  386.             if (strlen($indexAreaIds) > 0) {
  387.                 /*if($indexAreaIds == 'Børnecenter København'){
  388.                     $searchSqlStr = $searchSqlStr . " and (c.name LIKE :areaTxt) ";
  389.                     $parameters['areaTxt'] = '%' . $indexAreaIds . '%';
  390.                 }else{
  391.                     $searchSqlStr = $searchSqlStr . " and (a.area LIKE :areaTxt) ";
  392.                     $parameters['areaTxt'] = '%' . $indexAreaIds . '%';
  393.                 }*/
  394.                 if($user->hasRole('ROLE_CSV')){
  395.                     if($indexAreaIds == 'Børnecenter København'){
  396.                         $searchSqlStr $searchSqlStr " and (c.name LIKE :areaTxt) ";
  397.                         $parameters['areaTxt'] = '%' $indexAreaIds '%';
  398.                     }else{
  399.                         $areaName explode(',',$indexAreaIds);
  400.                         $i 0;
  401.                         foreach($areaName as $area){
  402.                             if($i == 0){
  403.                                 $searchSqlStr $searchSqlStr " and ( ";
  404.                                 $searchSqlStr $searchSqlStr " (a.area LIKE :areaTxt) ";
  405.                             }else{
  406.                                 $searchSqlStr $searchSqlStr " OR (a.area LIKE :areaTxt) ";
  407.                             }
  408.                             $i++;
  409.                             $parameters['areaTxt'] = '%' $area '%';
  410.                         }
  411.                         $searchSqlStr $searchSqlStr " )";
  412.     //                    $searchSqlStr = $searchSqlStr . " and (a.area LIKE :areaTxt) ";
  413.                     }
  414.                 }else{
  415.                     if($indexAreaIds == 'Børnecenter København'){
  416.                         $searchSqlStr $searchSqlStr " and (c.name LIKE :areaTxt) ";
  417.                         $parameters['areaTxt'] = '%' $indexAreaIds '%';
  418.                     }else{
  419.                         $areaName explode(',',$indexAreaIds);
  420.                         $i 0;
  421.                         foreach($areaName as $area){
  422.                             if($i == 0){
  423.                                 //$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  424.                                 $searchSqlStr $searchSqlStr " and ( ";
  425.                                 $searchSqlStr $searchSqlStr " (d.dialogueArea LIKE :areaTxt_$i) ";
  426.                             }else{
  427.                                 //$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  428.                                 $searchSqlStr $searchSqlStr " OR (d.dialogueArea LIKE :areaTxt_$i) ";
  429.                             }
  430.                             $parameters["areaTxt_$i"] = '%' $area '%';
  431.                             $i++;
  432.                         }
  433.                         $searchSqlStr $searchSqlStr " )";
  434.     //                    $searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt) ";
  435.                     }
  436.                 }
  437.             }
  438.             
  439.             if(strlen($indexFilterAdUserId)) {
  440.                 //$searchSqlStr = $searchSqlStr . " and d.anchor = :indexFilterAdUserId ";
  441.                 if($user->hasRole('ROLE_CSV')){
  442.                     $searchSqlStr $searchSqlStr " and dcm.responsiblePerson    = :indexFilterAdUserId ";
  443.                     $parameters['indexFilterAdUserId'] = '' $indexFilterAdUserId '';
  444.                 }else{
  445.                      $searchSqlStr $searchSqlStr " and (dcm.responsiblePerson    = :indexFilterAdUserId  or dc.createdBy    = :indexFilterAdUserId)";
  446.                     $parameters['indexFilterAdUserId'] = '' $indexFilterAdUserId '';
  447.                 }
  448.             }
  449.             
  450.             if (strlen($indexSchoolIds) > 0) {
  451. //                $searchSqlStr = $searchSqlStr . " and (pi.citizenSchoolName LIKE :schoolText) ";
  452. //                $parameters['schoolText'] = '%' . $indexSchoolIds . '%';
  453.                 $schoolName explode(',',$indexSchoolIds);
  454.                 $i 0;
  455.                 foreach($schoolName as $school){
  456.                     if($i == 0){
  457.                         //$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  458.                         $searchSqlStr $searchSqlStr " and (pi.citizenSchoolName LIKE :schoolText_$i) ";
  459.                     }else{
  460.                         //$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  461.                         $searchSqlStr $searchSqlStr " OR ( pi.citizenSchoolName LIKE :schoolText_$i) ";
  462.                     }
  463.                     $parameters["schoolText_$i"] = '%' $school '%';
  464.                     $i++;
  465.                 }
  466.             }
  467.            /* if (strlen($indexInstIds) > 0) {
  468.                 $searchSqlStr = $searchSqlStr . " and (pi.citizenInstitutionName LIKE :instText) and pi.citizenInstitutionToDate IS NULL";
  469.                 $parameters['instText'] = '%' . $indexInstIds . '%';
  470.             }*/
  471.             if (strlen($indexInstIds) > 0) {
  472.                 $InstIds explode(','$indexInstIds);
  473.                 $searchSqlStr $searchSqlStr ." and (";
  474.                 $count 0;
  475.                 if( count($InstIds) > 0) {
  476.                     unset($parameters['instText']);;
  477.                 }
  478.                 foreach($InstIds as $InstId){
  479.                     //echo "*".$count.$InstId."*";
  480.                     if($count){
  481.                         $searchSqlStr $searchSqlStr " or ";
  482.                     }
  483.                     $searchSqlStr $searchSqlStr " (pi.citizenInstitutionName LIKE :instText_$count) ";
  484.                     $parameters["instText_$count"] = '%' $InstId '%';
  485.                     $count++;
  486.                     
  487.                 }
  488.                 $searchSqlStr $searchSqlStr ." ) and pi.citizenInstitutionToDate IS NULL";
  489.             }
  490.             if (strlen($indexdocumentIds) > 0) {
  491. //                $searchSqlStr = $searchSqlStr . " and (dad.templateHeading LIKE :templateName)";
  492. //                $parameters['templateName'] = '%' . $indexdocumentIds . '%';
  493.                 $documentName explode(',',$indexdocumentIds);
  494.                 $i 0;
  495.                 foreach($documentName as $document){
  496.                     if($i == 0){
  497.                         //$searchSqlStr = $searchSqlStr . " and (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  498.                         $searchSqlStr $searchSqlStr " and (dad.templateHeading LIKE :templateName_$i) ";
  499.                         $searchSqlStr $searchSqlStr " and dad.activityType < 5 ";
  500.                     }else{
  501.                         //$searchSqlStr = $searchSqlStr . " OR (ar.area LIKE :areaTxt OR arm.area LIKE :areaTxt or d.dialogueArea LIKE :areaTxt) ";
  502.                         $searchSqlStr $searchSqlStr " OR ( dad.templateHeading LIKE :templateName_$i) ";
  503.                         $searchSqlStr $searchSqlStr " and dad.activityType < 5 ";
  504.                     }
  505.                     $parameters["templateName_$i"] = '%' $document '%';
  506.                     $i++;
  507.                 }
  508.             }
  509.             if (strlen($indexStatusIds) > 0) {
  510.                 $isDraftTempArray explode(","$indexStatusIds);
  511.                 //if (in_array(0, $isDraftTempArray) && (in_array(1, $isDraftTempArray)) && (in_array(2, $isDraftTempArray))) {
  512.                     if (in_array(0$isDraftTempArray)) {
  513.                     //$searchSqlStr = $searchSqlStr . " and dc.toDate IS NULL OR dc.toDate IS NOT NULL ";
  514.                     $searchSqlStr $searchSqlStr " and (dc.isClosed = false OR dc.isClosed = true) ";
  515.                     //$qb->andWhere('dc.toDate IS NULL OR dc.toDate IS NOT NULL');
  516.                 //} else if (in_array(1, $isDraftTempArray) && (!in_array(2, $isDraftTempArray))) {
  517.                 } else if (in_array(1$isDraftTempArray)) {
  518.                     //$searchSqlStr = $searchSqlStr . " and dc.toDate IS NULL ";
  519.                     $searchSqlStr $searchSqlStr " and dc.isClosed = false ";
  520.                     //$qb->andWhere('dc.toDate IS NULL');
  521.                 //} else if (in_array(2, $isDraftTempArray) && (!in_array(1, $isDraftTempArray))) {
  522.                 } else if (in_array(2$isDraftTempArray)) {
  523.                     //$searchSqlStr = $searchSqlStr . " and dc.toDate IS NOT NULL ";
  524.                     $searchSqlStr str_replace(" AND dc.toDate IS NULL "" "$searchSqlStr);
  525.                     $searchSqlStr $searchSqlStr " and dc.isClosed = true ";
  526.                     //$qb->andWhere('dc.toDate IS NOT NULL');
  527.                 }
  528.             }
  529.         }
  530.         
  531.         //if(($user->getIsTestUser() == "1" || $isTestServer == "1" || count($parameters) > 1) || ($indexSearch != '') ) { //Do not display “Alle sager” in overview.(5th list)
  532.         $fetchAllDialoguesAll $em->createQuery($searchSqlStr)
  533.                     ->setParameters($parameters//send multiple paramenters
  534.                     //->setMaxResults($pagelimit)
  535.                     ->execute();
  536.         /*}else{
  537.             $fetchAllDialoguesAll = array();
  538.         }*/
  539.                     $predefinedTemplateAll $em->createQuery('SELECT pt FROM  App\Entity\PredefinedTemplate pt
  540.                         WHERE pt.parentId NOT IN (0) and pt.userType = :userRoleTypeText')
  541.                         ->setParameter('userRoleTypeText'$userRoleTypeText)
  542.                         ->execute();
  543.                         foreach($predefinedTemplateAll as $key => $template){
  544.                             $predefinedTemplate[$key] = $template->getName();
  545.                         }
  546.         $documentsLinkForEachDialgue = array();
  547.         if (strlen($indexdocumentIds) > 0) {
  548.             $documentName explode(',',$indexdocumentIds);
  549.             foreach($fetchAllDialogues as $dialog){
  550.                 $dialogDOcuments $em->createQuery('SELECT dad FROM  App\Entity\DialogueAttachmentDetails dad
  551.                     WHERE dad.deletedBy IS NULL and dad.dialogue = :dialog and dad.pAtttachmentType = 7 and dad.templateHeading IN (:indexdocumentIds) and ((dad.isDraft = 1 and dad.visibleStatus = 1 and dad.user = :user) or (dad.isDraft = 1 and dad.visibleStatus = 0) or (dad.isDraft = 0)) ')
  552.                     //WHERE dad.deletedBy IS NULL and dad.dialogue = :dialog and dad.pAtttachmentType = 7 and dad.templateHeading IN (:indexdocumentIds) and (dad.visibleStatus = 0 or (dad.visibleStatus = 1 and dad.user = :user)) ')
  553.                     ->setParameter('dialog'$dialog)
  554.                     ->setParameter('user'$user)
  555.                     ->setParameter('indexdocumentIds'$documentName)
  556.                     ->execute();
  557.                 $dialogDocumentLinks '';
  558.                 foreach ($dialogDOcuments as $document){
  559.                     $link "<a href='therapist/load-dialogue/".$dialog->getId()."/".$document->getId()."' class='detail-view-link'><u>".$document->getTemplateHeading()."</u></a>, ";
  560.                     $dialogDocumentLinks $dialogDocumentLinks.$link;
  561.                 }
  562.                 $dialogDocumentLinks rtrim($dialogDocumentLinks', ');
  563.                 $documentsLinkForEachDialgue[$dialog->getId()] = $dialogDocumentLinks;
  564.             }
  565.         }
  566.         //var_dump($documentsLinkForEachDialgue);
  567.         // Fetch dialogues  where current user has created case_card or notes or measure (list 3)
  568.          if ($user->hasRole('ROLE_CSV')) {
  569.              $onlyMyDialogues $em->getRepository(Dialogue::class)->myActiveCases('ROLE_CSV'$searchTerm$user$dialogueType$pagelimit$isDummyPatient);
  570.         }else{
  571.             $onlyMyDialogues $em->getRepository(Dialogue::class)->myActiveCases('ROLE_DTS'$searchTerm$user$dialogueType$pagelimit$isDummyPatient);
  572.         }
  573.         
  574.         if ($user->hasRole('ROLE_CSV')) {
  575.             $onlyMyDialoguesRecords  $em->getRepository(Dialogue::class)->myActiveCases('ROLE_CSV'$searchTerm$user$dialogueType$pagelimit$isDummyPatient);
  576.         }else{
  577.             $onlyMyDialoguesRecords  $em->getRepository(Dialogue::class)->myActiveCases('ROLE_DTS'$searchTerm$user$dialogueType$pagelimit$isDummyPatient);
  578.         }
  579.         $onlyMyDialoguesCount count($onlyMyDialoguesRecords);
  580.         
  581.         
  582.         //(list 2)
  583.         
  584.             //DTS and CSV: The caes shown here should be the cases last accessed by the user logged in – not last accessed in general by all users.
  585.             /*$recentDialogues = $em->createQuery(
  586.                             'SELECT  d FROM App\Entity\Dialogue d   
  587.                         left join App\Entity\Patient p with p.id = d.patient 
  588.                         left join App\Entity\DialogueAccessLog c with c.dialogue = d.id
  589.                         WHERE c.dialogue = d and c.createdBy = :user and d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'  
  590.                         and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText)
  591.                         group by d.id order by max(c.id) desc'
  592.                     )
  593.                     ->setParameter('searchText', '%' . $searchTerm . '%')
  594.                     ->setParameter('user', $user)
  595.                     ->setParameter('dialogueType', $dialogueType)
  596.                     ->setMaxResults($pagelimit)
  597.                     ->execute();*/
  598.             $today = new \DateTime();
  599.             $before30days $today->modify('-30 day')->format('Y-m-d');
  600.             $recentDialogues $em->createQuery(
  601.                             'SELECT dal, MAX(dal.id) as id,  max(dal.createdAt) as accessed, sig.groupname as groupName FROM App\Entity\DialogueAccessLog  dal 
  602.                             LEFT JOIN App\Entity\Dialogue  d with dal.dialogue = d.id 
  603.                             LEFT JOIN App\Entity\Patient p with p.id = d.patient 
  604.                             left join App\Entity\PatientInformation pi with p.id = pi.patient
  605.                             left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  606.                    left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  607.                             WHERE dal.createdBy = :user AND d.deleted = false and d.status =1 and dal.createdAt >:before30days and d.dialogueType = :dialogueType  and (pi.citizenSchoolName LIKE :category or pi.citizenInstitutionName LIKE :category) and p.isDummyPatient = '.$isDummyPatient.'  and sp.institutionId in ('.$loginUserInstitutions[0].')
  608.                             GROUP BY dal.dialogue ORDER BY accessed desc'
  609.                     )
  610.                     ->setParameter('user'$user)
  611.                     ->setParameter('dialogueType'$dialogueType)
  612.                     ->setParameter('category'$loginUserCat)
  613.                     ->setParameter('before30days',$before30days)
  614.                     ->setMaxResults($pagelimit)
  615.                     ->execute();
  616.         //}
  617.         /*$recentDialoguesCount = $em->createQuery(
  618.                         'SELECT  d FROM App\Entity\Dialogue d   
  619.                     left join App\Entity\Patient p with p.id = d.patient 
  620.                     left join App\Entity\DialogueAccessLog c with c.dialogue = d.id  
  621.                     WHERE c.dialogue = d and c.createdBy = :user and d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'  
  622.                     and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText)
  623.                     group by d.id order by max(c.id) desc'
  624.                 )
  625.                 ->setParameter('searchText', '%' . $searchTerm . '%')
  626.                 ->setParameter('user', $user)
  627.                 ->setParameter('dialogueType', $dialogueType)
  628.                 ->execute();*/
  629.         $recentDialoguesCount $em->createQuery(
  630.                         'SELECT dal, MAX(dal.id) as id,  max(dal.createdAt) as accessed FROM App\Entity\DialogueAccessLog  dal 
  631.                             LEFT JOIN App\Entity\Dialogue  d with dal.dialogue = d.id 
  632.                             LEFT JOIN App\Entity\Patient p with p.id = d.patient
  633.                             left join App\Entity\PatientInformation pi with p.id = pi.patient
  634.                             left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  635.                             left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  636.                             WHERE dal.createdBy = :user AND d.deleted = false and d.status =1 and dal.createdAt >:before30days and d.dialogueType = :dialogueType  and (pi.citizenSchoolName LIKE :category or pi.citizenInstitutionName LIKE :category) and p.isDummyPatient = '.$isDummyPatient.'  and sp.institutionId in ('.$loginUserInstitutions[0].') 
  637.                             GROUP BY dal.dialogue ORDER BY accessed desc'
  638.                     )
  639.                     ->setParameter('user'$user)
  640.                     ->setParameter('dialogueType'$dialogueType)
  641.                     ->setParameter('category'$loginUserCat)
  642.                     ->setParameter('before30days',$before30days)
  643.                     ->execute();
  644.             //var_dump($recentDialoguesCount);die;
  645.         //$recentDialogues = $em->getRepository(Dialogue::class)->findBy(array('deleted' => false, 'status' => 1, 'dialogueType' => $dialogueType), array('updatedAt' => 'desc'), 10);
  646.         //Save post mails as reminder activity
  647.         $isSavedAsActivity false;
  648.         $postMailControllerObj = new PostMailController();
  649.         //foreach($fetchAllDialogues as $pDialogue) {
  650.         //foreach($fetchAllDialoguesAll as $pDialogue) {
  651.         //foreach($onlyMyDialogues as $pDialogue) {
  652.         foreach($recentDialoguesCount as $pDialogue) {
  653.             $dialogue $pDialogue[0]->getDialogue();
  654.             $patient $dialogue->getPatient();
  655.             $getNotSavedAsActivityPostMails $em->getRepository(JoPostMail::class)->getNotSavedAsActivityPostMails($isSavedAsActivity$dialogue);
  656.             $predefinedCaseCardObj $em->getRepository(PredefinedCaseCard::class)->getFirstPreCaseCardByUserType($userRoleTypeText);
  657.             $postMailControllerObj->createReminderActivityAsPostMail($request$em$user$predefinedCaseCardObj$patient$dialogue$getNotSavedAsActivityPostMails);
  658.         }
  659.         
  660.         $mailActivitiesDraft $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('pAtttachmentType' => '9','activityType' => '7''isPostMailActivity' => 1));
  661.         foreach ($mailActivitiesDraft as $activity){
  662.             if($activity->getJoPostMail() != null){
  663.                 if($activity->getUser()->getId() != $activity->getJoPostMail()->getSender()->getId()){
  664.                     $activity->setUser($activity->getJoPostMail()->getSender());
  665.                     $em->persist($activity);
  666.                     $em->flush();
  667.                 }
  668.             }
  669.         }
  670.         // get all my notes whose remider date is past today  (list 1)
  671.         
  672.             /* $notesPassedReminderDate = $em->createQuery('SELECT n from App\Entity\DialogueAttachmentDetails n where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate <= :cdate')->
  673.               setParameter('user', $user)->setParameter('cdate', date("Y-m-d"))->execute(); */
  674.             $notesPassedReminderDate $em->createQuery('
  675.                           SELECT n,po.isDeleted from App\Entity\DialogueAttachmentDetails n 
  676.                           left join App\Entity\Dialogue d with d.id = n.dialogue
  677.                           inner join App\Entity\Patient p with p.id = n.patient
  678.                           left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  679.                           where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0
  680.                          
  681.                           and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText) and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType group by n.id  HAVING (po.isDeleted = false or po.isDeleted is null) order by n.reminderDate asc')
  682.                     ->setParameter('searchText''%' $searchTerm '%')
  683.                     ->setParameter('user'$user)
  684.                     ->setParameter('dialogueType'$dialogueType)
  685.                     //->setParameter('cdate', date("Y-m-d"))
  686.                     ->setMaxResults($pagelimit)
  687.                     ->execute();
  688.         //}
  689.         $notesPassedReminderDateCount1 $em->createQuery('
  690.                           SELECT n.id,po.isDeleted from App\Entity\DialogueAttachmentDetails n 
  691.                           left join App\Entity\Dialogue d with d.id = n.dialogue
  692.                           inner join App\Entity\Patient p with p.id = n.patient 
  693.                           left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  694.                           where n.user = :user and n.pAtttachmentType <> 50  and n.reminderDate is not null and n.canTrash = 0
  695.                          
  696.                           and (p.firstName LIKE :searchText or p.lastName LIKE :searchText or p.cpr LIKE :searchText) and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType group by n.id HAVING (po.isDeleted = false or po.isDeleted is null)')
  697.                 ->setParameter('searchText''%' $searchTerm '%')
  698.                 ->setParameter('user'$user)
  699.                 ->setParameter('dialogueType'$dialogueType)
  700.                 //->setParameter('cdate', date("Y-m-d"))
  701.                 ->execute();
  702.         $notesPassedReminderDateCount count($notesPassedReminderDateCount1);
  703.         // Fetch dialogues created by other than logged in user or dialogues where current other than login user has created case_card or notes or attachment (list 4)
  704.         // $today = new \DateTime();
  705.         // $before30days = $today->modify('-30 day')->format('Y-m-d');
  706.     
  707.         $newContentDialogues =  $em->getRepository(DialogueAttachmentDetails::class)->newContentInMyActiveCases($searchTerm$user$before30days$onlyMyDialoguesRecords$dialogueType$pagelimit$isDummyPatient);
  708.         $newContentDialoguesCount1 =  $em->getRepository(DialogueAttachmentDetails::class)->newContentInMyActiveCases($searchTerm$user$before30days$onlyMyDialoguesRecords$dialogueType$pagelimit$isDummyPatient);
  709.         $newContentDialoguesCount = ($newContentDialoguesCount1[0][1]);
  710.         if ($orderBy == 'desc') {
  711.             $orderBy 'asc';
  712.         } else {
  713.             $orderBy 'desc';
  714.         }
  715.         $searchFilter "ROLE_DTS";
  716.         if ($user->hasRole('ROLE_CSV')) {
  717.             $searchFilter "ROLE_CSV";
  718.         }
  719.         /* for search functionality case card list */
  720.         $userCreatedCaseCardsId $userCreatedDialogueCaseCard = array();
  721.         $userCaseCardAll $em->getRepository(DialogueCaseCard::class)->findBy(array('createdBy' => $user));
  722.         foreach ($userCaseCardAll as $userCaseCard) {
  723.             $userCreatedCaseCardsId[] = $userCaseCard->getPCaseCardId()->getId();
  724.         }
  725.         $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForIndividual' => 1));
  726.         /* for search functionality area list */
  727.         $allDefaultUserAreas = array(array('id' => 1'area' => 'Amager'), array('id' => 2'area' => 'Nørrebro/Bispebjerg'), array('id' => 3'area' => 'Indre By/Østerbro'), array('id' => 4'area' => 'Brønshøj/Vanløse'), array('id' => 5'area' => 'Valby/Vesterbro/Kgs. Enghave'), array('id' => 6'area' => 'Børnecenter København'));
  728.         $allUserAreas $em->createQuery(
  729.                         'select u from App\Entity\User u where u.area is not null GROUP BY u.area'
  730.                 )->execute();
  731.         $userArea $em->getRepository(User::class)->findOneBy(array('id' => $user));
  732.         /* for search functionality school list and institute list */
  733.         //$allDefaultUserSchools = array(array('id' => 1, 'citizenSchoolName' => "Bjørn's International School", 'schoolarea' => 'Nørrebro/Bispebjerg' ), array('id' => 2, 'citizenSchoolName' => 'Blågård Skole', 'schoolarea' => 'Nørrebro/Bispebjerg'), array('id' => 3, 'citizenSchoolName' => 'Guldberg Skole', 'schoolarea' => 'Nørrebro/Bispebjerg'), array('id' => 4, 'citizenSchoolName' => 'Sortedamskolen', 'schoolarea' => 'Indre By/Østerbro'), array('id' => 5, 'citizenSchoolName' => 'Sølvgades Skole' , 'schoolarea' => 'Indre By/Østerbro'));
  734.         $toDate "'".date("Y-m-d")."'";
  735.         $month20Date "'".date("Y-m-d",strtotime("-14 month"))."'";
  736.         $allDefaultUserSchools$em->createQuery(
  737.                         "select pi from App\Entity\PatientInformation pi 
  738.                         left join App\Entity\Patient p with p.id = pi.patient
  739.                         inner join App\Entity\Dialogue d with p.id = d. patient
  740.                      where pi.citizenSchoolName is not null and p.isDummyPatient = ".$isDummyPatient." and d.dialogueType= :dialogueType and (pi.citizenSchoolEnd IS NULL OR StrToDate(pi.citizenSchoolEnd,'%d.%m.%Y')> ".$toDate.") and (pi.citizenSchoolEnd IS NULL AND StrToDate(pi.citizenSchoolStart,'%d.%m.%Y')> ".$month20Date.") GROUP BY pi.citizenSchoolName"
  741.                 )->setParameter('dialogueType'$dialogueType)->execute();
  742.         
  743.         $allUserSchools $em->createQuery(
  744.                         'select pi from App\Entity\PatientInformation pi 
  745.                      where pi.citizenSchoolName is not null GROUP BY pi.citizenSchoolName'
  746.                 )->execute();
  747.         /*$userSchools = $em->getRepository(PatientInformation::class)->findOneBy(array('user' => $user));*/
  748.         
  749.         $allInstitute $em->createQuery(
  750.                         'select pi from App\Entity\PatientInformation pi 
  751.                         left join App\Entity\Patient p with p.id = pi.patient
  752.                         inner join App\Entity\Dialogue d with p.id = d. patient
  753.                      where pi.citizenInstitutionName is not null and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType and (pi.citizenInstitutionToDate IS NULL OR pi.citizenInstitutionToDate> '.$toDate.') GROUP BY pi.citizenInstitutionName'
  754.                 )->setParameter('dialogueType'$dialogueType)->execute();
  755.         
  756.         if($isTestServer){
  757.             $showkopenhagen ' or  k.id =1 ';
  758.         }else{
  759.             $showkopenhagen '';
  760.         }
  761.         $allCasesKommunes $em->createQuery(
  762.                         'select k from App\Entity\Dialogue d 
  763.                         inner join App\Entity\Patient p with p.id = d. patient
  764.                         inner join App\Entity\PredefinedKomunne k with k.komunneId = p.kommuneId
  765.                      where ((p.kommuneId IS NOT NULL and p.kommuneId != 0 and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType  ) '.$showkopenhagen.' ) GROUP BY k.komunneId ORDER BY k.komunneName ASC'
  766.                 )->setParameter('dialogueType'$dialogueType)
  767.                 ->execute();
  768.         $userInfo $em->getRepository(PatientInformation::class)->findOneBy(array('user' => $user));
  769.         // Fetch Foranstaltningstype - should be the text added in the "Foranstaltning"
  770.         $dialogueMeasureText "";
  771.         
  772.         
  773.         //$joGroup = new JoGroup();
  774.         //$joGroupForm = $this->createForm(JoGroupType::class, $joGroup);
  775.         $groupPredefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCards($searchFilter);
  776.         
  777.         //$getLatestJoCaseMemosReminder = $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($selectedDialogue,$user);
  778.         
  779.         
  780.         $huskeseddelAllReminder $em->getRepository(JoCaseMemos::class)->getMemosReminderForUser(null $user);
  781.         $session->set("huskeseddelAllReminderCount"count($huskeseddelAllReminder));
  782.         
  783.         $advisCount $em->getRepository(JoCaseMemos::class)->fetchLatestAdvisFromJosaCaseMemosUnreadCount(null $user);
  784.         $session->set("advisCount"count($advisCount));
  785.         
  786.         //$loginUserInstitutions 
  787.         $loginUserData $em->createQuery("SELECT  sp.firstname,sp.familyname,sp.occupation,si.institutionnumber,si.institutionname, si.id FROM App\Entity\StilPerson sp                  
  788.                    left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser 
  789.                    left join App\Entity\StilInstitution si with sp.institutionId = si.id
  790.                    WHERE ac.user =".$user->getId() )
  791.                 ->execute();
  792.         $currentSelectedData $em->getRepository(StilInstitution::class)->findOneBy(array("id" => $currentSelectedInstitution));
  793.         if($currentSelectedData){
  794.             $currentSelectedPersonData $em->getRepository(StilPerson::class)->findOneBy(array("institutionId" => $currentSelectedInstitution));
  795.             $session->set("occupation"$currentSelectedPersonData->getOccupation());
  796.             $session->set("institutionname"$currentSelectedData->getInstitutionname());
  797.             $session->set("InstitutionNumber"$currentSelectedData->getInstitutionnumber());
  798.         }
  799.         if(!strlen($indexFilterAdUserId)) {
  800.             $indexFilterAdUserId '';
  801.         }
  802.         if(!strlen($indexAreaIds)) {
  803.             $indexAreaIds '';
  804.         }
  805.         if(!strlen($indexdocumentIds)) {
  806.             $indexdocumentIds '';
  807.         }
  808.         if ($request->isXmlHttpRequest()) {
  809.             return $this->render("default/_search_index.html.twig", array(
  810.                         'isDialogueExist' => $isDialogueExist,
  811.                         'fetchAllDialogues' => $fetchAllDialogues,
  812.                         'user' => $user,
  813.                         'indexFilterAdUserId' => $indexFilterAdUserId,
  814.                         'indexAreaIds' => $indexAreaIds,
  815.                         'indexStatusIds' => $indexStatusIds,
  816.                         'indexdocumentIds' => $indexdocumentIds,
  817.                         //'myDialogues' => $myDialogues,
  818.                         //'myDialoguesCount' => $myDialoguesCount,
  819.                         'allCaseCardsCount' => count($fetchAllDialoguesAll),
  820.                         'recentDialogues' => $recentDialogues,
  821.                         'recentDialoguesCount' => $recentDialoguesCount,
  822.                         'notesPassedReminderDate' => $notesPassedReminderDate,
  823.                         'notesPassedReminderDateCount' => $notesPassedReminderDateCount,
  824.                         'selectedPatient' => $selectedPatient,
  825.                         'selectedDialogue' => $selectedDialogue,
  826.                         'newContentDialogues' => $newContentDialogues,
  827.                         'newContentDialoguesCount' => $newContentDialoguesCount,
  828.                         'dialogueMeasureText' => $dialogueMeasureText,
  829.                         'sortBy' => $sortBy,
  830.                         'orderBy' => $orderBy,
  831.                         'listType' => $listType,
  832.                         'cids' => explode(","$indexCaseCardIds),
  833.                         'pagelimit' => $pagelimit,
  834.                         'isResultWithoutFilter' => $isResultWithoutFilter,
  835.                         'onlyMyDialogues' => $onlyMyDialogues,
  836.                         'onlyMyDialoguesCount' => $onlyMyDialoguesCount,
  837.                         'documentsLinkForEachDialgue' => $documentsLinkForEachDialgue,
  838.                         'predefinedTemplateAll' => $predefinedTemplate,
  839.                         'isTestServer' => $isTestServer,
  840.                         'loginUserData' => $loginUserData
  841.                             )
  842.             );
  843.         } else {
  844.             return $this->render("default/index.html.twig", array(
  845.                         'isDialogueExist' => $isDialogueExist,
  846.                         'fetchAllDialogues' => $fetchAllDialogues,
  847.                         'user' => $user,
  848.                         'indexFilterAdUserId' => $indexFilterAdUserId,  
  849.                         'indexAreaIds' => $indexAreaIds,
  850.                         'indexStatusIds' => $indexStatusIds,                
  851.                         'indexdocumentIds' => $indexdocumentIds,                
  852.                         //'myDialogues' => $myDialogues,
  853.                         //'myDialoguesCount' => $myDialoguesCount,
  854.                         'allCaseCardsCount' => count($fetchAllDialoguesAll),
  855.                         'recentDialogues' => $recentDialogues,
  856.                         'recentDialoguesCount' => $recentDialoguesCount,
  857.                         'notesPassedReminderDate' => $notesPassedReminderDate,
  858.                         'notesPassedReminderDateCount' => $notesPassedReminderDateCount,
  859.                         'selectedPatient' => $selectedPatient,
  860.                         'selectedDialogue' => $selectedDialogue,
  861.                         'newContentDialogues' => $newContentDialogues,
  862.                         'newContentDialoguesCount' => $newContentDialoguesCount,
  863.                         'dialogueMeasureText' => $dialogueMeasureText,
  864.                         'sortBy' => $sortBy,
  865.                         'orderBy' => $orderBy,
  866.                         'listType' => $listType,
  867.                         'predefinedCaseCardAll' => $predefinedCaseCardAll,
  868.                         'userCaseCardAll' => $userCreatedCaseCardsId,
  869.                         'allDefaultUserAreas' => $allDefaultUserAreas,
  870.                         'allUserAreas' => $allUserAreas,
  871.                         'userArea' => $userArea,
  872.                         'allUserSchools' => $allUserSchools,
  873.                         'allDefaultUserSchools' => $allDefaultUserSchools,
  874.                         'userInfo' => $userInfo,
  875.                         'allInstitute' => $allInstitute,
  876.                         'allCasesKommunes' => $allCasesKommunes,
  877.                         'cids' => array(),
  878.                         'isCprLookupActive' => $isCprLookupActive,
  879.                         'pagelimit' => $pagelimit,
  880.                         'isResultWithoutFilter' => $isResultWithoutFilter,
  881.                         'onlyMyDialogues' => $onlyMyDialogues,
  882.                         'onlyMyDialoguesCount' => $onlyMyDialoguesCount,
  883.                         //'joGroupForm' => $joGroupForm->createView(),
  884.                         'groupPredefinedCaseCardAll' => $groupPredefinedCaseCardAll,
  885.                         'selectedJoGroup' => $selectedJoGroup,
  886.                         'documentsLinkForEachDialgue' => $documentsLinkForEachDialgue,
  887.                         'isJoGroupExist' => $isJoGroupExist,
  888.                         'isTestServer' => $isTestServer,
  889.                         'loginUserData' => $loginUserData
  890.                             )
  891.             );
  892.         }
  893.     }
  894.     public function createCase() {
  895.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  896.         return $this->render("default/createCase.html.twig");
  897.     }
  898.     public function createCaseWithExisting(Request $request$cprNo) {
  899.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  900.         $cprNo base64_decode($cprNo);
  901.         $em $this->getDoctrine()->getManager();
  902.         $session $request->getSession();
  903.         $selectedDialogue $session->get("selectedDialogue"null);
  904.         
  905.         if ($selectedDialogue) {
  906.             $selectedDialogue $em->getRepository(Dialogue::class)->find($selectedDialogue);
  907.         }
  908.         // Symfony 2.5
  909.         //$therapist = $this->get('security.context')->getToken()->getUser();
  910.         // Symfony 2.6
  911.         $user $this->get('security.token_storage')->getToken()->getUser();
  912.         $patientObj $womenArray $menArray $gardianArray $addedRelations $childExtraInfo = array();
  913.         $gardianExistCnt 0;
  914.         $session $request->getSession();
  915.         //$session->set('isUserCreated', false);
  916.         $womenExist $menExist $bothExist $gardianAsWomen $gardianAsMen false;
  917.         $isExistingPatient false;
  918.         $searchFilter "ROLE_DTS";
  919.         if ($user->hasRole('ROLE_CSV')) {
  920.             $searchFilter "ROLE_CSV";
  921.         }
  922.         if ($cprNo) {
  923.             $cprNo str_replace('-'''$cprNo);
  924.             $patientObjTemp $em->getRepository(Patient::class)->findBy(array('cpr' => $cprNo));
  925.             $patientObj $patientObjTemp $patientObjTemp[0] : array();
  926.             
  927.             if($patientObj->getId() < 20) {
  928.                 $isExistingPatient true;
  929.             }
  930.             
  931.             $userObjTemp $em->getRepository(User::class)->findBy(array('username' => $cprNo));
  932.              $userObj $userObjTemp $userObjTemp[0] : array();
  933.             //var_dump($userObj);
  934.             //Patient family members
  935.             $patientFamilyObj $em->getRepository(Family::class)->findBy(array('patient' => $patientObj));
  936.             //Patient info
  937.             $patientInfoObjTemp $em->getRepository(PatientInformation::class)->findBy(array('user' => $patientObj->getUser()));
  938.             $patientInfoObj $patientInfoObjTemp $patientInfoObjTemp[0] : array();
  939.             //var_dump($patientInfoObj);
  940.             $statCprNo $cprNo;
  941.             
  942.             if($patientInfoObj && $patientInfoObj->getIsMultiple()){
  943.                 $childExtraInfoTemp $em->getRepository(PatientInformationDetails::class)->findBy(array('user' => $patientObj->getUser()),array('id' => 'desc','citizen_institution_from_date' =>'desc'));
  944.                 $childExtraInfo[$statCprNo]['info'] = $childExtraInfoTemp $childExtraInfoTemp : array();
  945. //             var_dump($childExtraInfo);die;
  946.            }
  947.             /*if ($statCprNo == '0605045467') {
  948.                 $childExtraInfo[$statCprNo]['info'][0] = array("citizen_institution_name" => "Fritidscenter Bispebjerg Nord", "citizen_institution_fromdate" => "01.08.2014", "citizen_institution_tilldate" => "30.05.2017", "citizen_school_name" => "", "citizen_school_fromdate" => "", "citizen_school_tilldate" => "");
  949.                 $childExtraInfo[$statCprNo]['info'][1] = array("citizen_institution_name" => "Fritidsinstitutionen ved Guldberg Skole", "citizen_institution_fromdate" => "01.08.2010", "citizen_institution_tilldate" => "03.06.2014", "citizen_school_name" => "", "citizen_school_fromdate" => "", "citizen_school_tilldate" => "");
  950.             }
  951.             if ($statCprNo == '1110104359') {
  952.                 $childExtraInfo[$statCprNo]['info'][0] = array("citizen_institution_name" => "Børnevænget", "citizen_institution_fromdate" => "30.11.2011", "citizen_institution_tilldate" => "14.01.2013", "citizen_school_name" => "", "citizen_school_fromdate" => "", "citizen_school_tilldate" => "");
  953.             }
  954.             if ($statCprNo == '1102128866') {
  955.                 $childExtraInfo[$statCprNo]['info'][0] = array("citizen_institution_name" => "", "citizen_institution_fromdate" => "", "citizen_institution_tilldate" => "", "citizen_school_name" => "Blågård Skole", "citizen_school_fromdate" => "10.08.2018", "citizen_school_tilldate" => "08.08.2019");
  956.             }*/
  957.             
  958.             $getFullDate $this->getBirthDate($cprNo);
  959.             $bdateYear date_format($getFullDate"d.m.Y");
  960.             $dateDiff $this->getUserAge($bdateYear);
  961.             foreach ($patientFamilyObj as $patientFamily) {
  962.                 if ($patientFamily->getRelation() == "1") {
  963.                     $womenArray $patientFamily;
  964.                     $womenExist true;
  965.                 }
  966.                 if ($patientFamily->getRelation() == "2") {
  967.                     $menArray $patientFamily;
  968.                     $menExist true;
  969.                 }
  970.                 if ($patientFamily->getRelation() == "9") {
  971.                     if($patientFamily->getRelative()->getDeletedBy() == null){
  972.                     $addedRelations[] = $patientFamily;
  973.                     }
  974.                 }
  975.                 
  976.                 if ($patientFamily->getRelation() == "3") {
  977.                     $gardianArray[] = $patientFamily;
  978.                     $gardianExist true;
  979.                     $gardianExistCnt = ($gardianExistCnt+1);
  980.                 }
  981.                 
  982.             }
  983.             
  984.             if ($womenExist && $menExist) {
  985.                 $bothExist true;
  986.             }
  987.             if(count($gardianArray) == "1") {
  988.                 if(!$womenExist) {
  989.                     $womenArray =  $gardianArray $gardianArray[0] : array();
  990.                     $gardianAsWomen $womenExist true;
  991.                     $gardianArray=[];
  992.                 }
  993.                 if($womenExist && !$menExist) {
  994.                     $menArray $gardianArray $gardianArray[0] : array();
  995.                     $gardianAsMen $menExist true;
  996.                     $gardianArray=[];
  997.                 }
  998.                 if($bothExist) {
  999.                     $gardianArray $gardianArray;
  1000.                 }
  1001.             }
  1002.             //var_dump($gardianAsMen, $menExist); die;
  1003.             $dialogueObj $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $patientObj));
  1004.             $session->set("selectedPatient"$patientObj);
  1005.             $session->set("selectedDialogue"$dialogueObj);
  1006.             $dialogueConsentObj $em->getRepository(DialogueConsentInfo::class)->findOneBy(array('dialogue' => $dialogueObj));
  1007.             $patientTravelNeedsDetails $em->getRepository(TravelNeedsDetails::class)->findBy(array('dialogue' => $dialogueObj'patient' => $patientObj));
  1008.         }
  1009.         
  1010.         $locationText null;
  1011.         $patientInstitutionMasterObj null;
  1012.         if(!is_array($patientInfoObj)){
  1013.         $patientInstitutionMasterObj $em->getRepository(JoMasterInformation::class)->findOneBy(array("inr" => $patientInfoObj->getCitizenInstitutionNumber()));
  1014.         
  1015.         if($patientInfoObj->getInstitutionLocationId() > 0){
  1016.             $location $em->getRepository(JoMasterInformationLocation::class)->find($patientInfoObj->getInstitutionLocationId());
  1017.             $locationText $location $location->getAdresseWithAlias() : null;
  1018.         }
  1019.         }
  1020.   
  1021.         $groupPredefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCards($searchFilter);
  1022.         
  1023.         $areaNames $em->getRepository(JoMasterInformation::class)->getAreaNames();
  1024.         $komunneIdsArray = array(
  1025.                         '101' => 'København',
  1026.                         '147' => 'Frederiksberg',
  1027.                         '151' => 'Ballerup',
  1028.                         '153' => 'Brøndby',
  1029.                         '155' => 'Dragør',
  1030.                         '157' => 'Gentofte',
  1031.                         '159' => 'Gladsaxe',
  1032.                         '161' => 'Glostrup',
  1033.                         '163' => 'Herlev',
  1034.                         '165' => 'Albertslund',
  1035.                         '167' => 'Hvidovre',
  1036.                         '169' => 'Høje-Taastrup',
  1037.                         '173' => 'Lyngby-Taarbæk',
  1038.                         '175' => 'Rødovre',
  1039.                         '183' => 'Ishøj',
  1040.                         '185' => 'Tårnby',
  1041.                         '187' => 'Vallensbæk',
  1042.                         '190' => 'Furesø',
  1043.                         '201' => 'Allerød',
  1044.                         '210' => 'Fredensborg',
  1045.                         '217' => 'Helsingør',
  1046.                         '219' => 'Hillerød',
  1047.                         '223' => 'Hørsholm',
  1048.                         '230' => 'Rudersdal',
  1049.                         '240' => 'Egedal',
  1050.                         '250' => 'Frederikssund',
  1051.                         '253' => 'Greve',
  1052.                         '259' => 'Køge',
  1053.                         '260' => 'Halsnæs',
  1054.                         '265' => 'Roskilde',
  1055.                         '269' => 'Solrød',
  1056.                         '270' => 'Gribskov',
  1057.                         '306' => 'Odsherred',
  1058.                         '316' => 'Holbæk',
  1059.                         '320' => 'Faxe',
  1060.                         '326' => 'Kalundborg',
  1061.                         '329' => 'Ringsted',
  1062.                         '330' => 'Slagelse',
  1063.                         '336' => 'Stevns',
  1064.                         '340' => 'Sorø',
  1065.                         '350' => 'Lejre',
  1066.                         '360' => 'Lolland',
  1067.                         '370' => 'Næstved',
  1068.                         '376' => 'Guldborgsund',
  1069.                         '390' => 'Vordingborg',
  1070.                         '400' => 'Bornholm',
  1071.                         '410' => 'Middelfart',
  1072.                         '411' => 'Christiansø',
  1073.                         '420' => 'Assens',
  1074.                         '430' => 'Faaborg-Midtfyn',
  1075.                         '440' => 'Kerteminde',
  1076.                         '450' => 'Nyborg',
  1077.                         '461' => 'Odense',
  1078.                         '479' => 'Svendborg',
  1079.                         '480' => 'Nordfyns',
  1080.                         '482' => 'Langeland',
  1081.                         '492' => 'Ærø',
  1082.                         '510' => 'Haderslev',
  1083.                         '530' => 'Billund',
  1084.                         '540' => 'Sønderborg',
  1085.                         '550' => 'Tønder',
  1086.                         '561' => 'Esbjerg',
  1087.                         '563' => 'Fanø',
  1088.                         '573' => 'Varde',
  1089.                         '575' => 'Vejen',
  1090.                         '580' => 'Aabenraa',
  1091.                         '607' => 'Fredericia',
  1092.                         '615' => 'Horsens',
  1093.                         '621' => 'Kolding',
  1094.                         '630' => 'Vejle',
  1095.                         '657' => 'Herning',
  1096.                         '661' => 'Holstebro',
  1097.                         '665' => 'Lemvig',
  1098.                         '671' => 'Struer',
  1099.                         '706' => 'Syddjurs',
  1100.                         '707' => 'Norddjurs',
  1101.                         '710' => 'Favrskov',
  1102.                         '727' => 'Odder',
  1103.                         '730' => 'Randers',
  1104.                         '740' => 'Silkeborg',
  1105.                         '741' => 'Samsø',
  1106.                         '746' => 'Skanderborg',
  1107.                         '751' => 'Aarhus',
  1108.                         '756' => 'Ikast-Brande',
  1109.                         '760' => 'Ringkøbing-Skjern',
  1110.                         '766' => 'Hedensted',
  1111.                         '773' => 'Morsø',
  1112.                         '779' => 'Skive',
  1113.                         '787' => 'Thisted',
  1114.                         '791' => 'Viborg',
  1115.                         '810' => 'Brønderslev',
  1116.                         '813' => 'Frederikshavn',
  1117.                         '820' => 'Vesthimmerlands',
  1118.                         '825' => 'Læsø',
  1119.                         '840' => 'Rebild',
  1120.                         '846' => 'Mariagerfjord',
  1121.                         '849' => 'Jammerbugt',
  1122.                         '851' => 'Aalborg',
  1123.                         '860' => 'Hjørring');
  1124.                 $komunneId $patientObj->getKommuneId();
  1125.                 if (array_key_exists($komunneId,$komunneIdsArray)) {
  1126.                     $komunneName $komunneIdsArray[$komunneId];
  1127.                 } else if($patientObj->getIsDummyPatient()) {
  1128.                     $komunneName "Københavns";
  1129.                 } else {
  1130.                     $komunneName "";
  1131.                 }
  1132.                 $getLatestJoCaseMemosReminder $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($dialogueObj,$user);
  1133.                 $loginUserData $em->createQuery("SELECT  sp.firstname,sp.familyname,sp.occupation,si.institutionnumber,si.institutionname, si.id FROM App\Entity\StilPerson sp                  
  1134.                     left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser 
  1135.                     left join App\Entity\StilInstitution si with sp.institutionId = si.id
  1136.                     WHERE ac.user =".$user->getId() )
  1137.                 ->execute();        
  1138.         return $this->render("default/createCaseWithExisting.html.twig", array(
  1139.                     'patientObj' => $patientObj,
  1140.                     'patientFamilyObj' => $patientFamilyObj,
  1141.                     'patientAge' => $dateDiff,
  1142.                     'womenExist' => $womenExist,
  1143.                     'menExist' => $menExist,
  1144.                     'bothExist' => $bothExist,
  1145.                     'womenArray' => $womenArray,
  1146.                     'menArray' => $menArray,
  1147.                     'addedRelations' => $addedRelations,
  1148.                     'user' => $user,
  1149.                     'patientInfoObj' => $patientInfoObj,
  1150.                     'childExtraInfo' => $childExtraInfo,
  1151.                     'statCprNo' => $statCprNo,
  1152.                     'dialogueObj' => $selectedDialogue,
  1153.                     'dialogueConsentObj' => $dialogueConsentObj,
  1154.                     'patientTravelNeedsDetails' => $patientTravelNeedsDetails,
  1155.                     'dateDiff' => $dateDiff,
  1156.                     'userObj' => $userObj,
  1157.                     'isExistingPatient' => $isExistingPatient,
  1158.                     'groupPredefinedCaseCardAll' => $groupPredefinedCaseCardAll,
  1159.                     'instituteLocations' => $patientInstitutionMasterObj ?  $patientInstitutionMasterObj->getJoMasterInformationLocations() : null,
  1160.                     'locationText' => $locationText,
  1161.                     'areaNames' => $areaNames,
  1162.                     'komunneName' => $komunneName,
  1163.                     'komunneId' => $komunneId,
  1164.                     'getLatestJoCaseMemosReminder' => $getLatestJoCaseMemosReminder,
  1165.                     'gardianArray' => $gardianArray,
  1166.                     'gardianExistCnt' => $gardianExistCnt,
  1167.                     'gardianAsWomen' => $gardianAsWomen,
  1168.                     'gardianAsMen' => $gardianAsMen,
  1169.                     'loginUserData' => $loginUserData
  1170.    
  1171.         ));
  1172.     }
  1173.     public function caseDetailView(Request $request) {
  1174.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  1175.         $em $this->getDoctrine()->getManager();
  1176.         $session $request->getSession();
  1177.         $detailviewId $request->get("detailviewId");
  1178.         $selectedPatient $session->get("selectedPatient"false);
  1179.         $selectedDialogue $session->get("selectedDialogue"false);
  1180.         $activityId $session->get("activityDetailUpdated"0);
  1181.         $session->set('activityDetailUpdated'NULL); //$session->set('activityDetailUpdated', 0);
  1182.         //var_dump($selectedPatient->getId(), $selectedDialogue->getId()); die;
  1183.         if (!$selectedPatient) {
  1184.             return $this->redirect($this->generateUrl('index'));
  1185.         }
  1186.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  1187.         $patientDetails $patient->getId();
  1188.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  1189.         //$user = $em->getRepository(User::class)->find(1);
  1190.         $user $this->get('security.token_storage')->getToken()->getUser();
  1191.         if (!$dialogue) {
  1192.             return $this->redirect($this->generateUrl('index'));
  1193.         }
  1194.         $patient $dialogue->getPatient();
  1195.         $session->set("selectedDialogue"$dialogue);
  1196.         $session->set("selectedPatient"$patient);
  1197.         
  1198.         
  1199.         $getLatestJoCaseMemos $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue,$user);
  1200.         $session->set("caseMemoCount",count($getLatestJoCaseMemos));
  1201.         $getLatestJoCaseComments $em->getRepository(JoCaseComments::class)->getLatestJoCaseComments($dialogue,$user);
  1202.         $session->set("caseCommentsCount"count($getLatestJoCaseComments));
  1203.         $getLatestJoCaseMemosReminder $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($dialogue,$user);
  1204.         //Delete DialogueAttachmentDetails activity if no borgerplan is attached to this
  1205.         $checkActivityNotAttachedToEventsCnt $em->getRepository(DialogueAttachmentDetails::class)->checkActivityNotAttachedToEventsCnt($dialogue,$user);
  1206.         if(count($checkActivityNotAttachedToEventsCnt) > 0) {
  1207.             foreach($checkActivityNotAttachedToEventsCnt as $dialogueAttachmentDetail) {
  1208.                 if($dialogueAttachmentDetail){
  1209.                     $JoCaseCardEventBrevActivityObj $em->getRepository(JoCaseCardEventBrevActivity::class)->findOneBy(array('attachmentDetails' => $dialogueAttachmentDetail));
  1210.                     if($JoCaseCardEventBrevActivityObj){
  1211.                         $em->remove($JoCaseCardEventBrevActivityObj);
  1212.                         $em->flush();
  1213.                     }
  1214.                     $em->remove($dialogueAttachmentDetail);
  1215.                     $em->flush();
  1216.                 }
  1217.             }
  1218.         }
  1219.         
  1220.         $finishedForm $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'activityType' => '1''isPostMailActivity' => 0));
  1221.         $draftForm $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'activityType' => '2''isPostMailActivity' => 0));
  1222.         $finishedScheme  $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'activityType' => '3''isPostMailActivity' => 0));
  1223.         $draftScheme $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'activityType' => '4''isPostMailActivity' => 0));
  1224.         $finishedNote $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'activityType' => '5''isPostMailActivity' => 0));
  1225.         $draftNote $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'activityType' => '6''isPostMailActivity' => 0));
  1226.         $finishedAttachment $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'activityType' => '7''isPostMailActivity' => 0));
  1227.         $draftAttachment $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'activityType' => '8''isPostMailActivity' => 0));
  1228.         $borgerplan $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'pAtttachmentType' => '8''isPostMailActivity' => 0));
  1229.                 
  1230.         if(count($finishedForm)){
  1231.             
  1232.         }
  1233.         $caseCardTypeListLi = array(
  1234.             => array(
  1235.                 'label' => 'Brev afsluttet''meaning' => 'Form/Letter-finished''count' => count($finishedForm)),
  1236.             => array(
  1237.                 'label' => 'Brev kladde''meaning' => 'Form/Letter-Draft''count' => count($draftForm)),
  1238.             => array(
  1239.                 'label' => 'Skabelon afsluttet''meaning' => 'Form/Scheme-finished','count' => count($finishedScheme)),
  1240.             => array(
  1241.                 'label' => 'Skabelon kladde''meaning' => 'Form/Scheme-Draft','count' => count($draftScheme)),
  1242.             => array(
  1243.                 'label' => 'Note afsluttet''meaning' => 'Note-finished','count' => count($finishedNote)),
  1244.             => array('label' => 'Note kladde''meaning' => 'Note-Draft','count' => count($draftNote)),
  1245.             => array('label' => 'Vedhæft afsluttet''meaning' => 'Attacment-finished','count' => count($finishedAttachment)),
  1246.             => array('label' => 'Vedhæft kladde''meaning' => 'Attacment-Draft','count' => count($draftAttachment)),
  1247.             10 => array('label' => 'Borgerplan afsluttet''meaning' => 'Borgerplan','count' => count($borgerplan)),
  1248.             => array('label' => 'Borgerplan kladde''meaning' => 'Borgerplan','count' => count($borgerplan)));
  1249.         //$selectedDialogue = $dialogue;
  1250.         //$cpr = "111111";
  1251.         $cpr $patient->getCpr();
  1252.         $getFullDate $this->getBirthDate($cpr);
  1253.         $bdateYear date_format($getFullDate"d.m.Y");
  1254.         $dateDiff $this->getUserAge($bdateYear);
  1255.         $searchFilter "ROLE_DTS";
  1256.         if ($user->hasRole('ROLE_CSV')) {
  1257.             $searchFilter "ROLE_CSV";
  1258.         }
  1259.         $joPredefinedCaseCardObjs NULL;
  1260.         $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForIndividual' => 1));
  1261.         $predefinedCaseCardAllIds = array();
  1262.         $joPredefinedCaseCardObj $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'josa_rapport'));
  1263.         if($joPredefinedCaseCardObj){
  1264.             $predefinedCaseCardAllIds[] = $joPredefinedCaseCardObj->getId();
  1265.         }
  1266.         $joPredefinedCaseCardObj $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'Sagsgrundlag'));
  1267.         if($joPredefinedCaseCardObj){
  1268.             $predefinedCaseCardAllIds[] = $joPredefinedCaseCardObj->getId();
  1269.             $joPredefinedCaseCardObjs $joPredefinedCaseCardObj;
  1270.         }
  1271.         $joGroupObj NULL;
  1272.         if(($dialogue->getDialogueType() == || $dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_DTS" ) {
  1273.             $joGroupObj $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  1274.             
  1275.             //$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCardListByType($searchFilter, $joGroupObj->getJoMasterInformation()->getInfoType(), $joGroupObj->getJoMasterInformation()->getKkorg());
  1276.             $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForGroup' => '1'));
  1277.         } else if(($dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_CSV" ) {
  1278.             $joGroupObj $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  1279.             $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForGroup' => 1));
  1280.         }
  1281.         //$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findAll();
  1282.         //$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findById(array(1, 2, 3, 4, 6, 9, 11,12), array('orderBy' => 'asc'));
  1283.         $predefinedAttachmentType $em->getRepository(PredefinedAttachmentType::class)->findBy(array('isActivityType' => 1), array('orderBy' => 'asc'));
  1284.         $dialogueCaseCardAll $em->getRepository(DialogueCaseCard::class)->findBy(array('dialogue' => $selectedDialogue));
  1285.         $userCreatedCaseCardsId $userCreatedDialogueCaseCard = array();
  1286.         $closedCaseCardCount 0;
  1287.         foreach ($dialogueCaseCardAll as $dialogueCaseCard) {
  1288.             if (!$dialogueCaseCard->getIsClosed()) {
  1289.                 $userCreatedCaseCardsId[] = $dialogueCaseCard->getPCaseCardId()->getId();
  1290.                 $userCreatedDialogueCaseCard[$dialogueCaseCard->getPCaseCardId()->getId()] = $dialogueCaseCard->getId();
  1291.             }else{
  1292.                 $closedCaseCardCount++;
  1293.             }
  1294.         }
  1295.         /*$predefinedTemplates = $em->getRepository(PredefinedTemplate::class)->findBy(array(), array('orderBy' => 'asc'));
  1296.         $parentTemplate = $childTemplate = array();
  1297.         foreach ($predefinedTemplates as $predefinedTemplate) {
  1298.             if ($predefinedTemplate->getParentId() == "0") {
  1299.                 $parentTemplate[$predefinedTemplate->getId()] = $predefinedTemplate;
  1300.             } else {
  1301.                 $childTemplate[$predefinedTemplate->getParentId()][] = $predefinedTemplate;
  1302.             }
  1303.         }*/
  1304.         //var_dump($userCreatedCaseCardsId, $userCreatedDialogueCaseCard);
  1305.         $sortBy $request->get('sortBy');
  1306.         $orderBy $request->get('orderBy');
  1307.         
  1308.             if ($user->hasRole('ROLE_PARENT')) {
  1309.                 $activitySharing $em->getRepository(JoActivitySharing::class)->findOneBy(array('dialogue' => $dialogue));
  1310.                 if($activitySharing){
  1311.                     //$dialogueAttachmentDetailIds = $activitySharing->getLoggedInCitizenActivitiesForDialog($user);
  1312.                     $activitySharingParticipant $em->getRepository(JoActivitySharingParticipant::class)->findOneBy(array('joActivitySharing' => $activitySharing'user' => $user));
  1313.                     if($activitySharingParticipant){
  1314.                         $dialogueAttachmentDetailIds $activitySharingParticipant->getLoggedInCitizenActivitiesForDialog();
  1315.                     }else{
  1316.                         $dialogueAttachmentDetailIds = array();
  1317.                     }
  1318.                 }else{
  1319.                     $dialogueAttachmentDetailIds = array();
  1320.                 }
  1321.             }else{
  1322.                 $dialogueAttachmentDetailIds = array();
  1323.             }
  1324.             $update_skalering $this->updateSkaleringAttachment($dialogue,$patient,$em);
  1325.             $dialogueAttachmentFilter $em->getRepository(DialogueAttachmentDetails::class)->filterDialogueAttachmentDetails($dialogue$patient'''''''''''''''''','','' ,$dialogueAttachmentDetailIds0$user );
  1326.             $dialogueAttachmentDetails $dialogueAttachmentFilter['result'];
  1327.             $futureActivities $dialogueAttachmentFilter['futureActivitiesCount'];
  1328.             //When an event is journalised(black line) the date of the event should be shown instead of the create date in the case activity column dato. 13-06-2020
  1329.             $isAttachmentDateUpdated false;
  1330.             $relatedRecordsDetails= [];
  1331.             $tunnelshareActivity=array();
  1332.             $scaleGraphArray=array();
  1333.             foreach ($dialogueAttachmentDetails as $attachmentDetailObj) {
  1334.                 if ($attachmentDetailObj->getPAtttachmentType()->getId() == 8) {
  1335.                     foreach ($attachmentDetailObj->getJoCaseCardEvents() as $eventObj) {
  1336.                         $eventStartAt strtotime($eventObj->getStartAt()->format('Y-m-d'));
  1337.                         $currentDate strtotime("now");
  1338.                         if(strtotime($attachmentDetailObj->getAttachmentDate()->format('Y-m-d')) != strtotime($eventObj->getStartAt()->format('Y-m-d')) ) {
  1339.                             if ($eventStartAt $currentDate) {
  1340.                                 $attachmentDetailObj->setAttachmentDate($eventObj->getStartAt());
  1341.                                 $em->persist($attachmentDetailObj);
  1342.                                 $em->flush();
  1343.                                 $isAttachmentDateUpdated true;
  1344.                             }else if($dialogue->getDialogueType() == || $dialogue->getDialogueType() == 4){
  1345.                                 $attachmentDetailObj->setAttachmentDate($eventObj->getStartAt());
  1346.                                 $em->persist($attachmentDetailObj);
  1347.                                 $em->flush();
  1348.                                 $isAttachmentDateUpdated true;
  1349.                             }
  1350.                         }
  1351.                         
  1352.                         if($attachmentDetailObj->getPatient()->getUser() != NULL && $attachmentDetailObj->getPatient()->getUser()->getId() == $patient->getUser()->getId()){
  1353.                             $relatedRecords $em->getRepository(JoCaseCardEvent::class)->findChildIndividualDialogEventList($dialogue,$eventObj->getDialogueCaseCard(),$eventObj->getDialogueCaseCardMeasure(),$eventObj->getHeading(),$eventObj->getEventCollection());
  1354.                             if($relatedRecords != '' && (count($relatedRecords) > )){
  1355.                             $relatedRecordsDetails[$attachmentDetailObj->getId()]['index'] = array_search($eventObj$relatedRecords) + 1;
  1356.                             $relatedRecordsDetails[$attachmentDetailObj->getId()]['count'] = count$relatedRecords);
  1357.                             $min $relatedRecords[0];
  1358.                             for ($i 1$i count($relatedRecords); $i++)
  1359.                                 if ($relatedRecords[$i]->getId() < $min->getId())
  1360.                                     $min $relatedRecords[$i];
  1361.                             $relatedRecordsDetails[$attachmentDetailObj->getId()]['link_id'] =  $min->getId();
  1362.                             }
  1363.                         }
  1364.                     }
  1365.                 }
  1366.                 $tunnelRid$attachmentDetailObj->getTunnelListId();
  1367.                 if($tunnelRid){
  1368.                     $tunnelDetailsObj $em->getRepository(SepoTunnelliste::class)->findOneBy(array('rid' => $tunnelRid));
  1369.                     if($tunnelDetailsObj){
  1370.                         $tunnelshareActivity[$tunnelRid]=  array('name' =>  $tunnelDetailsObj->getName());
  1371.                     }
  1372.                 }
  1373.             
  1374.                 //featchScaleGraph detils
  1375.                 $res=$this->featchAllScalingGraphDetails($em,$attachmentDetailObj);
  1376.                 if($res){
  1377.                     $scaleGraphArray[$attachmentDetailObj->getId()] = isset($res['scalingIndividualGraphArray'][$attachmentDetailObj->getId()])?$res['scalingIndividualGraphArray'][$attachmentDetailObj->getId()]:[];
  1378.                 }
  1379.                 
  1380.                 //clear activity access older than today (if not cleared)
  1381.                 if($attachmentDetailObj->getIsOpen() == 1){
  1382.                     if(strtotime($attachmentDetailObj->getOpenTime()->format('Y-m-d')) < strtotime((new \DateTime())->format('Y-m-d')) ) {
  1383.                          $attachmentDetailObj->setIsOpen(0);
  1384.                          $attachmentDetailObj->setOpenedBy(null);
  1385.                          $attachmentDetailObj->setOpenTime(null);
  1386.                          $em->persist($attachmentDetailObj);
  1387.                          $em->flush();
  1388.                     }
  1389.                 }
  1390.             }
  1391.             if($isAttachmentDateUpdated){                
  1392.                 $dialogueAttachmentFilter $em->getRepository(DialogueAttachmentDetails::class)->filterDialogueAttachmentDetails($dialogue$patient'''''''''''''''''','','' ,$dialogueAttachmentDetailIds0$user );
  1393.                 $dialogueAttachmentDetails $dialogueAttachmentFilter['result'];
  1394.                 $futureActivities $dialogueAttachmentFilter['futureActivitiesCount'];
  1395.             }
  1396.         //}
  1397.         
  1398.         $dialogueAttachments $em->getRepository(DialogueAttachments::class)->findBy(array('dialogue' => $dialogue'patient' => $patient));
  1399.         $dialogueAttachmentFileName = array();
  1400.         foreach ($dialogueAttachments as $dialogueAttachment) {
  1401.             $id $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
  1402.             $dialogueAttachmentFileName[$id]['files'][] = $dialogueAttachment;
  1403.         }
  1404.         $webPath '/public/uploads/attachments/'//$this->get('kernel')->getProjectDir() . 
  1405.         //var_dump($dialogueAttachmentFileName); die;
  1406.         $dialogueNotes $em->getRepository(DialogueNotes::class)->findBy(array('dialogue' => $dialogue'patient' => $patient));
  1407.         $current_year date('Y');
  1408.         $range range($current_year$current_year 10);
  1409.         $last10Years array_combine($range$range);
  1410.         //fetch all DialogueCaseCardMeasure related to ccId
  1411.         //$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->findBy(array('referenceType' => 'F'));
  1412.         $dialogueCaseCardMeasureAll $em->getRepository(DialogueCaseCardMeasure::class)->fetchMeasureTilDate('F',new \DateTime(),$user->getProfession());
  1413.         
  1414.         //fetch completed casecard activities
  1415.         $dialogueCompleteAttachmentDetails $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue'patient' => $patient'isDraft' => "0"'isPostMailActivity' => 0));
  1416.         
  1417.         $joGroupObj NULL;
  1418.         if($dialogue->getDialogueType() > && $dialogue->getDialogueType() < 5) {
  1419.             $joGroupObj $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  1420.         }
  1421.         $groupPredefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCards($searchFilter);
  1422.         
  1423.         $areaNames $em->getRepository(JoMasterInformation::class)->getAreaNames();
  1424.         $holdList $em->getRepository(JoCaseCardHold::class)->findAll();
  1425.         //$joGroup = new JoGroup();
  1426.         //$joGroupForm = $this->createForm(JoGroupType::class, $joGroup);
  1427.         
  1428.         $isSavedAsActivity false;
  1429.         $getNotSavedAsActivityPostMails $em->getRepository(JoPostMail::class)->getNotSavedAsActivityPostMails($isSavedAsActivity$dialogue);
  1430.         $session->set("postMailCnt"count($getNotSavedAsActivityPostMails));
  1431.         
  1432.         $showFutureActivities 0;
  1433.         $isBackendEnabled $this->container->getParameter('isBackendEnabled');
  1434.         
  1435.         $komunneId $patient->getKommuneId();
  1436.         $session->set("komunneId",$komunneId);
  1437.         $brevActivityEvent=array();
  1438.         $checkBrevActivityDetails $em->getRepository(DialogueAttachmentDetails::class)->checkBrevActivityEvent($dialogue,$patient);
  1439.         foreach ($checkBrevActivityDetails as $brevActivity) {
  1440.             $brevActivityEvent[$brevActivity['id']]=  array('eventId' => $brevActivity['eventId'],
  1441.                     'heading' =>  $brevActivity['heading'],
  1442.                 );
  1443.         }
  1444.         $loginUserData $em->createQuery("SELECT  sp.firstname,sp.familyname,sp.occupation,si.institutionnumber,si.institutionname, si.id FROM App\Entity\StilPerson sp                  
  1445.                    left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser 
  1446.                    left join App\Entity\StilInstitution si with sp.institutionId = si.id
  1447.                    WHERE ac.user =".$user->getId() )
  1448.                 ->execute(); 
  1449.         //check count skelering activity
  1450.         $checkForSkelering $em->getRepository(DialogueAttachmentDetails::class)->checkSkeleringActivity($dialogue$patient);
  1451.         // to display brev and delt sagskter display sent mail/ebook date time
  1452.         $skebelon_ebook_log $em->getRepository(SkebelonEbookLog::class)->findBy(array('dialogueId' => $dialogue->getId()));
  1453.         foreach ($skebelon_ebook_log as $skebelon_ebook_logs) {
  1454.             // $skebelon_ebook_log_arr[]= $skebelon_ebook_logs['status'];
  1455.             $id $skebelon_ebook_logs->getDialogueAttachmentDetailId();
  1456.             $created_at date_format($skebelon_ebook_logs->getCreatedAt(), "d.m.Y, h.i");
  1457.             $status $skebelon_ebook_logs->getStatus();
  1458.             $skebelon_ebook_log_arr[$id]=  array('created_at' => $created_at,
  1459.                     'status' => $status ,'id'=>$id
  1460.                 );
  1461.         }
  1462.         
  1463.         $i 0;
  1464.         foreach($dialogueAttachmentDetails as $dialogueAttachment)
  1465.         {
  1466.             $noteQuery $em->createQuery("SELECT dad FROM App\Entity\DialogueAttachmentDetails  dad
  1467.             WHERE  dad.parentId =:parentId order by dad.updatedAt DESC")
  1468.             ->setParameter('parentId'$dialogueAttachment->getId());
  1469.             $noteIds $noteQuery->execute();
  1470.             $dialogueAttachmentArray[$dialogueAttachment->getId()] = $noteIds;
  1471.         $i++;
  1472.         }
  1473.         
  1474.         return $this->render("default/caseDetailView.html.twig", array(
  1475.                     'dateDiff' => $dateDiff,
  1476.                     'dialogueNotes' => $dialogueNotes,
  1477.                     'dialogueCaseCardAll' => $dialogueCaseCardAll,
  1478.                     'predefinedCaseCardAll' => $predefinedCaseCardAll,
  1479.                     'userCreatedCaseCardsId' => $userCreatedCaseCardsId,
  1480.                     'patientObj' => $patient,
  1481.                     'user' => $user,
  1482.                     'dialogue' => $dialogue,
  1483.                     'predefinedAttachmentType' => $predefinedAttachmentType,
  1484.                     'dialogueAttachmentDetails' => $dialogueAttachmentDetails,
  1485.                     'holdList' => $holdList,
  1486.                     'dialogueAttachmentFileName' => $dialogueAttachmentFileName,
  1487.                     'webPath' => $webPath,
  1488.                     'sortBy' => $sortBy,
  1489.                     'orderBy' => $orderBy,
  1490.                     'showFutureActivities' => $showFutureActivities,
  1491.                     'futureActivities' => $futureActivities,
  1492.                     'dialogueObj' => $dialogue,
  1493.                     'userCreatedDialogueCaseCard' => $userCreatedDialogueCaseCard,
  1494.                     'caseCardTypeListLi' => $caseCardTypeListLi,
  1495.                     'last10Years' => $last10Years,
  1496.                     'dialogueCaseCardMeasureAll' => $dialogueCaseCardMeasureAll,
  1497.                     'detailviewId' => $detailviewId,
  1498.                     'activityId' => $activityId,
  1499.                     'closedCaseCardCount' => $closedCaseCardCount,
  1500.                     'dialogueCompleteAttachmentDetails' => count($dialogueCompleteAttachmentDetails),
  1501.                     'joGroupObj' => $joGroupObj,
  1502.                     'groupPredefinedCaseCardAll' => $groupPredefinedCaseCardAll,
  1503.                     'relatedRecordsDetails' => $relatedRecordsDetails,
  1504.                     'areaNames' => $areaNames,
  1505.                     'isBackendEnabled' => $isBackendEnabled,
  1506.                     'brevActivityEvent' => $brevActivityEvent,
  1507.                     'getLatestJoCaseMemosReminder' => $getLatestJoCaseMemosReminder,
  1508.                     'tunnelshareActivity' => $tunnelshareActivity,
  1509.                     'patientDetails' => $patientDetails,
  1510.                     'scaleGraphArray' => $scaleGraphArray,
  1511.                     'skeleringCnt' => count($checkForSkelering),
  1512.                     'loginUserData' => $loginUserData,
  1513.                     'joPredefinedCaseCardObjs' => $joPredefinedCaseCardObjs,
  1514.                     'dialogueAttachmentArray' => $dialogueAttachmentArray
  1515.                     //'joGroupForm' => $joGroupForm->createView(),
  1516.                     //'parentTemplate' => $parentTemplate,
  1517.                     //'childTemplate' => $childTemplate,
  1518.                         )
  1519.         );
  1520.     }
  1521.     public function caseDetailOverview(Request $request) {
  1522.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  1523.         $showNew $request->get("new");
  1524.         $openNew $request->get("open");
  1525.         $id $request->get("id");
  1526.         $holdOpen $request->get("holdOpen",0);
  1527.         $dialogueId$request->get("dialogueId");
  1528.         $isCprLookupActive $this->container->getParameter('isCprLookupActive');
  1529.         $user $this->get('security.token_storage')->getToken()->getUser();
  1530.         $session $request->getSession();
  1531.         if($dialogueId){
  1532.             $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  1533.             $em $this->getDoctrine()->getManager();
  1534.             $dialogue $em->getRepository(Dialogue::class)->find($dialogueId);
  1535.             $patient $em->getRepository(Patient::class)->find($dialogue->getPatient()->getId());
  1536.             $dialogue->setUpdatedAt(new \DateTime());
  1537.             $em->persist($dialogue);
  1538.             $em->flush();
  1539.             $dal = new DialogueAccessLog();
  1540.             $dal->createdBy $this->get('security.token_storage')->getToken()->getUser();
  1541.             $dal->setCreatedAt(new \DateTime());
  1542.             $dal->dialogue $dialogue;
  1543.             $em->persist($dal);
  1544.             $em->flush();
  1545.             $session $request->getSession();
  1546.             //$em->detach($patient);
  1547.             //$em->detach($dialogue);
  1548.             $selectedPatient $session->set("selectedPatient"$patient);
  1549.             $selectedDialogue $session->set("selectedDialogue"$dialogue);
  1550.             $selectedPatient $patient;
  1551.             $selectedDialogue $selectedPatient;
  1552.             
  1553.             if($dialogue->getDialogueType() == || $dialogue->getDialogueType() == 2){
  1554.                 if(!$session->get('waitingListCount',false)){
  1555.                     $measureList $em->getRepository(DialogueCaseCardMeasure::class)->fetchMeasuresWithStatusAfventer($patient->getId());
  1556.                     $waitingList $em->getRepository(JoGroupWaitinglist::class)->fetchWaitingListFOrPatient($patient->getId());
  1557.                     $waitingListCount count($measureList) + count($waitingList);
  1558.                     $session->set('waitingListCount',$waitingListCount,false);
  1559.                 }
  1560.                 
  1561.                 $log $this->checkAccessDialogOfDeceased($dialogue$user$patient );
  1562.             }
  1563.             //Get rental default listing
  1564.             $defaultRentalList $em->getRepository(RbRental::class)->getDefaultRentalList($patient);
  1565.             $session->set("rentalItemCnt"count($defaultRentalList));
  1566.             
  1567.             $getLatestJoCaseComments $em->getRepository(JoCaseComments::class)->getLatestJoCaseComments($dialogue,$user);
  1568.             $isReadAllComments 'true';
  1569.             foreach($getLatestJoCaseComments as $joCaseCommentObj) {
  1570.                 $joCaseCommentsLogObj $em->getRepository(JoCaseCommentsLog::class)->findOneBy(array('JoCaseComments' => $joCaseCommentObj'User' => $user));
  1571.                 if(!$joCaseCommentsLogObj) {
  1572.                     $isReadAllComments 'false';
  1573.                     break;
  1574.                 }
  1575.             }
  1576.             //$session->set("caseCommentsCount", count($getLatestJoCaseComments));
  1577.             $session->set("isReadAllComments"$isReadAllComments);
  1578.             if($isReadAllComments === 'false') {
  1579.                 return $this->redirectToRoute('case_comment_overview');
  1580.             }
  1581.             
  1582.             $myHuskeseddelReminder $em->getRepository(JoCaseMemos::class)->getMemosReminderForUser($dialogue $user);
  1583.             $session->set("myHuskeseddelReminderCount"count($myHuskeseddelReminder));
  1584.             $myMemo $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue $user);
  1585.             $session->set("myMemoCount"count($myMemo));
  1586.         }
  1587.         
  1588.         $em $this->getDoctrine()->getManager();
  1589.         $session $request->getSession();
  1590.         $selectedPatient $session->get("selectedPatient"false);
  1591.         $selectedDialogue $session->get("selectedDialogue"false);
  1592.         $user $this->get('security.token_storage')->getToken()->getUser();
  1593.         $womenExist $menExist $bothExist false;
  1594.         $womenArray $menArray $addedRelations = array();
  1595.         //var_dump($selectedPatient); die;
  1596.         if (!$selectedPatient) {
  1597.             return $this->redirect($this->generateUrl('index'));
  1598.         }
  1599.         $patientObj $em->getRepository(Patient::class)->find($selectedPatient->getId());
  1600.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  1601.         $patientFamilyObj $em->getRepository(Family::class)->findBy(array('patient' => $patientObj));
  1602.         $cpr $patientObj->getCpr();
  1603.         $getFullDate $this->getBirthDate($cpr);
  1604.         $bdateYear date_format($getFullDate"d.m.Y");
  1605.         $dateDiff $this->getUserAge($bdateYear);
  1606.         
  1607.         $getComments $em->getRepository(JoCaseComments::class)->getLatestJoCaseComments($dialogue,$user);
  1608.         $session->set("caseCommentsCount"count($getComments));
  1609.         $getLatestJoCaseMemos $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue,$user);
  1610.         $session->set("caseMemoCount",count($getLatestJoCaseMemos));
  1611.         $getLatestJoCaseMemosReminder $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($dialogue,$user);
  1612.         //var_dump($selectedDialogue); die;
  1613.         $searchFilter "ROLE_DTS";
  1614.         if ($user->hasRole('ROLE_CSV')) {
  1615.             $searchFilter "ROLE_CSV";
  1616.         }
  1617.         //if($dialogue->getDialogueType() == 1 || $dialogue->getDialogueType() == 2 ) {
  1618.             $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForIndividual' => 1));
  1619.         //} else {
  1620.             //$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => 1));
  1621.         //}
  1622.         
  1623.         $joGroupObj NULL;
  1624.         if(($dialogue->getDialogueType() == || $dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_DTS" ) {
  1625.             $joGroupObj $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  1626.             
  1627.             //$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCardListByType($searchFilter, $joGroupObj->getJoMasterInformation()->getInfoType(), $joGroupObj->getJoMasterInformation()->getKkorg());
  1628.             $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForGroup' => 1));
  1629.         } else if(($dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_CSV" ) {
  1630.             $joGroupObj $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  1631.             $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForGroup' => 1));
  1632.         }
  1633.         
  1634.         $dialogueCaseCard = new DialogueCaseCard();
  1635.         $form $this->createForm(DialogueCaseCardType::class, $dialogueCaseCard);
  1636.         $dialogueCaseCardAll $em->getRepository(DialogueCaseCard::class)->findBy(array('dialogue' => $selectedDialogue'isClosed' => 0), array('createdAt' => 'desc')); //'toDate' => NULL
  1637.         //For select case drop down list
  1638.         $dialogueCaseCardActiveClosed $em->getRepository(DialogueCaseCard::class)->findBy(array('dialogue' => $selectedDialogue), array('createdAt' => 'desc'));
  1639.         //Closed case card listing
  1640.         $dialogueCaseCardClosed $em->getRepository(DialogueCasecardMeasure::class)->fetchClosedCaseCard($selectedDialogue);
  1641.         $userCreatedCaseCardsId = array();
  1642.         $attachmentCnt $noteCnt = array();
  1643.         foreach ($dialogueCaseCardActiveClosed as $dialogueCaseCard) {
  1644.             $userCreatedCaseCardsId[] = $dialogueCaseCard->getPCaseCardId()->getId();
  1645.             //$allAttachmentRecords = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patientObj, 'pCaseCardId' => $dialogueCaseCard->getPCaseCardId()->getId(), 'user' => $user ));
  1646.             /* $allAttachmentRecords = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patientObj, 'pCaseCardId' => $dialogueCaseCard->getPCaseCardId()->getId()));
  1647.               $attachmentCnt[$dialogueCaseCard->getPCaseCardId()->getId()] = count($allAttachmentRecords);
  1648.               $allNotesRecords = $em->getRepository(DialogueNotes::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patientObj, 'caseCard' => $dialogueCaseCard->getPCaseCardId()->getCaseCardType(), 'user' => $user));
  1649.               $noteCnt[$dialogueCaseCard->getPCaseCardId()->getId()] = count($allNotesRecords); */
  1650.         }
  1651.         
  1652.         $caseCardMeasureCount = [];
  1653.         // to show count of measures in individual case if gruppe measure is also included
  1654.         if($dialogue->getdialogueType() == '1' || $dialogue->getdialogueType() == '2'){ 
  1655.             foreach ($dialogueCaseCardAll as $caseCard) {
  1656.                 $holds = [];
  1657.                 //$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->findBy(array('DialogueCaseCard' => $caseCard->getId(), 'referenceType' => 'F'), array('searchDate' => 'desc'));
  1658.                 $dialogueCaseCardMeasureAll $em->getRepository(DialogueCaseCardMeasure::class)->getDialogueMeasuresByProfession($caseCard->getId(),$user->getProfession(),$caseCard->getPCaseCardId()->getId()); // change made for visitation
  1659.                 $queryHoldIds $em->createQuery(
  1660.                     "SELECT h FROM App\Entity\JoCaseCardHold  h
  1661.                     left join App\Entity\DialogueCaseCardMeasure dcm with dcm.id = h.measure  
  1662.                     left join App\Entity\DialogueCaseCard dcc with dcm.DialogueCaseCard = dcc.id
  1663.                     WHERE dcc.pCaseCardId = :predefinedCC and h.id IN (SELECT IDENTITY (hr.JoCaseCardHold) FROM App\Entity\HoldResponsiblePerson hr where hr.User = :patientUser and hr.responsibleType = 'GP' )" )
  1664.                     ->setParameter('predefinedCC'$caseCard->getPCaseCardId())
  1665.                     ->setParameter('patientUser'$patientObj->getUser());
  1666.                 $holdTemps $queryHoldIds->execute();
  1667.                 foreach($holdTemps as $hold) {
  1668.                     if($hold->getMeasure()->getDialogueCaseCard()->getDialogue()->getFirstJoGroup()){
  1669.                         $holds[] = $hold;
  1670.                      }
  1671.                 }
  1672.                 //var_dump($holdMeasureIds);die;
  1673.                 
  1674. //                $gruppeMeasureIds = [];
  1675. //                foreach ($holds as $hold){
  1676. //                    if($hold->getMeasure()->getDialogueCaseCard()->getPCaseCardId()->getId()  == $caseCard->getPCaseCardId()->getId() ){
  1677. //                        $gruppeMeasureIds[] = $hold->getMeasure()->getId();
  1678. //                    }
  1679. //                }
  1680. //                //var_dump($gruppeMeasureIds);die;
  1681. //                
  1682. //                $dialogueCaseCardMeasureAllQuery = $em->createQuery(
  1683. //                    "SELECT dcm FROM App\Entity\DialogueCaseCardMeasure  dcm
  1684. //                       where ((dcm.DialogueCaseCard = :dialogueCaseCard) or (dcm.id IN (:measureIds))) and dcm.referenceType = 'F' order by dcm.searchDate desc" )
  1685. //                    ->setParameter('dialogueCaseCard', $caseCard->getId())
  1686. //                    ->setParameter('measureIds', $gruppeMeasureIds);
  1687.                 
  1688.                 $caseCardMeasureCount[$caseCard->getId()] = count($dialogueCaseCardMeasureAll) + count($holds);
  1689.             }
  1690.         }
  1691.         
  1692.         $caseCardMeasureCountClosed = [];
  1693.         // to show count of measures in individual case if gruppe measure is also included
  1694.         if($dialogue->getdialogueType() == '1' || $dialogue->getdialogueType() == '2'){ 
  1695.             foreach ($dialogueCaseCardClosed as $caseCard) {
  1696.                 $holds = [];
  1697.                 //$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->findBy(array('DialogueCaseCard' => $caseCard->getId(), 'referenceType' => 'F'), array('searchDate' => 'desc'));
  1698.                 $dialogueCaseCardMeasureAll $em->getRepository(DialogueCaseCardMeasure::class)->getDialogueMeasuresByProfession($caseCard->getId(),$user->getProfession(),$caseCard->getPCaseCardId()->getId()); // change made for visitation
  1699.                 $queryHoldIds $em->createQuery(
  1700.                 "SELECT h FROM App\Entity\JoCaseCardHold  h
  1701.                 left join App\Entity\DialogueCaseCardMeasure dcm with dcm.id = h.measure  
  1702.                 left join App\Entity\DialogueCaseCard dcc with dcm.DialogueCaseCard = dcc.id
  1703.                 WHERE dcc.pCaseCardId = :predefinedCC and h.id IN (SELECT IDENTITY (hr.JoCaseCardHold) FROM App\Entity\HoldResponsiblePerson hr where hr.User = :patientUser and hr.responsibleType = 'GP' )" )
  1704.                 ->setParameter('predefinedCC'$caseCard->getPCaseCardId())
  1705.                 ->setParameter('patientUser'$patientObj->getUser());
  1706.                 $holdTemps $queryHoldIds->execute();
  1707.                 foreach($holdTemps as $hold) {
  1708.                     if($hold->getMeasure()->getDialogueCaseCard()->getDialogue()->getFirstJoGroup()){
  1709.                         $holds[] = $hold;
  1710.                      }
  1711.                 }
  1712.                 $caseCardMeasureCountClosed[$caseCard->getId()] = count($dialogueCaseCardMeasureAll) + count($holds);
  1713.             }
  1714.         }
  1715.         //When a case has been created and the create new case card is activated – the case card that is related to the user logged in should be selected as default in the drop down so the user doesn't have to select it them selves.
  1716.         /* $userDefaultSelectedCC = array();
  1717.           //&& ( count($userCreatedCaseCardsId) == 0 )
  1718.           if(!is_null($user->getProfession())){
  1719.           $userProfession = substr($user->getProfession(), 0 , 3);
  1720.           $userDefaultSelectedCC = $em->getRepository(PredefinedCaseCard::class)->userDefaultSelectedCC($searchFilter, $userProfession);
  1721.           } */
  1722.         $records $em->getRepository(DialogueAttachmentDetails::class)->getCaseCardRecordCount($selectedDialogue->getId(), $selectedPatient->getId(), $user);
  1723.         $finalCnt = array();
  1724.         foreach ($records as $record) {
  1725.             $pcaseId $record['pCaseCardId'];
  1726.             $finalCnt[$pcaseId] = $record['count'];
  1727.         }
  1728.         //When you go to a case with no case cards created yet – the add new case card bar should be open as shown here – instead of showing an empty page as it does now
  1729.         //This should both happen after you have created a new case and after you access a case from the overview with no case card created.
  1730.         if (count($dialogueCaseCardAll) <= 0) {
  1731.             $showNew "true";
  1732.         }
  1733.         foreach ($patientFamilyObj as $patientFamily) {
  1734.             if ($patientFamily->getRelation() == "1" || $patientFamily->getRelation() == "3") {
  1735.                 $womenArray $patientFamily;
  1736.                 $womenExist true;
  1737.             }
  1738.             if ($patientFamily->getRelation() == "2" || $patientFamily->getRelation() == "4") {
  1739.                 $menArray $patientFamily;
  1740.                 $menExist true;
  1741.             }
  1742.             if ($patientFamily->getRelation() == "9") {
  1743.                 if($patientFamily->getRelative()->getDeletedBy() == null){
  1744.                 $addedRelations[] = $patientFamily;
  1745.                 }
  1746.             }
  1747.         }
  1748.         if ($womenExist && $menExist) {
  1749.             $bothExist true;
  1750.         }
  1751.         /*$joGroupObj = NULL;
  1752.         if(($dialogue->getDialogueType() == 3 || $dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_DTS" ) {
  1753.             $joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  1754.             
  1755.             $predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCardListByType($searchFilter, $joGroupObj->getJoMasterInformation()->getInfoType(), $joGroupObj->getJoMasterInformation()->getKkorg());
  1756.         } else if(($dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_CSV" ) {
  1757.             $joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  1758.             $predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter, 'isForGroup' => 1));
  1759.         } else if(($dialogue->getDialogueType() == 3) && $searchFilter == "ROLE_CSV" ) {
  1760.             $joGroupObj = $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  1761.         }*/
  1762.         $groupPredefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCards($searchFilter);
  1763.         
  1764.         $areaNames $em->getRepository(JoMasterInformation::class)->getAreaNames();
  1765.         $komunneId $patientObj->getKommuneId();
  1766.         $session->set("komunneId",$komunneId);
  1767.         $viewData = array(
  1768.             'predefinedCaseCardAll' => $predefinedCaseCardAll,
  1769.             'form' => $form->createView(),
  1770.             'dialogueCaseCardAll' => $dialogueCaseCardAll,
  1771.             'caseCardMeasureCount' => $caseCardMeasureCount,
  1772.             'userCreatedCaseCardsId' => $userCreatedCaseCardsId,
  1773.             'patientObj' => $patientObj,
  1774.             'user' => $user,
  1775.             'isCprLookupActive' => $isCprLookupActive,
  1776.             'showNew' => $showNew,
  1777.             //'finalCnt' => $finalCnt,
  1778.             'finalCnt' => $finalCnt,
  1779.             'dialogueObj' => $dialogue,
  1780.             'dialogueCaseCardClosed' => $dialogueCaseCardClosed,
  1781.             'caseCardMeasureCountClosed' => $caseCardMeasureCountClosed,
  1782.             //'userDefaultSelectedCC' => $userDefaultSelectedCC,
  1783.             'womenExist' => $womenExist,
  1784.             'menExist' => $menExist,
  1785.             'bothExist' => $bothExist,
  1786.             'womenArray' => $womenArray,
  1787.             'menArray' => $menArray,
  1788.             'addedRelations' => $addedRelations,
  1789.             'openNew' => $openNew,
  1790.             'id' => $id,
  1791.             'holdOpen' => $holdOpen,
  1792.             'dateDiff' => $dateDiff,
  1793.             'joGroupObj' => $joGroupObj,
  1794.             'areaNames' => $areaNames,
  1795.             'groupPredefinedCaseCardAll' => $groupPredefinedCaseCardAll,
  1796.             'getLatestJoCaseMemosReminder' => $getLatestJoCaseMemosReminder
  1797.             //'joGroupForm' => $joGroupForm->createView(),
  1798.         );
  1799.        
  1800.         //show used matched case card on top for case card and default open casecard in indivisusal case card
  1801.         if(($dialogue->getDialogueType() == || $dialogue->getDialogueType() == 2)) {
  1802.             $matchedCaseCardTop=[];$notMatchedCaseCardBelow=[];
  1803.             foreach ($dialogueCaseCardAll as $caseCard1) {
  1804.                 if(($caseCard1->getPCaseCardId() && $user->getPredefinedCaseCard()) && ($caseCard1->getPCaseCardId()->getId() == $user->getPredefinedCaseCard()->getId())){
  1805.                     $matchedCaseCardTop[]=$caseCard1;
  1806.                 } else {
  1807.                     $notMatchedCaseCardBelow[]=$caseCard1;
  1808.                 }
  1809.             }
  1810.             if($openNew == false){
  1811.                 $dialogueCaseCardAll array_merge($matchedCaseCardTop,$notMatchedCaseCardBelow);
  1812.             }
  1813.             if($dialogueCaseCardAll){
  1814.                 $ccId=$dialogueCaseCardAll[0]->getId();
  1815.                 
  1816.                 if($ccId !="") {
  1817.                     $dialogueCaseCardObj $em->getRepository(DialogueCaseCard::class)->find($ccId);
  1818.                     $session->set("dccId"$dialogueCaseCardObj->getId());
  1819.                     $pCaseCardId $dialogueCaseCardObj->getPCaseCardId()->getId();
  1820.                     $dialogueCaseCardControllerObj  = new DialogueCaseCardController();
  1821.                     $dialogueCaseCardData $dialogueCaseCardControllerObj->defaultContentForCaseCard($request,$em,$user,$ccId);
  1822.                     $dialogueCaseCardMeasureControllerObj  = new DialogueCaseCardMeasureController();
  1823.                     $dialogueCaseCardMeasureData $dialogueCaseCardMeasureControllerObj->getDefaultDialogueCaseCardMeasure($request,$em,$user,$pCaseCardId);
  1824.                     
  1825.                     $viewData['dialogueCaseCardObj'] = $dialogueCaseCardObj;
  1826.                     $viewData['ccId'] = $ccId;
  1827.                     $viewData['pCaseCardId'] = $pCaseCardId ;
  1828.                     $viewData['dialogueCaseCardAll'] = $dialogueCaseCardAll;
  1829.                     $viewData['dialogueCaseCardMeasureAll'] = $dialogueCaseCardMeasureData['dialogueCaseCardMeasureAll'];
  1830.                     $viewData['allSkabelonRecords'] = $dialogueCaseCardData['allSkabelonRecords'];
  1831.                     $viewData['recordCount'] = $dialogueCaseCardData['recordCount'];
  1832.                     $viewData['casecardMeasureAll'] = $dialogueCaseCardMeasureData['casecardMeasureAll'];
  1833.                     $viewData['caseCardMeasureTypeAll'] = $dialogueCaseCardMeasureData['caseCardMeasureTypeAll'];
  1834.                     $viewData['casecardMeasureFormAll'] = $dialogueCaseCardMeasureData['casecardMeasureFormAll'];
  1835.                     $viewData['caseCardStatusAll'] = $dialogueCaseCardMeasureData['caseCardStatusAll'];
  1836.                     $viewData['holds'] = $dialogueCaseCardMeasureData['holds'];
  1837.                     $viewData['holdCountList'] = $dialogueCaseCardMeasureData['holdCountList'];
  1838.                     $viewData['patientAge'] = $dateDiff;
  1839.                     $viewData['combo1'] = $dialogueCaseCardMeasureData['combo1'];
  1840.                     $viewData['combo2'] =  $dialogueCaseCardMeasureData['combo2'];
  1841.                     $viewData['inactiveHoursArray'] =   $dialogueCaseCardMeasureData['inactiveHoursArray'];
  1842.                     $viewData['combo2'] =  $dialogueCaseCardMeasureData['combo2'];
  1843.                     $viewData['loginUser'] =  $user;
  1844.                     $viewData['isClosedCaseCard'] = $dialogueCaseCardMeasureData['isClosedCaseCard'];
  1845.                     $viewData['orderBy'] = $dialogueCaseCardMeasureData['orderBy'];
  1846.                 }
  1847.             }
  1848.         }
  1849.         //$joGroup = new JoGroup();
  1850.         //$joGroupForm = $this->createForm(JoGroupType::class, $joGroup);
  1851.         
  1852.         //for maintain log for case no when click name of patient on index page 
  1853.         if($dialogue->getdialogueType() == || $dialogue->getdialogueType() == 4){
  1854.             $this->maintaineUserLog($em,$user,$dialogue->getCaseNo(),'','','','','','');
  1855.         }
  1856.         return $this->render("default/caseDetailOverview.html.twig"$viewData);
  1857.     }
  1858.     public function getBirthDate($cpr) {
  1859.         $d intval(substr($cpr02));
  1860.         $m intval(substr($cpr22));
  1861.         $today_obj = new \DateTime();
  1862.         $currentYear $today_obj->format('y');
  1863.         //$y = intval((intval(substr($this->cpr, 6, 1)) < 5 ? "19" : "20") . substr($this->cpr, 4, 2));
  1864.         //$y = intval((intval(substr($cpr, 4, 2)) <= $currentYear ? "20" : "19") . substr($cpr, 4, 2));
  1865.         $digit intval(substr($cpr61));
  1866.         $digit56 intval(substr($cpr42));
  1867.         $y = ((($digit >=&& $digit<=3) || (($digit == || $digit == 9) && ($digit56 36))) ? "19" "20").substr($cpr42);
  1868.         $tstamp mktime(nullnullnull$m$d$y);
  1869.         return $tstamp == false null : new \DateTime('@' $tstamp);
  1870.     }
  1871.     public function getUserAge($bdate) {
  1872.         //$bday = new \DateTime('02.11.1986'); // Your date of birth d.m.Y
  1873.         $bday = new \DateTime($bdate); // Your date of birth d.m.Y
  1874.         $today = new \Datetime(date('m.d.y'));
  1875.         $diff $today->diff($bday);
  1876.         return $diff;
  1877.         //printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
  1878.     }
  1879.     public function addNote(Request $request) {
  1880.         $em $this->getDoctrine()->getManager();
  1881.         $caseCard $request->get('caseCard');
  1882.         $headingNote trim($request->get('headingNote'));
  1883.         $selectDate $request->get('selectDateNote');
  1884.         $reminderDate $request->get('reminderDate');
  1885.         $noteText trim($request->get('noteText'));
  1886.         $isDraft $request->get('isDraft');
  1887.         $visibleStatus $request->get('visibleStatus');
  1888.         //$patient = $em->getRepository(Patient::class)->find(1);
  1889.         //$dialogue = $em->getRepository(Dialogue::class)->find(1);
  1890.         //$user = $em->getRepository(User::class)->find(1);
  1891.         $session $request->getSession();
  1892.         $selectedPatient $session->get("selectedPatient"false);
  1893.         $selectedDialogue $session->get("selectedDialogue"false);
  1894.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  1895.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  1896.         //$user = $em->getRepository(User::class)->find(1);
  1897.         $user $this->get('security.token_storage')->getToken()->getUser();
  1898.         $dialogueNotes = new DialogueNotes();
  1899.         $dialogueNotes->setPatient($patient);
  1900.         $dialogueNotes->setDialogue($dialogue);
  1901.         if ($selectDate != "") {
  1902.             $dialogueNotes->setNoteDate(new \DateTime($selectDate));
  1903.         }
  1904.         if ($reminderDate != "") {
  1905.             $dialogueNotes->setReminderDate(new \DateTime($reminderDate));
  1906.         }
  1907.         $dialogueNotes->setNoteText($noteText);
  1908.         $dialogueNotes->setCaseCard($caseCard);
  1909.         $dialogueNotes->setNoteHeading($headingNote);
  1910.         $dialogueNotes->setUser($user);
  1911.         $dialogueNotes->setIsDraft($isDraft);
  1912.         $dialogueNotes->setVisibleStatus($visibleStatus);
  1913.         $em->persist($dialogueNotes);
  1914.         $em->flush();
  1915.         // return "success";
  1916.         $responce "success";
  1917.         return new Response($responce);
  1918.         // echo "here";die;
  1919.     }
  1920.     public function editView(Request $request) {
  1921.         $em $this->getDoctrine()->getManager();
  1922.         $dataId $request->get('dataId');
  1923.         //$grpCreater = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $dataId));
  1924.         $grpCreater $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $dataId));
  1925.         return $this->render("default/editView.html.twig", array('grpCreater' => $grpCreater));
  1926.     }
  1927.     
  1928.     public function editTemplateStatusView(Request $request) {
  1929.         $em $this->getDoctrine()->getManager();
  1930.         $dataId $request->get('dataId');
  1931.         //$grpCreater = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $dataId));
  1932.         $grpCreater $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $dataId));
  1933.         return $this->render("default/edittemplateStatusView.html.twig", array('grpCreater' => $grpCreater));
  1934.     }
  1935.     public function editNote(Request $request) {
  1936.         $em $this->getDoctrine()->getManager();
  1937.         $selectedNote $request->get('selectedNote');
  1938.         $caseCard $request->get('caseCard');
  1939.         $headingNote trim($request->get('headingNote'));
  1940.         $selectDate $request->get('selectDateNote');
  1941.         $reminderDate $request->get('reminderDate');
  1942.         $noteText trim($request->get('noteText'));
  1943.         $isDraft $request->get('isDraft');
  1944.         $visibleStatus $request->get('visibleStatus');
  1945.         //$patient = $em->getRepository(Patient::class)->find(1);
  1946.         //$dialogue = $em->getRepository(Dialogue::class)->find(1);
  1947.         //$user = $em->getRepository(User::class)->find(1);
  1948.         $session $request->getSession();
  1949.         $selectedPatient $session->get("selectedPatient"false);
  1950.         $selectedDialogue $session->get("selectedDialogue"false);
  1951.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  1952.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  1953.         $user $this->get('security.token_storage')->getToken()->getUser();
  1954.         $dialogueNotes $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $selectedNote));
  1955.         $dialogueNotes->setPatient($patient);
  1956.         $dialogueNotes->setDialogue($dialogue);
  1957.         if ($selectDate != "") {
  1958.             $dialogueNotes->setNoteDate(new \DateTime($selectDate));
  1959.         }
  1960.         if ($reminderDate != "") {
  1961.             $dialogueNotes->setReminderDate(new \DateTime($reminderDate));
  1962.         }
  1963.         $dialogueNotes->setNoteText($noteText);
  1964.         $dialogueNotes->setCaseCard($caseCard);
  1965.         $dialogueNotes->setNoteHeading($headingNote);
  1966.         $dialogueNotes->setUser($user);
  1967.         $dialogueNotes->setIsDraft($isDraft);
  1968.         $dialogueNotes->setVisibleStatus($visibleStatus);
  1969.         $em->persist($dialogueNotes);
  1970.         $em->flush();
  1971.         $responce "success";
  1972.         return new Response($responce);
  1973.     }
  1974.     public function createDialogueCaseCard(Request $request) {
  1975.         $card = new DialogueCaseCard();
  1976.         $form $this->createForm(DialogueCaseCardType::class, $card);
  1977.         $form->handleRequest($request);
  1978.         $entityManager $this->getDoctrine()->getManager();
  1979.         $em $this->getDoctrine()->getManager();
  1980.         $session $request->getSession();
  1981.         $selectedDialgoue $session->get("selectedDialogue"false);
  1982.         if ($form->isSubmitted() && $form->isValid()) {
  1983.             $dialogueObj $em->getRepository(Dialogue::class)->find($selectedDialgoue->getId());
  1984.             $card->setPatient($dialogueObj->getPatient());
  1985.             $card->setDialogue($dialogueObj);
  1986.             $user $this->get('security.token_storage')->getToken()->getUser();
  1987.             $card->setCreatedBy($user);
  1988.             $entityManager->persist($card);
  1989.             $entityManager->flush();
  1990.             
  1991.             $dialogueCaseCardControllerObj = new DialogueCaseCardController();
  1992.             $history $dialogueCaseCardControllerObj->saveCaseCardHistory($entityManager$card'N',$dialogueObj,null$user);
  1993.             $case_detail_overview_url $this->generateUrl('case_detail_overview', array('open' => 'true'));
  1994.             return $this->redirect($case_detail_overview_url);
  1995.         }
  1996.     }
  1997.     
  1998.     public function deleteNote(Request $request) {
  1999.         $em $this->getDoctrine()->getManager();
  2000.         $selectedNote $request->get('selectedNote');
  2001.         $parentNote $request->get('parentNote');
  2002.         $user $this->get('security.token_storage')->getToken()->getUser();
  2003.         //$dialogueNotes = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $selectedNote));
  2004.         $dialogueNotes $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $selectedNote));
  2005.         if($dialogueNotes){
  2006.             foreach ($dialogueNotes->getDialogueAttachmentDetails() as $childNoteObj) {
  2007.                 if ($childNoteObj) {
  2008.                     $childNoteDeleteObj $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $childNoteObj->getId()));
  2009.                     $em->remove($childNoteDeleteObj);
  2010.                     $em->flush();
  2011.                 }
  2012.             }
  2013.         }
  2014.         $em->remove($dialogueNotes);
  2015.         $em->flush();
  2016.         // $responce = "success";
  2017.         // return new Response($responce);
  2018.         $dialogueAttachmentDetails $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('id' => $parentNote));
  2019.         $i 0;
  2020.         foreach($dialogueAttachmentDetails as $dialogueAttachment)
  2021.         {
  2022.             $noteQuery $em->createQuery("SELECT dad FROM App\Entity\DialogueAttachmentDetails  dad
  2023.             WHERE  dad.parentId =:parentId order by dad.updatedAt DESC")
  2024.             ->setParameter('parentId'$dialogueAttachment->getId());
  2025.             $noteIds $noteQuery->execute();
  2026.             $dialogueAttachmentArray[$dialogueAttachment->getId()] = $noteIds;
  2027.         $i++;
  2028.         }
  2029.         
  2030.         return $this->render("default/dialogueNoteAttachmentDetailsUpdated.html.twig", array(
  2031.             'dialogueAttachmentArray' => $dialogueAttachmentArray,
  2032.             'dialogueAttachmentDetails' => $dialogueAttachmentDetails,
  2033.             'user' => $user
  2034.         ));
  2035.     }
  2036.     public function loadDialogue(Request $request$id,$detailviewId) {
  2037.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  2038.         $isRentalSystemAccessible $this->container->getParameter('isRentalSystemAccessible');
  2039.         $em $this->getDoctrine()->getManager();
  2040.         $session $request->getSession();
  2041.         $user $this->get('security.token_storage')->getToken()->getUser();
  2042.         $session->set("isRentalSystemAccessible"$isRentalSystemAccessible true false);
  2043.         $dialogue $em->getRepository(Dialogue::class)->find($id);
  2044.         $postMailControllerObj = new PostMailController();
  2045.         $userRoleType $user->hasRole('ROLE_CSV') ? : ($user->hasRole('ROLE_DTS') ? 0);
  2046.         $userRoleTypeText $user->hasRole('ROLE_CSV') ? 'ROLE_CSV' : ($user->hasRole('ROLE_DTS') ? 'ROLE_DTS' 0);
  2047.         $patient $em->getRepository(Patient::class)->find($dialogue->getPatient()->getId());
  2048.         if($patient->getUserAge()  != $patient->getChildAge()){
  2049.             if($patient->getIsFakeCpr() != '1'){
  2050.                 $patient->setChildAge($patient->getUserAge());
  2051.             }
  2052.             $em->persist($patient);
  2053.             $em->flush();
  2054.         }
  2055.         $dialogue->setUpdatedAt(new \DateTime());
  2056.         $dialougeType $dialogue->getDialogueType();
  2057.         if(($dialougeType == or $dialougeType == 2) && ($dialogue->getCaseNo() == NULL || $dialogue->getCaseNo() == '9001000') ) {
  2058.             $dialogue->setCaseNo($dialogue->getUniqueCaseNumber());
  2059.         } else if(($dialougeType == or $dialougeType == 4) && ($dialogue->getCaseNo() == NULL) ) {
  2060.             $dialogue->setCaseNo($dialogue->getUniqueGroupNumber());
  2061.         }
  2062.         $em->persist($dialogue);
  2063.         if($dialougeType == or $dialougeType == 2) {
  2064.             $dal = new DialogueAccessLog();
  2065.             $dal->createdBy $this->get('security.token_storage')->getToken()->getUser();
  2066.             $dal->setCreatedAt(new \DateTime());
  2067.             $dal->dialogue $dialogue;
  2068.             $em->persist($dal);
  2069.             
  2070.             $log $this->checkAccessDialogOfDeceased($dialogue$user$patient);
  2071.         }
  2072.         
  2073.         //update phone number from nordjurrs
  2074.         $this->addFlash("updateParentPhone"true);
  2075.         //for maintain log for case no when click name of patient on index page 
  2076.         $this->maintaineUserLog($em,$user,$dialogue->getCaseNo(),'','','','','','');
  2077.         //create dialougecase card details
  2078.         $dialogueCaseCardObj $this->createDefaultDialougeCaseCard($user,$patient,$dialogue);
  2079.         $saveMeasure $this->createMeasureOnLoad($dialogueCaseCardObj,$user);
  2080.         //create default skelering activity
  2081.         $checkForSkeleringobjs $em->getRepository(DialogueAttachmentDetails::class)->checkSkeleringActivity($dialogue$patient);
  2082.         //echo count($checkForSkelering)."\n".$dialogue->getId()."".$patient->getId();
  2083.         //die;
  2084.         if(count($checkForSkeleringobjs)==0){
  2085.             $checkForSkelerings $em->getRepository(DialogueAttachmentDetails::class)->checkSkeleringActivityTrash($dialogue$patient);
  2086.             if($checkForSkelerings){
  2087.                 foreach ($checkForSkelerings as $skeleringActivity) {
  2088.                     $dialogueAttachmentDetailsObj $em->getRepository(DialogueAttachmentDetails::class)->find($skeleringActivity['id']);
  2089.                     foreach ($dialogueAttachmentDetailsObj->getScalingProgressions() as $progressionObj) {
  2090.                         if ($progressionObj) {
  2091.                             $graphObjs $em->getRepository(ScalingGraph::class)->findBy(array('progression' => $progressionObj->getId()));
  2092.                             foreach($graphObjs as $graphObj){
  2093.                                 if($graphObj){
  2094.                                     $em->remove($graphObj);
  2095.                                     $em->flush();
  2096.                                 }
  2097.                             }
  2098.                             $em->remove($progressionObj);
  2099.                             $em->flush();
  2100.                         }
  2101.                     }
  2102.                     $em->remove($dialogueAttachmentDetailsObj);
  2103.                     $em->flush();
  2104.                 }
  2105.             }
  2106.             $skeleringObj $this->createSkelringCaseActivity($user,$patient,$dialogue,$dialogueCaseCardObj);
  2107.         }
  2108.         $isSavedAsActivity false;
  2109.         $getNotSavedAsActivityPostMails $em->getRepository(JoPostMail::class)->getNotSavedAsActivityPostMails($isSavedAsActivity$dialogue);
  2110.         //$predefinedCaseCardObj = $em->getRepository(PredefinedCaseCard::class)->getFirstPreCaseCardByUserType($userRoleTypeText);
  2111.         //$postMailControllerObj->createReminderActivityAsPostMail($request, $em, $user, $predefinedCaseCardObj, $patient, $dialogue, $getNotSavedAsActivityPostMails);
  2112.         $session->set("postMailCnt"count($getNotSavedAsActivityPostMails));
  2113.         
  2114.         //$getLatestJoCaseCommentsCount = $em->getRepository(JoCaseComments::class)->getLatestJoCaseCommentsCount($dialogue);
  2115.         //$session->set("caseCommentsCount", $getLatestJoCaseCommentsCount);
  2116.         $getLatestJoCaseComments $em->getRepository(JoCaseComments::class)->getLatestJoCaseComments($dialogue,$user);
  2117.         $isReadAllComments 'true';
  2118.         foreach($getLatestJoCaseComments as $joCaseCommentObj) {
  2119.             $joCaseCommentsLogObj $em->getRepository(JoCaseCommentsLog::class)->findOneBy(array('JoCaseComments' => $joCaseCommentObj'User' => $user));
  2120.             if(!$joCaseCommentsLogObj) {
  2121.                 $isReadAllComments 'false';
  2122.                 break;
  2123.             }
  2124.         }
  2125.         $getLatestJoCaseMemos $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue,$user);
  2126.         $getLatestSentJoCaseMemos $em->getRepository(JoCaseMemos::class)->getLatestSentJoCaseMemos($dialogue,$user);
  2127.         $getLatestJoCaseMemosReminder $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemosReminder($dialogue,$user);
  2128.         $session->set("caseCommentsCount"count($getLatestJoCaseComments));
  2129.         $session->set("caseMemoCount",count($getLatestJoCaseMemos));
  2130.         $session->set("isReadAllComments"$isReadAllComments);
  2131.         $komunneIdsArray = array(
  2132.                         '101' => 'København',
  2133.                         '147' => 'Frederiksberg',
  2134.                         '151' => 'Ballerup',
  2135.                         '153' => 'Brøndby',
  2136.                         '155' => 'Dragør',
  2137.                         '157' => 'Gentofte',
  2138.                         '159' => 'Gladsaxe',
  2139.                         '161' => 'Glostrup',
  2140.                         '163' => 'Herlev',
  2141.                         '165' => 'Albertslund',
  2142.                         '167' => 'Hvidovre',
  2143.                         '169' => 'Høje-Taastrup',
  2144.                         '173' => 'Lyngby-Taarbæk',
  2145.                         '175' => 'Rødovre',
  2146.                         '183' => 'Ishøj',
  2147.                         '185' => 'Tårnby',
  2148.                         '187' => 'Vallensbæk',
  2149.                         '190' => 'Furesø',
  2150.                         '201' => 'Allerød',
  2151.                         '210' => 'Fredensborg',
  2152.                         '217' => 'Helsingør',
  2153.                         '219' => 'Hillerød',
  2154.                         '223' => 'Hørsholm',
  2155.                         '230' => 'Rudersdal',
  2156.                         '240' => 'Egedal',
  2157.                         '250' => 'Frederikssund',
  2158.                         '253' => 'Greve',
  2159.                         '259' => 'Køge',
  2160.                         '260' => 'Halsnæs',
  2161.                         '265' => 'Roskilde',
  2162.                         '269' => 'Solrød',
  2163.                         '270' => 'Gribskov',
  2164.                         '306' => 'Odsherred',
  2165.                         '316' => 'Holbæk',
  2166.                         '320' => 'Faxe',
  2167.                         '326' => 'Kalundborg',
  2168.                         '329' => 'Ringsted',
  2169.                         '330' => 'Slagelse',
  2170.                         '336' => 'Stevns',
  2171.                         '340' => 'Sorø',
  2172.                         '350' => 'Lejre',
  2173.                         '360' => 'Lolland',
  2174.                         '370' => 'Næstved',
  2175.                         '376' => 'Guldborgsund',
  2176.                         '390' => 'Vordingborg',
  2177.                         '400' => 'Bornholm',
  2178.                         '410' => 'Middelfart',
  2179.                         '411' => 'Christiansø',
  2180.                         '420' => 'Assens',
  2181.                         '430' => 'Faaborg-Midtfyn',
  2182.                         '440' => 'Kerteminde',
  2183.                         '450' => 'Nyborg',
  2184.                         '461' => 'Odense',
  2185.                         '479' => 'Svendborg',
  2186.                         '480' => 'Nordfyns',
  2187.                         '482' => 'Langeland',
  2188.                         '492' => 'Ærø',
  2189.                         '510' => 'Haderslev',
  2190.                         '530' => 'Billund',
  2191.                         '540' => 'Sønderborg',
  2192.                         '550' => 'Tønder',
  2193.                         '561' => 'Esbjerg',
  2194.                         '563' => 'Fanø',
  2195.                         '573' => 'Varde',
  2196.                         '575' => 'Vejen',
  2197.                         '580' => 'Aabenraa',
  2198.                         '607' => 'Fredericia',
  2199.                         '615' => 'Horsens',
  2200.                         '621' => 'Kolding',
  2201.                         '630' => 'Vejle',
  2202.                         '657' => 'Herning',
  2203.                         '661' => 'Holstebro',
  2204.                         '665' => 'Lemvig',
  2205.                         '671' => 'Struer',
  2206.                         '706' => 'Syddjurs',
  2207.                         '707' => 'Norddjurs',
  2208.                         '710' => 'Favrskov',
  2209.                         '727' => 'Odder',
  2210.                         '730' => 'Randers',
  2211.                         '740' => 'Silkeborg',
  2212.                         '741' => 'Samsø',
  2213.                         '746' => 'Skanderborg',
  2214.                         '751' => 'Aarhus',
  2215.                         '756' => 'Ikast-Brande',
  2216.                         '760' => 'Ringkøbing-Skjern',
  2217.                         '766' => 'Hedensted',
  2218.                         '773' => 'Morsø',
  2219.                         '779' => 'Skive',
  2220.                         '787' => 'Thisted',
  2221.                         '791' => 'Viborg',
  2222.                         '810' => 'Brønderslev',
  2223.                         '813' => 'Frederikshavn',
  2224.                         '820' => 'Vesthimmerlands',
  2225.                         '825' => 'Læsø',
  2226.                         '840' => 'Rebild',
  2227.                         '846' => 'Mariagerfjord',
  2228.                         '849' => 'Jammerbugt',
  2229.                         '851' => 'Aalborg',
  2230.                         '860' => 'Hjørring');
  2231.                 $komunneId $patient->getKommuneId();
  2232.                 //var_dump($komunneId);
  2233.                 if (array_key_exists($komunneId,$komunneIdsArray)) {
  2234.                     $session->set("komunneName"$komunneIdsArray[$komunneId]);
  2235.                     $session->set("komunneId",$komunneId);
  2236.                 }else if($patient->getIsDummyPatient()) {
  2237.                     $session->set("komunneName""Københavns");
  2238.                     $session->set("komunneId",0);
  2239.                 } else {
  2240.                     $session->set("komunneName""");
  2241.                     $session->set("komunneId","");
  2242.                 }
  2243.                 
  2244.         //update ALL data in stamdata first time a case is opened on a given day
  2245.         if($patient && !($patient->getIsDummyPatient()) && !($patient->getIsFakeCpr())) {
  2246.             $nextStamdataCallDateObj $patient->getNextStamdataCall();
  2247.             if(!is_null($nextStamdataCallDateObj)){
  2248.                 $nextStamdataCallDate $nextStamdataCallDateObj->format('d-m-Y');
  2249.             }
  2250.             
  2251.             $todayDate = new \DateTime();
  2252.             $todayDateFormatted $todayDate->format('d-m-Y');
  2253.             $tomorrowDate = new \DateTime('+6 days');
  2254.             $tomorrowDateFormatted $tomorrowDate->format('d-m-Y');
  2255.             //var_dump($nextStamdataCallDate, $todayDateFormatted); die;
  2256.             //var_dump(is_null($nextStamdataCallDate), strtotime($todayDateFormatted) , strtotime($nextStamdataCallDate) ); die;
  2257.             
  2258.             if(is_null($nextStamdataCallDateObj) || (strtotime($nextStamdataCallDate) <= strtotime($todayDateFormatted))) {
  2259.                 
  2260.                 $userProfession $user->getProfession();
  2261.                 if($userProfession){  // update user profession in pcascecard field
  2262.                     if (strpos($userProfession',') !== false) {
  2263.                         $userProfession substr($userProfession0strpos($userProfession","));
  2264.                     }
  2265.                     
  2266.                     if(strlen($userProfession) > 5){
  2267.                        $userProfession substr($userProfession0, -3);
  2268.                     }
  2269.                    
  2270.                     $userRole "ROLE_DTS";
  2271.                     if ($user->hasRole('ROLE_CSV')) {
  2272.                         $userRole "ROLE_CSV";
  2273.                     }
  2274.                     $userDefaultSelectedCC $em->getRepository(PredefinedCaseCard::class)->userDefaultSelectedCC($userRoletrim($userProfession));
  2275.                     
  2276.                     if($userDefaultSelectedCC){
  2277.                         $user->setPredefinedCaseCard($userDefaultSelectedCC);
  2278.                         $em->persist($user);
  2279.                         $em->flush();
  2280.                     }
  2281.                 }
  2282.                 
  2283.                 // $this->updateAllStamdata($patient, $session);
  2284.                 //Update citizen school and institude information from IST_ELEV and IST_ELEV_UDV entity
  2285.                 $this->updateStamdataISTElevData($patient$session);
  2286.                 
  2287.                 //var_Dump($tomorrowDateFormatted, $tomorrowDate); die;
  2288.                 //$patient->setNextStamdataCall($tomorrowDate);
  2289.                 $em->persist($patient);
  2290.             }
  2291.         }
  2292.         
  2293.         $em->flush();
  2294.         
  2295.         //$type = "1";
  2296.         //$message = "Amol Is so smart";
  2297.         //$notificationObj = $this->setNotificationData($em, $dialogue, $user, $type, $message);
  2298.         //$notificationLogObj = $this->setNotificationLogData($em, $dialogue, $user, $notificationObj);
  2299.         
  2300.         $em->detach($patient);
  2301.         $em->detach($dialogue);
  2302.         $selectedPatient $session->set("selectedPatient"$patient);
  2303.         $selectedDialogue $session->set("selectedDialogue"$dialogue);
  2304.         $session->set("isJoGroupExist"false);
  2305.         $session->set("selectedJoGroup"null);
  2306.         
  2307.         if($dialogue->getDialogueType() == || $dialogue->getDialogueType() == 2){
  2308.             $measureList $em->getRepository(DialogueCaseCardMeasure::class)->fetchMeasuresWithStatusAfventer($patient->getId());
  2309.             $waitingList $em->getRepository(JoGroupWaitinglist::class)->fetchWaitingListFOrPatient($patient->getId());
  2310.             $waitingListCount count($measureList) + count($waitingList);
  2311.             $session->set('waitingListCount',$waitingListCount,false);
  2312.         }
  2313.         
  2314.         //Get rental default listing
  2315.         $defaultRentalList $em->getRepository(RbRental::class)->getDefaultRentalList($patient);
  2316.         $session->set("rentalItemCnt"count($defaultRentalList));
  2317.         
  2318.         $myHuskeseddelReminder $em->getRepository(JoCaseMemos::class)->getMemosReminderForUser($dialogue $user);
  2319.         $session->set("myHuskeseddelReminderCount"count($myHuskeseddelReminder));
  2320.         
  2321.         $myMemo $em->getRepository(JoCaseMemos::class)->getLatestJoCaseMemos($dialogue $user);
  2322.         $session->set("myMemoCount"count($myMemo));
  2323.         if($isReadAllComments === 'false') {
  2324.             return $this->redirectToRoute('case_comment_overview');
  2325.         }
  2326.         
  2327.         if($detailviewId) {
  2328.             $isMemo explode("me_",$detailviewId);
  2329.             if(count($isMemo) === 2) {
  2330.                 if (strpos($isMemo[1], '_sent') !== false) {
  2331.                     $session->set("openSentMemo"true);
  2332.                 }
  2333.                 return $this->redirectToRoute('case_memo_overview');
  2334.             }
  2335.             return $this->redirectToRoute('case_detail_view',['detailviewId' => $detailviewId]);
  2336.         } else {
  2337.             return $this->redirectToRoute('case_detail_view');
  2338.         }
  2339.     }
  2340.     
  2341.     public function checkAccessDialogOfDeceased ($dialogue$user$patient  ){
  2342.         $em $this->getDoctrine()->getManager();
  2343.         $this->addFlash("citizenDeceased"'');
  2344.         $this->addFlash("parentDeceased"'');
  2345.         //for Citizen deceased
  2346.         if($patient->getIsDeceased() == 1){
  2347.             $JoPatientIsdeceasedLog $em->getRepository(JoPatientIsdeceasedLog::class)->findBy(array('dialogue' => $dialogue'loggedUser' => $user'User' => $patient->getUser()));
  2348.             if(!$JoPatientIsdeceasedLog){
  2349.                 //$session->set("citizenDeceased", $patient->getDeceaseDate()->format('d-m-Y'));
  2350.                 $this->addFlash("citizenDeceased"$patient->getDeceaseDate()->format('d-m-Y'));
  2351.                 $newJoPatientIsdeceasedLog = new JoPatientIsdeceasedLog();
  2352.                 $newJoPatientIsdeceasedLog->setDialogue($dialogue);
  2353.                 $newJoPatientIsdeceasedLog->setLoggedUser($user);
  2354.                 $newJoPatientIsdeceasedLog->setUser($patient->getUser());
  2355.                 $em->persist($newJoPatientIsdeceasedLog);
  2356.                 $em->flush();
  2357.             }
  2358.         }
  2359.         //for Parents deceased
  2360.         $patientFamilyObj $em->getRepository(Family::class)->findBy(array('patient' => $patient));
  2361.         foreach ($patientFamilyObj as $patientFamily) {
  2362.             if ($patientFamily->getRelation() == "1" || $patientFamily->getRelation() == "2" || $patientFamily->getRelation() == "3" || $patientFamily->getRelation() == "4") {
  2363.                 if($patientFamily->getIsDeceased() == 1){
  2364.                     $JoPatientIsdeceasedLog $em->getRepository(JoPatientIsdeceasedLog::class)->findBy(array('dialogue' => $dialogue'loggedUser' => $user'User' => $patientFamily->getRelative()));
  2365.                     if(!$JoPatientIsdeceasedLog){
  2366.                         //$session->set("parentDeceased", $patientFamily->getDeceaseDate()->format('d-m-Y'));
  2367.                         $this->addFlash("parentDeceased"$patientFamily->getDeceaseDate()->format('d-m-Y'));
  2368.                         $newJoPatientIsdeceasedLog = new JoPatientIsdeceasedLog();
  2369.                         $newJoPatientIsdeceasedLog->setDialogue($dialogue);
  2370.                         $newJoPatientIsdeceasedLog->setLoggedUser($user);
  2371.                         $newJoPatientIsdeceasedLog->setUser($patientFamily->getRelative());
  2372.                         $em->persist($newJoPatientIsdeceasedLog);
  2373.                         $em->flush();
  2374.                         break;
  2375.                     }
  2376.                 }
  2377.             }
  2378.         }
  2379.         
  2380.         return true;
  2381.     }
  2382.     public function deleteView(Request $request) {
  2383.         $em $this->getDoctrine()->getManager();
  2384.         $dataId $request->get('dataId');
  2385.         //$grpCreater = $em->getRepository(DialogueNotes::class)->findOneBy(array("id" => $dataId));
  2386.         $grpCreater $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array("id" => $dataId));
  2387.         return $this->render("default/deleteView.html.twig", array('grpCreater' => $grpCreater));
  2388.     }
  2389.     public function editStamdataProfile(Request $request$familyId) {
  2390.         $em $this->getDoctrine()->getManager();
  2391.         $user $this->get('security.token_storage')->getToken()->getUser();
  2392.         $session $request->getSession();
  2393.         $childRelation $request->get('childRelation');
  2394.         $selectedPatient $session->get("selectedPatient"false);
  2395.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  2396.         $familyDetails $em->getRepository(Family::class)->find($familyId);
  2397.         
  2398.         if($this->get('security.authorization_checker')->isGranted('ROLE_PARENT')) {
  2399.             return $this->render("dialogue/citizen-edit-stamdata-profile.html.twig", array('familyDetails' => $familyDetails'patientObj' => $patient'childRelation' => $childRelation));
  2400.         }else{
  2401.             return $this->render("dialogue/edit-stamdata-profile.html.twig", array('familyDetails' => $familyDetails'patientObj' => $patient'childRelation' => $childRelation));
  2402.         }
  2403.     }
  2404.     public function saveStamdataProfile(Request $request$userId) {
  2405.         $em $this->getDoctrine()->getManager();
  2406.         $session $request->getSession();
  2407.         $loginUser $this->get('security.token_storage')->getToken()->getUser();
  2408.         $selectedPatient $session->get("selectedPatient"false);
  2409.         $selectedDialogue $session->get("selectedDialogue"false);
  2410.         $responce 'fail';
  2411.         $motherTongue $request->get('mother_tongue');
  2412.         $phoneNo1 $request->get('phoneno1');
  2413.         $phoneNo2 $request->get('phoneno2');
  2414.         $phoneNo3 $request->get('phoneno3');
  2415.         $smsOne $request->get('smsOne');
  2416.         $smsTwo $request->get('smsTwo');
  2417.         $smsThree $request->get('smsThree');
  2418.         $needTranslator $request->get('needTranslator');
  2419.         $secretAddress $request->get('secretAddress');
  2420.         $oralConsentDate $request->get('oralConsentDate');
  2421.         $oralConsentText $request->get('oralConsentText');
  2422.         $isSecretNumber $request->get('isSecretNumber',null);
  2423.         $isSecretNumber2 $request->get('isSecretNumber2',null);
  2424.         $dialogue NULL;
  2425.         $mobile_1_code trim($request->get('mobile_1_code'));
  2426.         if(strlen($mobile_1_code) > && $phoneNo1 !=""){
  2427.             $phoneNo1 $mobile_1_code.'-'.$phoneNo1;
  2428.         }
  2429.         
  2430.         $mobile_2_code trim($request->get('mobile_2_code'));
  2431.         if(strlen($mobile_2_code) > && $phoneNo2 !=""){
  2432.             $phoneNo2 $mobile_2_code.'-'.$phoneNo2;
  2433.         }
  2434.         //echo $motherTongue.", ".$phoneNo.", ".$needTranslator.", ".$secretAddress.", ";die;
  2435.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  2436.         $userObj $em->getRepository(User::class)->find($userId);
  2437.         if($selectedDialogue){
  2438.             $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  2439.         }
  2440.         //var_dump($userObj);die;
  2441.         if($motherTongue){
  2442.             $userObj->setNativeLanguage($motherTongue);
  2443.         }
  2444.         //if($phoneNo1){
  2445.             $userObj->setmobileNo($phoneNo1);
  2446.         //}
  2447.        // if($phoneNo2){
  2448.             $userObj->setmobileNo2($phoneNo2);
  2449.        // }
  2450.         //if($phoneNo3){
  2451.             $userObj->setmobileNo3($phoneNo3);
  2452.        // }
  2453.         //if($smsOne){
  2454.             $userObj->setSmsOne($smsOne);
  2455.         //}
  2456.         //if($smsTwo){
  2457.             $userObj->setSmsTwo($smsTwo);
  2458.         //}
  2459.         if($smsThree){
  2460.             $userObj->setSmsThree($smsThree);
  2461.         }
  2462.         //if($needTranslator){
  2463.             $userObj->setTranslate($needTranslator);
  2464.         //}
  2465.         //if($secretAddress){
  2466.             $userObj->setIsSecretAddress($secretAddress);
  2467.         //}
  2468.         //if($isSecretNumber){
  2469.             $userObj->setIsSecretNumber($isSecretNumber);
  2470.         //}
  2471.             $userObj->setIsSecretNumber2($isSecretNumber2);
  2472.         $em->persist($userObj);
  2473.         $em->flush();
  2474.         $familyObj $em->getRepository(Family::class)->findOneBy(array("relative" => $userObj'patient' => $patient));
  2475.         if ($oralConsentDate != '') {
  2476.             $oralConsentDate = new \DateTime($oralConsentDate);
  2477.             $familyObj->setOralConsentDate($oralConsentDate);
  2478.         } else {
  2479.             $familyObj->setOralConsentDate(null);
  2480.         }
  2481.         if ($oralConsentText != '') {
  2482.             $familyObj->setOralConsentText($oralConsentText);
  2483.         } else {
  2484.             $familyObj->setOralConsentText('');
  2485.         }
  2486.         
  2487.         //Save oral consent record in dialogue multiple attachement table to send the ebook message
  2488.         $patientOralConsentText trim($familyObj->getOralConsentText());
  2489.         if(isset($dialogue)){
  2490.         $dialogueAttachmentObj $em->getRepository(DialogueMultipleAttachment::class)->findOneBy(array('patient' => $patient'dialogue' => $dialogue'isOralConsent' => true'oralConsentGivenBy' => $userObj));
  2491.         if ((!$dialogueAttachmentObj) && strlen($patientOralConsentText) > && isset($dialogue)) {
  2492.             $dialogueAttachmentObj = new DialogueMultipleAttachment();
  2493.             $dialogueAttachmentObj->setPatient($patient);
  2494.             $dialogueAttachmentObj->setDialogue($dialogue);
  2495.             $dialogueAttachmentObj->setUser($loginUser);
  2496.             $dialogueAttachmentObj->setAttachmentName(NULL);
  2497.             $dialogueAttachmentObj->setOriginalName(NULL);
  2498.             $dialogueAttachmentObj->setIsDeleted(false);
  2499.             $dialogueAttachmentObj->setIsDefault(true);
  2500.             $dialogueAttachmentObj->setSequenceNumber(0);
  2501.             $dialogueAttachmentObj->setIsOralConsent(1);
  2502.             $dialogueAttachmentObj->setOralConsentGivenBy($userObj);
  2503.             $em->persist($dialogueAttachmentObj);
  2504.             $em->flush();
  2505.         }
  2506.         }
  2507.         
  2508.         //update phone number in nordjurrs
  2509.         $NotatController = new NotatWorkFlowController();
  2510.         $updateParentPhone $NotatController->updateParentPhoneInNorddjurs($em,$patient,$phoneNo1,$phoneNo2,$familyObj->getRelation(),$this->container);
  2511.         $em->persist($familyObj);
  2512.         $em->flush();
  2513.         $this->updatePatientDate($patient);
  2514.         $patient->setUpdatedBy($loginUser);
  2515.         $em->persist($patient);
  2516.         $em->flush();
  2517.         $responce 'success';
  2518.         $response = new Response(json_encode(array('result' => $responce)));
  2519.         $response->headers->set('Content-Type''application/json');
  2520.         return $response;
  2521.     }
  2522.     public function searchCaseOverview(Request $request) {
  2523.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  2524.         $em $this->getDoctrine()->getManager();
  2525.         $session $request->getSession();
  2526.         $selectedPatient $session->get("selectedPatient"false);
  2527.         $selectedDialogue $session->get("selectedDialogue"false);
  2528.         //var_dump($selectedPatient->getId(), $selectedDialogue->getId()); die;
  2529.         if (!$selectedPatient) {
  2530.             return $this->redirect($this->generateUrl('index'));
  2531.         }
  2532.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  2533.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  2534.         //$user = $em->getRepository(User::class)->find(1);
  2535.         $user $this->get('security.token_storage')->getToken()->getUser();
  2536.         $patient $dialogue->getPatient();
  2537.         $session->set("selectedDialogue"$dialogue);
  2538.         $session->set("selectedPatient"$patient);
  2539.         //Search filter paramenters
  2540.         $searchByTypeHeading trim($request->get('searchByTypeHeading'));
  2541.         $filtercasecardids trim($request->get('filtercasecardids'));
  2542.         $filterstatusids trim($request->get('filterstatusids'));
  2543.         $filtertypeids trim($request->get('filtertypeids'));
  2544.         $filterfromdate trim($request->get('filterfromdate'));
  2545.         $filtertodate trim($request->get('filtertodate'));
  2546.         $filteruserid trim($request->get('filteruserid'));
  2547.         $filterbyyearly trim($request->get('filterbyyearly'));
  2548.         $filterByQuarter trim($request->get('filterByQuarter'));
  2549.         //$selectedDialogue = $dialogue;
  2550.         //$cpr = "111111";
  2551.         $cpr $patient->getCpr();
  2552.         $getFullDate $this->getBirthDate($cpr);
  2553.         $bdateYear date_format($getFullDate"d.m.Y");
  2554.         $dateDiff $this->getUserAge($bdateYear);
  2555.         $sortBy $request->get('sortBy');
  2556.         $orderBy $request->get('orderBy');
  2557.         $showFutureActivities $request->get('showFutureActivities');
  2558.         
  2559.         $searchFilter "ROLE_DTS";
  2560.         if ($user->hasRole('ROLE_CSV')) {
  2561.             $searchFilter "ROLE_CSV";
  2562.         }
  2563.         $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForIndividual' => 1));
  2564.         
  2565.         $predefinedCaseCardAllIds = array();
  2566.         $joPredefinedCaseCardObj $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'josa_rapport'));
  2567.         if($joPredefinedCaseCardObj){
  2568.             $predefinedCaseCardAllIds[] = $joPredefinedCaseCardObj->getId();
  2569.         }
  2570.         $joPredefinedCaseCardObj $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'Sagsgrundlag'));
  2571.         if($joPredefinedCaseCardObj){
  2572.             $predefinedCaseCardAllIds[] = $joPredefinedCaseCardObj->getId();
  2573.         }
  2574.         
  2575.         $joGroupObj NULL;
  2576.         if(($dialogue->getDialogueType() == || $dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_DTS" ) {
  2577.             $joGroupObj $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  2578.             
  2579.             //$predefinedCaseCardAll = $em->getRepository(PredefinedCaseCard::class)->fetchGroupPredefinedCaseCardListByType($searchFilter, $joGroupObj->getJoMasterInformation()->getInfoType(), $joGroupObj->getJoMasterInformation()->getKkorg());
  2580.             $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForGroup' => '1'));
  2581.         } else if(($dialogue->getDialogueType() == 4) && $searchFilter == "ROLE_CSV" ) {
  2582.             $joGroupObj $em->getRepository(JoGroup::class)->findOneBy(array('Dialogue' => $dialogue));
  2583.             $predefinedCaseCardAll $em->getRepository(PredefinedCaseCard::class)->findBy(array('userType' => $searchFilter'isForGroup' => 1));
  2584.         }
  2585.         //$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findAll();
  2586.         //$predefinedAttachmentType = $em->getRepository(PredefinedAttachmentType::class)->findById(array(1, 2, 3, 4, 6, 9, 11,12));
  2587.         $predefinedAttachmentType $em->getRepository(PredefinedAttachmentType::class)->findBy(array('isActivityType' => 1), array('orderBy' => 'asc'));
  2588.         $dialogueCaseCardAll $em->getRepository(DialogueCaseCard::class)->findBy(array('dialogue' => $selectedDialogue));
  2589.         $userCreatedCaseCardsId $userCreatedDialogueCaseCard = array();
  2590.         foreach ($dialogueCaseCardAll as $dialogueCaseCard) {
  2591.             $userCreatedCaseCardsId[] = $dialogueCaseCard->getPCaseCardId()->getId();
  2592.             $userCreatedDialogueCaseCard[$dialogueCaseCard->getPCaseCardId()->getId()] = $dialogueCaseCard->getId();
  2593.         }
  2594.         //Delete DialogueAttachmentDetails activity if no borgerplan is attached to this
  2595.         $checkActivityNotAttachedToEventsCnt $em->getRepository(DialogueAttachmentDetails::class)->checkActivityNotAttachedToEventsCnt($dialogue$user);
  2596.         if(count($checkActivityNotAttachedToEventsCnt) > 0) {
  2597.             foreach($checkActivityNotAttachedToEventsCnt as $dialogueAttachmentDetail) {
  2598.                 if($dialogueAttachmentDetail){
  2599.                     $JoCaseCardEventBrevActivityObj $em->getRepository(JoCaseCardEventBrevActivity::class)->findOneBy(array('attachmentDetails' => $dialogueAttachmentDetail));
  2600.                     if($JoCaseCardEventBrevActivityObj){
  2601.                         $em->remove($JoCaseCardEventBrevActivityObj);
  2602.                         $em->flush();
  2603.                     }
  2604.                     $em->remove($dialogueAttachmentDetail);
  2605.                     $em->flush();
  2606.                 }
  2607.             }
  2608.         }
  2609.         if ($user->hasRole('ROLE_PARENT')) {
  2610.             $activitySharing $em->getRepository(JoActivitySharing::class)->findOneBy(array('dialogue' => $dialogue));
  2611.             if($activitySharing){
  2612.                 $loggedInUser $session->get("loggedInUser");
  2613.                 if($loggedInUser){  // for cpr and cvr users who have multiple entries in user table
  2614.                     $user $em->getRepository(User::class)->find($loggedInUser->getId());
  2615.                 }
  2616.                 //$dialogueAttachmentDetailIds = $activitySharing->getLoggedInCitizenActivitiesForDialog($user);
  2617.                 $activitySharingParticipant $em->getRepository(JoActivitySharingParticipant::class)->findOneBy(array('joActivitySharing' => $activitySharing'user' => $user));
  2618.                 if($activitySharingParticipant){
  2619.                     $dialogueAttachmentDetailIds $activitySharingParticipant->getLoggedInCitizenActivitiesForDialog();
  2620.                 }else{
  2621.                     $dialogueAttachmentDetailIds = array();
  2622.                 }
  2623.             }else{
  2624.                 $dialogueAttachmentDetailIds = array();
  2625.             }
  2626.         }else{
  2627.             $dialogueAttachmentDetailIds = array();
  2628.         }
  2629.         $update_skalering $this->updateSkaleringAttachment($dialogue,$patient,$em);
  2630.         //$dialogueAttachmentDetails = $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('dialogue' => $dialogue, 'patient' => $patient),array('attachmentDate' => 'desc'));
  2631.         $dialogueAttachmentFilter $em->getRepository(DialogueAttachmentDetails::class)->filterDialogueAttachmentDetails($dialogue$patient$searchByTypeHeading$filtercasecardids$filterstatusids$filtertypeids$filterfromdate$filtertodate$filteruserid$filterbyyearly$filterByQuarter,$sortBy,$orderBy ,$dialogueAttachmentDetailIds$showFutureActivities$user );
  2632.         $dialogueAttachmentDetails $dialogueAttachmentFilter['result'];
  2633.         $futureActivitiesCount $dialogueAttachmentFilter['futureActivitiesCount'];
  2634.         $relatedRecordsDetails = [];
  2635.         $isAttachmentDateUpdated false;
  2636.         $tunnelshareActivity=array();
  2637.         foreach ($dialogueAttachmentDetails as $attachmentDetailObj) {
  2638.             if ($sortBy == 'measureName') {
  2639.                 $attachmentDetailObj $attachmentDetailObj[0];
  2640.             }
  2641.             if ($attachmentDetailObj->getPAtttachmentType()->getId() == 8) {
  2642.                 foreach ($attachmentDetailObj->getJoCaseCardEvents() as $eventObj) {
  2643.                     $eventStartAt strtotime($eventObj->getStartAt()->format('Y-m-d'));
  2644.                     $currentDate strtotime("now");
  2645.                     if(strtotime($attachmentDetailObj->getAttachmentDate()->format('Y-m-d')) != strtotime($eventObj->getStartAt()->format('Y-m-d')) ) {
  2646.                         if ($eventStartAt $currentDate) {
  2647.                             $attachmentDetailObj->setAttachmentDate($eventObj->getStartAt());
  2648.                             $em->persist($attachmentDetailObj);
  2649.                             $em->flush();
  2650.                             $isAttachmentDateUpdated true;
  2651.                         }else if($dialogue->getDialogueType() == || $dialogue->getDialogueType() == 4){
  2652.                             $attachmentDetailObj->setAttachmentDate($eventObj->getStartAt());
  2653.                             $em->persist($attachmentDetailObj);
  2654.                             $em->flush();
  2655.                             $isAttachmentDateUpdated true;
  2656.                         }
  2657.                     }
  2658.                     
  2659.                     if($attachmentDetailObj->getPatient()->getUser() != NULL && $attachmentDetailObj->getPatient()->getUser()->getId() == $patient->getUser()->getId()){
  2660.                     $relatedRecords $em->getRepository(JoCaseCardEvent::class)->findChildIndividualDialogEventList($dialogue,$eventObj->getDialogueCaseCard(),$eventObj->getDialogueCaseCardMeasure(),$eventObj->getHeading(),$eventObj->getEventCollection());
  2661.                     if(count($relatedRecords) > ){
  2662.                     $relatedRecordsDetails[$attachmentDetailObj->getId()]['index'] = array_search($eventObj$relatedRecords) + 1;
  2663.                     $relatedRecordsDetails[$attachmentDetailObj->getId()]['count'] = count$relatedRecords);
  2664.                     $min $relatedRecords[0];
  2665.                     for ($i 1$i count($relatedRecords); $i++)
  2666.                         if ($relatedRecords[$i]->getId() < $min->getId())
  2667.                             $min $relatedRecords[$i];
  2668.                     $relatedRecordsDetails[$attachmentDetailObj->getId()]['link_id'] =  $min->getId();
  2669.                     }
  2670.                     }
  2671.                 }
  2672.             }
  2673.             $tunnelRid$attachmentDetailObj->getTunnelListId();
  2674.             if($tunnelRid){
  2675.                 $tunnelDetailsObj $em->getRepository(SepoTunnelliste::class)->findOneBy(array('rid' => $tunnelRid));
  2676.                 if($tunnelDetailsObj){
  2677.                     $tunnelshareActivity[$tunnelRid]=  array('name' =>  $tunnelDetailsObj->getName());
  2678.                 }
  2679.             }
  2680.         }
  2681.         if($isAttachmentDateUpdated){
  2682.             $dialogueAttachmentFilter $em->getRepository(DialogueAttachmentDetails::class)->filterDialogueAttachmentDetails($dialogue$patient$searchByTypeHeading$filtercasecardids$filterstatusids$filtertypeids$filterfromdate$filtertodate$filteruserid$filterbyyearly$filterByQuarter,$sortBy,$orderBy$dialogueAttachmentDetailIds$showFutureActivities$user );
  2683.             $dialogueAttachmentDetails $dialogueAttachmentFilter['result'];
  2684.             $futureActivitiesCount $dialogueAttachmentFilter['futureActivitiesCount'];
  2685.         }
  2686.         
  2687.         $dialogueAttachments $em->getRepository(DialogueAttachments::class)->findBy(array('dialogue' => $dialogue'patient' => $patient));
  2688.         /*$dialogueAttachments = $em->createQuery(
  2689.                                     "SELECT dad FROM App\Entity\DialogueAttachmentDetails dad
  2690.                      where (dad.deletedBy IS NULL) and (dad.dialogue = :dialogue and dad.patient = :patient) and dad.isPostMailActivity = 0
  2691.                     order by dad.$sortBy " . $orderBy)
  2692.                             ->setParameter('dialogue', $dialogue)
  2693.                             ->setParameter('patient', $patient);*/
  2694.         $dialogueAttachmentFileName = array();
  2695.         foreach ($dialogueAttachments as $dialogueAttachment) {
  2696.             $id $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
  2697.             $dialogueAttachmentFileName[$id]['files'][] = $dialogueAttachment;
  2698.         }
  2699.         $webPath '/public/uploads/attachments/'//$this->get('kernel')->getProjectDir() . 
  2700.         //var_dump($dialogueAttachmentFileName); die;
  2701.         $dialogueNotes $em->getRepository(DialogueNotes::class)->findBy(array('dialogue' => $dialogue'patient' => $patient));
  2702.         //fetch all DialogueCaseCardMeasure related to ccId
  2703.         //$dialogueCaseCardMeasureAll = $em->getRepository(DialogueCaseCardMeasure::class)->findBy(array('referenceType' => 'F'));
  2704.         $dialogueCaseCardMeasureAll $em->getRepository(DialogueCaseCardMeasure::class)->fetchMeasureTilDate('F',new \DateTime(),$user->getProfession());
  2705.         $holdList $em->getRepository(JoCaseCardHold::class)->findAll();
  2706.         $brevActivityEvent = array();
  2707.         $checkBrevActivityDetails $em->getRepository(DialogueAttachmentDetails::class)->checkBrevActivityEvent($dialogue,$patient);
  2708.         foreach ($checkBrevActivityDetails as $brevActivity) {
  2709.             $brevActivityEvent[$brevActivity['id']]=  array('eventId' => $brevActivity['eventId'],
  2710.                 'heading' =>  $brevActivity['heading'],
  2711.             );
  2712.         }
  2713.         $i 0;
  2714.         foreach($dialogueAttachmentDetails as $dialogueAttachment)
  2715.         {
  2716.             $noteQuery $em->createQuery("SELECT dad FROM App\Entity\DialogueAttachmentDetails  dad
  2717.             WHERE  dad.parentId =:parentId order by dad.updatedAt DESC")
  2718.             ->setParameter('parentId'$dialogueAttachment->getId());
  2719.             $noteIds $noteQuery->execute();
  2720.             $dialogueAttachmentArray[$dialogueAttachment->getId()] = $noteIds;
  2721.         $i++;
  2722.         }
  2723.         return $this->render("default/dialogueNoteAttachmentDetails.html.twig", array(
  2724.                     'dateDiff' => $dateDiff,
  2725.                     'dialogueNotes' => $dialogueNotes,
  2726.                     'dialogueCaseCardAll' => $dialogueCaseCardAll,
  2727.                     'predefinedCaseCardAll' => $predefinedCaseCardAll,
  2728.                     'userCreatedCaseCardsId' => $userCreatedCaseCardsId,
  2729.                     'patientObj' => $patient,
  2730.                     'user' => $user,
  2731.                     'dialogue' => $dialogue,
  2732.                     'predefinedAttachmentType' => $predefinedAttachmentType,
  2733.                     'dialogueAttachmentDetails' => $dialogueAttachmentDetails,
  2734.                     'holdList' => $holdList,
  2735.                     'relatedRecordsDetails' => $relatedRecordsDetails,
  2736.                     'dialogueAttachmentFileName' => $dialogueAttachmentFileName,
  2737.                     'webPath' => $webPath,
  2738.                     'dialogueObj' => $dialogue,
  2739.                     'userCreatedDialogueCaseCard' => $userCreatedDialogueCaseCard,
  2740.                     'fromOverview' => 1,
  2741.                     'dialogueCaseCardMeasureAll' => $dialogueCaseCardMeasureAll,
  2742.                     'futureActivitiesCount' => $futureActivitiesCount,
  2743.                     'sortBy' => $sortBy,
  2744.                     'isFromFilter' => true,
  2745.                     'brevActivityEvent' => $brevActivityEvent,
  2746.                     'dialogueAttachmentArray' => $dialogueAttachmentArray
  2747.                         )
  2748.         );
  2749.     }
  2750.     public function editChildProfile(Request $request$childId) {
  2751.         //echo 'editChildProfile call';die;
  2752.         $em $this->getDoctrine()->getManager();
  2753.         $user $this->get('security.token_storage')->getToken()->getUser();
  2754.         $travelText = array();
  2755.         $session $request->getSession();
  2756.         $selectedPatient $session->get("selectedPatient"false);
  2757.         $childInfo $em->getRepository(User::class)->find($childId);
  2758.         $currentDateTime strtotime("now");
  2759.         $patientInfo $em->getRepository(Patient::class)->findOneBy(array('user' => $childId));
  2760.         $patientTravelInfo $em->getRepository(TravelNeedsDetails::class)->findBy(array('patient' => $selectedPatient));
  2761.         if (count($patientTravelInfo) > 0) {
  2762.             foreach ($patientTravelInfo as $text) {
  2763.                 $travelText[] = $text->getTravelNeedsText();
  2764.             }
  2765.         }
  2766.         $needTextObj = new TravelNeedsDetails();
  2767.         $patientTravelNeedsDetails_session $session->get('needTravelInfo');
  2768. //        var_dump($patientTravelNeedsDetails_session);die;
  2769.         if (!is_null($patientTravelNeedsDetails_session)) {
  2770.             $patientTravelInfo = [];
  2771.             foreach ($patientTravelNeedsDetails_session as $key => $travelInfo) {
  2772.                 $travelObj = [];
  2773.                 $travelObj['travelNeedId'] = $key;
  2774.                 $travelObj['travelNeedsText'] = $travelInfo['name'];
  2775.                 $travelObj['travelNeedsFromDate'] = new \DateTime($travelInfo['fromDate']);
  2776.                 $travelObj['travelNeedsToDate'] = new \DateTime($travelInfo['toDate']);
  2777.                 array_push($patientTravelInfo$travelObj);
  2778.             }
  2779.         }
  2780.         $needTextOptions $needTextObj::$travelNeedStrings;
  2781.         //var_dump($patientTravelInfo);die;
  2782.         $patientCoreAreas $em->getRepository(PredefinedTravelsType::class)->findBy(array('status'=>'1'));
  2783.         if($this->get('security.authorization_checker')->isGranted('ROLE_PARENT')) {
  2784.             return $this->render("dialogue/citizen-edit-child-profile.html.twig", array('childInfo' => $childInfo'patientInfo' => $patientInfo'patientTravelInfo' => $patientTravelInfo'needTextOptions' => $needTextOptions'travelText' => $travelText'currentDateTime' => $currentDateTime,'patientCoreAreas'=>$patientCoreAreas));
  2785.         }else{
  2786.             return $this->render("dialogue/edit-child-profile.html.twig", array('childInfo' => $childInfo'patientInfo' => $patientInfo'patientTravelInfo' => $patientTravelInfo'needTextOptions' => $needTextOptions'travelText' => $travelText'currentDateTime' => $currentDateTime,'patientCoreAreas'=>$patientCoreAreas));
  2787.         }
  2788.         
  2789.     }
  2790.     
  2791.     public function deleteChildProfileOralConsent(Request $request$childId){
  2792.         $em $this->getDoctrine()->getManager();
  2793.         $userObj $em->getRepository(User::class)->find($childId);
  2794.         $patientObj $em->getRepository(Patient::class)->findOneBy(array('user' => $userObj));
  2795.         
  2796.         $patientObj->setOralConsentText(NULL);
  2797.         $patientObj->setOralConsentDate(NULL);
  2798.         
  2799.         $em->persist($patientObj);
  2800.         $em->flush();
  2801.         
  2802.         $responce 'success';
  2803.         $response = new Response(json_encode(array('result' => $responce)));
  2804.         $response->headers->set('Content-Type''application/json');
  2805.         return $response;
  2806.     }
  2807.     
  2808.     public function deleteStamdataProfileOralConsent(Request $request$userId){
  2809.         $em $this->getDoctrine()->getManager();
  2810.         $session $request->getSession();
  2811.         $selectedPatient $session->get("selectedPatient"false);
  2812.         $userObj $em->getRepository(User::class)->find($userId);
  2813.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  2814.         
  2815.         $familyObj $em->getRepository(Family::class)->findOneBy(array("relative" => $userObj'patient' => $patient));
  2816.         $familyObj->setOralConsentDate(NULL);
  2817.         $familyObj->setOralConsentText(NULL);
  2818.         
  2819.         $em->persist($familyObj);
  2820.         $em->flush();
  2821.         $responce 'success';
  2822.         $response = new Response(json_encode(array('result' => $responce)));
  2823.         $response->headers->set('Content-Type''application/json');
  2824.         return $response;
  2825.     }
  2826.     public function saveChildProfile(Request $request$childId) {
  2827.         $responce 'fail';
  2828.         $motherTongue $request->get('mother_tongue');
  2829.         $phoneNo $request->get('phoneno');
  2830.         $phoneNo2 $request->get('phoneno2');
  2831.         $phoneNo3 $request->get('phoneno3');
  2832.         $smsOne $request->get('smsOne');
  2833.         $smsTwo $request->get('smsTwo');
  2834.         $smsThree $request->get('smsThree');
  2835.         $needTranslator $request->get('needTranslator');
  2836.         $secretAddress $request->get('secretAddress');
  2837.         $em $this->getDoctrine()->getManager();
  2838.         $userObj $em->getRepository(User::class)->find($childId);
  2839.         $session $request->getSession();
  2840.         $selectedDialogue $session->get("selectedDialogue"null);
  2841.         $isSecretNumber $request->get('isSecretNumber');
  2842.         $isSecretNumber2 $request->get('isSecretNumber2');
  2843.         $needTravelInfo $request->get('needTravelInfo');
  2844.         $patientCoreArea $request->get('patientCoreArea');
  2845.         $patientCoreSubArea $request->get('patientCoreSubArea');
  2846.         $user $this->get('security.token_storage')->getToken()->getUser();
  2847.         
  2848.         $mobile_1_code trim($request->get('mobile_1_code'));
  2849.         if(strlen($mobile_1_code) > && $phoneNo !=""){
  2850.             $phoneNo $mobile_1_code.'-'.$phoneNo;
  2851.         }
  2852.         
  2853.         $mobile_2_code trim($request->get('mobile_2_code'));
  2854.         if(strlen($mobile_2_code) > && $phoneNo2 !=""){
  2855.             $phoneNo2 $mobile_2_code.'-'.$phoneNo2;
  2856.         }
  2857.         
  2858.         $tt $request->get('isSecretNumber');
  2859.         if ($selectedDialogue) {
  2860.             $selectedDialogue $em->getRepository(Dialogue::class)->find($selectedDialogue);
  2861.         }
  2862.         $user $this->get('security.token_storage')->getToken()->getUser();
  2863.         $patientObj $em->getRepository(Patient::class)->findOneBy(array('user' => $userObj));
  2864.         $patient_dialogue $em->getRepository(Dialogue::class)->findOneBy(array('patient' => $patientObj));
  2865.         $oralConsentText trim($request->get('oralConsent'));
  2866.         $oralConsentDate $request->get('oralconsentselectdate');
  2867.         $travelNeedsText $request->get('travelneedsselecttotext');
  2868.         $travelNeedsFromDate $request->get('travelneedsselectfromdate');
  2869.         $travleNeedsToDate $request->get('travelneedsselecttodate');
  2870.         $consentdatechanged $request->get('oralconsentdatechanged');
  2871.         $patientObj->setOralConsentText($oralConsentText);
  2872.         if ($oralConsentDate != "") {
  2873.             $patientObj->setOralConsentDate(new \DateTime($oralConsentDate));
  2874.         } else {
  2875.             $patientObj->setOralConsentDate(NULL);
  2876.         }
  2877.         
  2878.         //Save oral consent record in dialogue multiple attachement table to send the ebook message
  2879.         $patientOralConsentText trim($patientObj->getOralConsentText());
  2880.         $dialogueAttachmentObj $em->getRepository(DialogueMultipleAttachment::class)->findOneBy(array('patient' => $patientObj'dialogue' => $selectedDialogue'isOralConsent' => true'oralConsentGivenBy' => $userObj));
  2881.         if ((!$dialogueAttachmentObj) && strlen($patientOralConsentText) > && isset($selectedDialogue) ) {
  2882.             $dialogueAttachmentObj = new DialogueMultipleAttachment();
  2883.             $dialogueAttachmentObj->setPatient($patientObj);
  2884.             $dialogueAttachmentObj->setDialogue($selectedDialogue);
  2885.             $dialogueAttachmentObj->setUser($user);
  2886.             $dialogueAttachmentObj->setAttachmentName(NULL);
  2887.             $dialogueAttachmentObj->setOriginalName(NULL);
  2888.             $dialogueAttachmentObj->setIsDeleted(false);
  2889.             $dialogueAttachmentObj->setIsDefault(NULL);
  2890.             $dialogueAttachmentObj->setSequenceNumber(NULL);
  2891.             $dialogueAttachmentObj->setIsOralConsent(1);
  2892.             $dialogueAttachmentObj->setOralConsentGivenBy($userObj);
  2893.             $em->persist($dialogueAttachmentObj);
  2894.             $em->flush();
  2895.         }
  2896.             
  2897.         if ($user->hasRole('ROLE_CSV')) {
  2898.             $selectedTravelNeeds $em->getRepository(TravelNeedsDetails::class)->findBy(array('patient' => $patientObj'dialogue' => $selectedDialogue));
  2899.             foreach ($selectedTravelNeeds as $stn) {
  2900.                 $em->remove($stn);
  2901.                 $em->flush();
  2902.             }
  2903.             /* $patientObj->setTravelNeedsText($travelNeedsText);
  2904.               if($travelNeedsFromDate != ""){
  2905.               $patientObj->setTravelNeedsFromDate(new \DateTime($travelNeedsFromDate));
  2906.               }
  2907.               if($travleNeedsToDate != ""){
  2908.               $patientObj->setTravleNeedsToDate(new \DateTime($travleNeedsToDate));
  2909.               } */
  2910.             if($patientCoreArea && $patientCoreSubArea){
  2911.                 $patientCoreAreaObj $em->getRepository(PredefinedTravelsType::class)->find($patientCoreArea);
  2912.                 $patientCoreSubAreaObj $em->getRepository(PredefinedTravelsType::class)->find($patientCoreSubArea);
  2913.                 $patientObj->setPatientCoreArea($patientCoreAreaObj);
  2914.                 $patientObj->setPatientSubCoreArea($patientCoreSubAreaObj);
  2915.             }
  2916.             $em->persist($patientObj);
  2917.             $em->flush();
  2918.             if ($consentdatechanged && $patient_dialogue) {
  2919.                 $dialogueConsentInfo $em->getRepository(DialogueConsentInfo::class)->findOneBy(array('dialogue' => $patient_dialogue));
  2920.                 if (!$dialogueConsentInfo) {
  2921.                     $dialogueConsentInfo = new DialogueConsentInfo();
  2922.                 }
  2923.                 $dialogueConsentInfo->setDialogue($patient_dialogue);
  2924.                 $dialogueConsentInfo->setUser($user);
  2925.                 $em->persist($dialogueConsentInfo);
  2926.                 $em->flush();
  2927.             }
  2928.             
  2929.             $needTravelInfo_session $session->get('needTravelInfo');
  2930.             $session->set('needTravelInfo'null);
  2931. //            var_dump($selectedDialogue->getPatient()->getFirstName());die;
  2932. //            var_dump($patient_dialogue);die;
  2933.             if($patient_dialogue){
  2934.                 if (!is_null($needTravelInfo)) {
  2935.                     foreach ($needTravelInfo as $allTravelInfo) {
  2936.                     foreach ($allTravelInfo as $key => $travelInfo) {
  2937.                         $needTextObj = new TravelNeedsDetails();
  2938.                         $needTextObj->setTravelNeedsText($travelInfo['name']);
  2939.                         if ($travelInfo['fromDate'] != "") {
  2940.                             $needTextObj->setTravelNeedsFromDate(new \DateTime($travelInfo['fromDate']));
  2941.                         } else {
  2942.                             $needTextObj->setTravelNeedsFromDate(NULL);
  2943.                         }
  2944.                         if ($travelInfo['toDate'] != "") {
  2945.                             $needTextObj->setTravelNeedsToDate(new \DateTime($travelInfo['toDate']));
  2946.                         } else {
  2947.                             $needTextObj->setTravelNeedsToDate(NULL);
  2948.                         }
  2949.                         $needTextObj->setCreatedBy($user);
  2950.                         $needTextObj->setPatient($patientObj);
  2951.                         $needTextObj->setDialogue($patient_dialogue);
  2952.                         $needTextObj->setTravelNeedId($key);
  2953.                         $em->persist($needTextObj);
  2954.                         $em->flush();
  2955.                     }
  2956.                 }
  2957.             }
  2958.             }else{
  2959.                 if($needTravelInfo)
  2960.                     $session->set('needTravelInfo'$needTravelInfo);
  2961.                 if($needTravelInfo_session)
  2962.                     $session->set('needTravelInfo'$needTravelInfo_session);
  2963.             }
  2964.         }
  2965.         $this->updatePatientDate($patientObj);
  2966.         $patientObj->setUpdatedBy($user);
  2967.         $em->persist($patientObj);
  2968.         $em->flush();
  2969.         //echo $motherTongue.", ".$phoneNo.", ".$needTranslator.", ".$secretAddress.", ";die;
  2970.         //echo $oralConsentText.", ".$oralConsentDate.", ".$travelNeedsText.", ".$travelNeedsFromDate.", ".$travleNeedsToDate.", ";die;
  2971.         if($motherTongue){
  2972.             $userObj->setNativeLanguage($motherTongue);
  2973.         }
  2974.        // if($phoneNo){
  2975.             $userObj->setmobileNo($phoneNo);
  2976.        // }
  2977.        // if($phoneNo2){
  2978.             $userObj->setmobileNo2($phoneNo2);
  2979.         //}
  2980.         if($phoneNo3){
  2981.             $userObj->setmobileNo3($phoneNo3);
  2982.         }
  2983.         //if($smsOne){
  2984.             $userObj->setSmsOne($smsOne);
  2985.         //}
  2986.         //if($smsTwo){
  2987.             $userObj->setSmsTwo($smsTwo);
  2988.         //}
  2989.         if($smsThree){
  2990.             $userObj->setSmsThree($smsThree);
  2991.         }
  2992.         //if($needTranslator){
  2993.             $userObj->setTranslate($needTranslator);
  2994.         //}
  2995.         //if($secretAddress){
  2996.             $userObj->setIsSecretAddress($secretAddress);
  2997.         //}
  2998.         //if($isSecretNumber){
  2999.             $userObj->setIsSecretNumber($isSecretNumber);
  3000.         //}
  3001.         //if($isSecretNumber2){
  3002.             $userObj->setIsSecretNumber2($isSecretNumber2);
  3003.         //}
  3004.         $em->persist($userObj);
  3005.         $em->flush();
  3006.         $responce 'success';
  3007.         $response = new Response(json_encode(array('result' => $responce)));
  3008.         $response->headers->set('Content-Type''application/json');
  3009.         return $response;
  3010.     }
  3011.     public function changeCreationDate(Request $request$ccId) {
  3012.         $em $this->getDoctrine()->getManager();
  3013.         $dialogueCaseCardObj $em->getRepository(DialogueCaseCard::class)->find($ccId);
  3014.         if ('POST' === $request->getMethod()) {
  3015.             $onSelectCCcreation $request->get('onSelectCCcreation');
  3016.             if ($onSelectCCcreation != "") {
  3017.                 $dialogueCaseCardObj->setCreatedAt(new \DateTime($onSelectCCcreation));
  3018.                 $em->persist($dialogueCaseCardObj);
  3019.                 $em->flush();
  3020.                 
  3021.                 $dialogueCaseCardHistories $dialogueCaseCardObj->getDialogueCaseCardHistories();
  3022.                 if($dialogueCaseCardHistories){
  3023.                     if($dialogueCaseCardHistories[0]->getType() == 'C'){
  3024.                         $dialogueCaseCardHistory $dialogueCaseCardHistories[1];
  3025.                     }else{
  3026.                         $dialogueCaseCardHistory $dialogueCaseCardHistories[0];
  3027.                     }
  3028.                     $dialogueCaseCardHistory->setCreatedAt(new \DateTime($onSelectCCcreation));
  3029.                     $em->persist($dialogueCaseCardHistory);
  3030.                     $em->flush();
  3031.                 }
  3032.             }
  3033.         }
  3034.         return $this->render("default/changeCreationDate.html.twig", array(
  3035.                     'dialogueCaseCardObj' => $dialogueCaseCardObj,
  3036.                     'ccId' => $ccId
  3037.         ));
  3038.     }
  3039.     
  3040.     public function showUserDetails(Request $request$userId) {
  3041.         $em $this->getDoctrine()->getManager();
  3042.         $userObj$em->getRepository(User::class)->find($userId);
  3043.         
  3044.         return $this->render("default/userDetailsPopup.html.twig", array(
  3045.                     'user' => $userObj
  3046.         ));
  3047.     }
  3048.     
  3049.     public function showHistoryCasecard(Request $request$ccId) {
  3050.         $em $this->getDoctrine()->getManager();
  3051.         $dialogueCaseCardObj$em->getRepository(DialogueCaseCard::class)->find($ccId);
  3052.         $dialogueCaseCardHistories $dialogueCaseCardObj->getDialogueCaseCardHistories();
  3053.         
  3054.         return $this->render("default/showHistoryCasecard.html.twig", array(
  3055.                     'dialogueCaseCardHistories' => $dialogueCaseCardHistories
  3056.         ));
  3057.     }
  3058.     public function changeEndDate(Request $request$ccId) {
  3059.         $em $this->getDoctrine()->getManager();
  3060.         $dialogueCaseCardObj $em->getRepository(DialogueCaseCard::class)->find($ccId);
  3061.         if ('POST' === $request->getMethod()) {
  3062.             $onSelectCCcreation $request->get('onSelectCCcreation');
  3063.             if ($onSelectCCcreation != "") {
  3064.                 $dialogueCaseCardObj->setToDate(new \DateTime($onSelectCCcreation));
  3065.                 $em->persist($dialogueCaseCardObj);
  3066.                 $em->flush();
  3067.                 
  3068.                 $dialogueCaseCardHistories $dialogueCaseCardObj->getDialogueCaseCardHistories();
  3069.                 if($dialogueCaseCardHistories){
  3070.                     $dialogueCaseCardHistory $dialogueCaseCardHistories[0];
  3071.                     $dialogueCaseCardHistory->setCreatedAt(new \DateTime($onSelectCCcreation));
  3072.                     $em->persist($dialogueCaseCardHistory);
  3073.                     $em->flush();
  3074.                 }
  3075.             }
  3076.         }
  3077.         return $this->render("default/changeEndDate.html.twig", array(
  3078.                     'dialogueCaseCardObj' => $dialogueCaseCardObj,
  3079.                     'ccId' => $ccId
  3080.         ));
  3081.     }
  3082.     function updatePatientDate($patientObj) {
  3083.         $em $this->getDoctrine()->getManager();
  3084.         $patientObj->setUpdatedAt(new \DateTime());
  3085.         $em->persist($patientObj);
  3086.         $em->flush();
  3087.     }
  3088.     public function patientTravelInfo(Request $request) {
  3089.         $em $this->getDoctrine()->getManager();
  3090.         $session $request->getSession();
  3091.         $currentDateTime strtotime("now");
  3092.         $needValText $request->get('needVal');
  3093.         $needVal $request->get('needVal').'-'.$currentDateTime;
  3094.         $needText $request->get('needText').'-'.$currentDateTime;
  3095.         $needId $request->get('needId');
  3096.         $needIdDiff $request->get('needId').'-'.$currentDateTime;
  3097.         $selectedDialogue $session->get("selectedDialogue"null);
  3098.         $selectedPatient $session->get("selectedPatient"null);
  3099.         return $this->render("default/patientTravelInfo.html.twig", array(
  3100.                     'selectedDialogue' => $selectedDialogue,
  3101.                     'selectedPatient' => $selectedPatient,
  3102.                     'needVal' => $needVal,
  3103.                     'needText' => $needText,
  3104.                     'needId' => $needId,
  3105.                     'needValText' => $needValText,
  3106.                     'needIdDiff' => $needIdDiff,
  3107.                     'currentDateTime' => $currentDateTime
  3108.         ));
  3109.     }
  3110.     
  3111.     public function viewMoreRecentlyOpen(Request $request){
  3112.         $em $this->getDoctrine()->getManager();
  3113.         $session $request->getSession();
  3114.         $user $this->get('security.token_storage')->getToken()->getUser();
  3115.         $listType $request->get('listType');
  3116.         $sortBy $request->get('sortBy');
  3117.         $orderBy $request->get('orderBy');
  3118.         $isTestUser $user->getIsTestUser();
  3119.         $isDummyPatient $isTestUser 0;
  3120.         $dialogueType $user->hasRole('ROLE_CSV') ? : ($user->hasRole('ROLE_DTS') ? 0);
  3121.         $loginUserCat $user->getCategory()->getName();
  3122.         
  3123.         $loginUserInstitutions $this->loginUserInstitutions($em$user);
  3124.         $currentSelectedInstitution $session->get('selectedInstitutionId') ? $session->get('selectedInstitutionId') : $loginUserInstitutions[0];
  3125.         $loginUserGroups $this->loginUserGroups($em$user);
  3126.         $today = new \DateTime();
  3127.         $before30days $today->modify('-30 day')->format('Y-m-d');
  3128.         $recentDialoguesQuery 'SELECT dal, MAX(dal.id) as id,  max(dal.createdAt) as accessed, sig.groupname as groupName FROM App\Entity\DialogueAccessLog  dal 
  3129.                 LEFT JOIN App\Entity\Dialogue  d with dal.dialogue = d.id 
  3130.                 LEFT JOIN App\Entity\Patient p with p.id = d.patient 
  3131.                 left join App\Entity\PatientInformation pi with p.id = pi.patient
  3132.                 left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  3133.                 left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3134.                 WHERE dal.createdBy = :user AND d.deleted = false and d.status =1 and dal.createdAt >:before30days and d.dialogueType = :dialogueType  and (pi.citizenSchoolName LIKE :category or pi.citizenInstitutionName LIKE :category) and p.isDummyPatient = '.$isDummyPatient.'  and sp.institutionId in ('.$currentSelectedInstitution.') 
  3135.                 GROUP BY dal.dialogue';
  3136.         
  3137.         
  3138.         if ($sortBy != null && $orderBy != null && $listType == 'recent') {
  3139.             if ($sortBy == 'createdAt') {
  3140.                 $recentDialoguesQuery .= ' order by d.createdAt ' $orderBy
  3141.             } elseif ($sortBy == 'fullName') {
  3142.                 $recentDialoguesQuery .= ' order by p.firstName ' $orderBy
  3143.             } elseif ($sortBy == 'caseCard') {
  3144.                 $recentDialoguesQuery .= ' '
  3145.             } elseif ($sortBy == 'cpr') {
  3146.                 $recentDialoguesQuery .= ' order by p.cpr ' $orderBy
  3147.             } elseif ($sortBy == 'anchorName') {
  3148.                 $recentDialoguesQuery .= ' '
  3149.             } elseif ($sortBy == 'updatedAt') {
  3150.                 $recentDialoguesQuery .= ' order by accessed ' $orderBy
  3151.             } elseif ($sortBy == 'age') {
  3152.                 $recentDialoguesQuery .= ' order by p.childAge ' $orderBy
  3153.             } elseif ($sortBy == 'citizenInstitutionStatus') {
  3154.                 $recentDialoguesQuery .= ' order by groupName ' $orderBy
  3155.             } elseif ($sortBy == 'school') {
  3156.                 $recentDialoguesQuery .= ' '
  3157.             } elseif ($sortBy == 'gread') {
  3158.                 $recentDialoguesQuery .= ' order by d.latestGrade  ' $orderBy
  3159.             }
  3160.         } else {
  3161.             $recentDialoguesQuery .= ' ORDER BY accessed desc'
  3162.         }
  3163.         
  3164.         $recentDialogues $em->createQuery($recentDialoguesQuery)
  3165.                 ->setParameter('user'$user)
  3166.                 ->setParameter('dialogueType'$dialogueType)
  3167.                 ->setParameter('category'$loginUserCat)
  3168.                 ->setParameter('before30days',$before30days)
  3169.                 ->execute();
  3170.         //var_dump($recentDialogues) ;
  3171.         return $this->render("default/viewMoreRecentlyOpen.html.twig", array('recentDialogues' => $recentDialogues'user' => $user));
  3172.     }
  3173.     public function viewMoreMyUrgentInfo(Request $request) {
  3174.         $em $this->getDoctrine()->getManager();
  3175.         $session $request->getSession();
  3176.         $user $this->get('security.token_storage')->getToken()->getUser();
  3177.         $listType $request->get('listType');
  3178.         $sortBy $request->get('sortBy');
  3179.         $orderBy $request->get('orderBy');
  3180.         $isTestUser $user->getIsTestUser();
  3181.         $isDummyPatient $isTestUser 0;
  3182.         $dialogueType $user->hasRole('ROLE_CSV') ? : ($user->hasRole('ROLE_DTS') ? 0);
  3183.         // get all my notes whose remider date is past today 
  3184.         if ($sortBy != null && $orderBy != null && $listType == 'urgent') {
  3185.             if ($sortBy == 'createdAt') {
  3186.                 $notesPassedReminderDate $em->createQuery(
  3187.                                 'SELECT n,po.isDeleted  from App\Entity\DialogueAttachmentDetails n 
  3188.                                 left join App\Entity\Dialogue d with d.id = n.dialogue
  3189.                                 inner join App\Entity\Patient p with p.id = n.patient 
  3190.                                 left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  3191.                          where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by n.createdAt ' $orderBy)
  3192.                         ->setParameter('user'$user)
  3193.                         ->setParameter('dialogueType'$dialogueType)
  3194.                         //->setParameter('cdate', date("Y-m-d"))
  3195.                         ->execute();
  3196.             } elseif ($sortBy == 'fullName') {
  3197.                 $notesPassedReminderDate $em->createQuery(
  3198.                                 'SELECT n,po.isDeleted  from App\Entity\DialogueAttachmentDetails n 
  3199.                                 left join App\Entity\Dialogue d with d.id = n.dialogue
  3200.                                 inner join App\Entity\Patient p with p.id = n.patient 
  3201.                                 left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  3202.                          where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by p.firstName ' $orderBy)
  3203.                         ->setParameter('user'$user)
  3204.                         ->setParameter('dialogueType'$dialogueType)
  3205.                         //->setParameter('cdate', date("Y-m-d"))
  3206.                         ->execute();
  3207.             } elseif ($sortBy == 'cpr') {
  3208.                 $notesPassedReminderDate $em->createQuery(
  3209.                                 'SELECT n,po.isDeleted  from App\Entity\DialogueAttachmentDetails n 
  3210.                                 left join App\Entity\Dialogue d with d.id = n.dialogue
  3211.                                 inner join App\Entity\Patient p with p.id = n.patient 
  3212.                                 left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  3213.                          where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by p.cpr ' $orderBy)
  3214.                         ->setParameter('user'$user)
  3215.                         ->setParameter('dialogueType'$dialogueType)
  3216.                         //->setParameter('cdate', date("Y-m-d"))
  3217.                         ->execute();
  3218.             } elseif ($sortBy == 'age') {
  3219.                 $notesPassedReminderDate $em->createQuery(
  3220.                                 'SELECT n,po.isDeleted  from App\Entity\DialogueAttachmentDetails n 
  3221.                                 left join App\Entity\Dialogue d with d.id = n.dialogue
  3222.                                 inner join App\Entity\Patient p with p.id = n.patient 
  3223.                                 left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  3224.                          where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by p.childAge ' $orderBy)
  3225.                         ->setParameter('user'$user)
  3226.                         ->setParameter('dialogueType'$dialogueType)
  3227.                         //->setParameter('cdate', date("Y-m-d"))
  3228.                         ->execute();
  3229.             } elseif ($sortBy == 'heading') {
  3230.                 $notesPassedReminderDate $em->createQuery(
  3231.                                 'SELECT n,po.isDeleted  from App\Entity\DialogueAttachmentDetails n 
  3232.                                 left join App\Entity\Dialogue d with d.id = n.dialogue
  3233.                                 inner join App\Entity\Patient p with p.id = n.patient 
  3234.                                 left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  3235.                          where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by n.attachmentHeading ' $orderBy)
  3236.                         ->setParameter('user'$user)
  3237.                         ->setParameter('dialogueType'$dialogueType)
  3238.                        // ->setParameter('cdate', date("Y-m-d"))
  3239.                         ->execute();
  3240.             } elseif ($sortBy == 'reminderDate') {
  3241.                 $notesPassedReminderDate $em->createQuery(
  3242.                                 'SELECT n,po.isDeleted  from App\Entity\DialogueAttachmentDetails n 
  3243.                                 left join App\Entity\Dialogue d with d.id = n.dialogue
  3244.                                 inner join App\Entity\Patient p with p.id = n.patient 
  3245.                                 left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  3246.                          where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and p.isDummyPatient = '.$isDummyPatient.' and d.dialogueType= :dialogueType HAVING (po.isDeleted = false or po.isDeleted is null) order by n.reminderDate ' $orderBy)
  3247.                         ->setParameter('user'$user)
  3248.                         ->setParameter('dialogueType'$dialogueType)
  3249.                         //->setParameter('cdate', date("Y-m-d"))
  3250.                         ->execute();
  3251.             }
  3252.         } else {
  3253.             $notesPassedReminderDate $em->createQuery('
  3254.                           SELECT n,po.isDeleted  from App\Entity\DialogueAttachmentDetails n 
  3255.                           left join App\Entity\Dialogue d with d.id = n.dialogue
  3256.                           inner join App\Entity\Patient p with p.id = n.patient 
  3257.                           left join App\Entity\JoPostMail po with po.id = n.joPostMail 
  3258.                           where n.user = :user and n.pAtttachmentType <> 50 and n.reminderDate is not null and n.canTrash = 0 and n.deletedBy IS NULL and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'
  3259.                           group by n.id HAVING (po.isDeleted = false or po.isDeleted is null) order by n.reminderDate asc ')
  3260.                     ->setParameter('user'$user)
  3261.                     ->setParameter('dialogueType'$dialogueType)
  3262.                     //->setParameter('cdate', date("Y-m-d"))
  3263.                     ->execute();
  3264.         }
  3265.         return $this->render("default/viewMoreMyUrgentInfo.html.twig", array('notesPassedReminderDate' => $notesPassedReminderDate'user' => $user));
  3266.     }
  3267.     public function viewMoreMyActiveInfo(Request $request) {
  3268.         $em $this->getDoctrine()->getManager();
  3269.         $session $request->getSession();
  3270.         $user $this->get('security.token_storage')->getToken()->getUser();
  3271.         $listType $request->get('listType');
  3272.         $sortBy $request->get('sortBy');
  3273.         $orderBy $request->get('orderBy');
  3274.         $isTestUser $user->getIsTestUser();
  3275.         $isDummyPatient $isTestUser 0;
  3276.         $dialogueType $user->hasRole('ROLE_CSV') ? : ($user->hasRole('ROLE_DTS') ? 0);
  3277.         if ($sortBy != null && $orderBy != null && $listType == 'active') {
  3278.             // Fetch dialogues created by logged in user or dialogues where current user has created case_card or notes
  3279.             if ($sortBy == 'createdAt') {
  3280.                 if ($user->hasRole('ROLE_CSV')) {
  3281.                     $query $em->createQuery(
  3282.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3283.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3284.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3285.                         left join App\Entity\Patient p with p.id = d.patient
  3286.                         WHERE ( m.responsiblePerson = :user  and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by d.createdAt ' $orderBy
  3287.                             )->setParameter('dialogueType'$dialogueType)
  3288.                             ->setParameter('user'$user);
  3289.                 }else{
  3290.                     $query $em->createQuery(
  3291.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3292.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3293.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3294.                         left join App\Entity\Patient p with p.id = d.patient
  3295.                         WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by d.createdAt ' $orderBy
  3296.                             )->setParameter('dialogueType'$dialogueType)
  3297.                             ->setParameter('user'$user);
  3298.                 }
  3299.                 $myDialogues $query->execute();
  3300.             } elseif ($sortBy == 'fullName') {
  3301.                 if ($user->hasRole('ROLE_CSV')) {
  3302.                     $query $em->createQuery(
  3303.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3304.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3305.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3306.                         left join App\Entity\Patient p with p.id = d.patient
  3307.                         WHERE ( m.responsiblePerson = :user  and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ' $orderBy
  3308.                             )->setParameter('dialogueType'$dialogueType)
  3309.                             ->setParameter('user'$user);
  3310.                 }else{
  3311.                     $query $em->createQuery(
  3312.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3313.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3314.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3315.                         left join App\Entity\Patient p with p.id = d.patient
  3316.                         WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ' $orderBy
  3317.                             )->setParameter('dialogueType'$dialogueType)
  3318.                             ->setParameter('user'$user);
  3319.                 }
  3320.                 $myDialogues $query->execute();
  3321.             } elseif ($sortBy == 'age') {
  3322.                 if ($user->hasRole('ROLE_CSV')) {
  3323.                     $query $em->createQuery(
  3324.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3325.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3326.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3327.                         left join App\Entity\Patient p with p.id = d.patient
  3328.                         WHERE ( m.responsiblePerson = :user  and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.childAge ' $orderBy
  3329.                             )->setParameter('dialogueType'$dialogueType)
  3330.                             ->setParameter('user'$user);
  3331.                 }else{
  3332.                     $query $em->createQuery(
  3333.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3334.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3335.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3336.                         left join App\Entity\Patient p with p.id = d.patient
  3337.                         WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.childAge ' $orderBy
  3338.                             )->setParameter('dialogueType'$dialogueType)
  3339.                             ->setParameter('user'$user);
  3340.                 }
  3341.                 $myDialogues $query->execute();
  3342.             } elseif ($sortBy == 'cpr') {
  3343.                 if ($user->hasRole('ROLE_CSV')) {
  3344.                     $query $em->createQuery(
  3345.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3346.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3347.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3348.                         left join App\Entity\Patient p with p.id = d.patient
  3349.                         WHERE ( m.responsiblePerson = :user  and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.cpr ' $orderBy
  3350.                             )->setParameter('dialogueType'$dialogueType)
  3351.                             ->setParameter('user'$user);
  3352.                 }else{
  3353.                     $query $em->createQuery(
  3354.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3355.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3356.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3357.                         left join App\Entity\Patient p with p.id = d.patient
  3358.                         WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.cpr ' $orderBy
  3359.                             )->setParameter('dialogueType'$dialogueType)
  3360.                             ->setParameter('user'$user);
  3361.                 }
  3362.                 $myDialogues $query->execute();
  3363.             } elseif ($sortBy == 'updatedAt') {
  3364.                 if ($user->hasRole('ROLE_CSV')) {
  3365.                     $query $em->createQuery(
  3366.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3367.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3368.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3369.                         left join App\Entity\Patient p with p.id = d.patient
  3370.                         WHERE ( m.responsiblePerson = :user  and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by d.updatedAt ' $orderBy
  3371.                             )->setParameter('dialogueType'$dialogueType)
  3372.                             ->setParameter('user'$user);
  3373.                 }else{
  3374.                    $query $em->createQuery(
  3375.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3376.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3377.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3378.                         left join App\Entity\Patient p with p.id = d.patient
  3379.                         WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by d.updatedAt ' $orderBy
  3380.                             )->setParameter('dialogueType'$dialogueType)
  3381.                             ->setParameter('user'$user);
  3382.                 }
  3383.                 $myDialogues $query->execute();
  3384.             }
  3385.         } else {
  3386.             // Fetch dialogues created by logged in user or dialogues where current user has created case_card or notes
  3387.             /* $query = $em->createQuery(
  3388.               'SELECT DISTINCT d FROM App\Entity\Dialogue d
  3389.               left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3390.               left join App\Entity\DialogueAttachmentDetails n with d.id = n.dialogue
  3391.               WHERE (d.anchor = :user or c.createdBy = :user or n.user = :user) and d.deleted = false and d.status =1 '
  3392.               )->setParameter('user', $user);
  3393.               $myDialogues = $query->execute(); */
  3394.             if ($user->hasRole('ROLE_CSV')) {
  3395.                     $myDialogues $em->createQuery(
  3396.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3397.                                 left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3398.                                 left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3399.                                 left join App\Entity\Patient p with p.id = d.patient 
  3400.                                 WHERE ( m.responsiblePerson = :user  and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.
  3401.                                 order by p.firstName ASC'
  3402.                             )
  3403.                             ->setParameter('user'$user)
  3404.                             ->setParameter('dialogueType'$dialogueType)
  3405.                             ->execute();
  3406.                 }else{
  3407.                     $myDialogues $em->createQuery(
  3408.                                     'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3409.                                 left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3410.                                 left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3411.                                 left join App\Entity\Patient p with p.id = d.patient 
  3412.                                 WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false and  d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.
  3413.                                 order by p.firstName ASC'
  3414.                             )
  3415.                             ->setParameter('user'$user)
  3416.                             ->setParameter('dialogueType'$dialogueType)
  3417.                             ->execute();
  3418.                 }
  3419.         }
  3420.         return $this->render("default/viewMoreMyActiveInfo.html.twig", array('myDialogues' => $myDialogues'user' => $user));
  3421.     }
  3422.     public function viewMoreMyNewInfo(Request $request) {
  3423.         $em $this->getDoctrine()->getManager();
  3424.         $session $request->getSession();
  3425.         $user $this->get('security.token_storage')->getToken()->getUser();
  3426.         $listType $request->get('listType');
  3427.         $sortBy $request->get('sortBy');
  3428.         $orderBy $request->get('orderBy');
  3429.         $isTestUser $user->getIsTestUser();
  3430.         $isDummyPatient $isTestUser 0;
  3431.         $pagelimit NULL;
  3432.         $searchTerm NULL;
  3433.         $dialogueType $user->hasRole('ROLE_CSV') ? : ($user->hasRole('ROLE_DTS') ? 0);
  3434.         $parameters = [];
  3435.         $parameters['dialogueType'] = $dialogueType;
  3436.         /*$searchSqlStr = "SELECT DISTINCT d FROM App\Entity\Dialogue d                   
  3437.                    left join App\Entity\Patient p with p.id = d.patient 
  3438.                    left join App\Entity\User u with u.id = p.user
  3439.                    left join App\Entity\DialogueCaseCard dc with d.id = dc.dialogue
  3440.                    left join App\Entity\User a with a.id = d.anchor 
  3441.                    WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType AND dc.isClosed = false and p.isDummyPatient = ".$isDummyPatient;
  3442.         $fetchAllDialogues = $em->createQuery($searchSqlStr)
  3443.                 ->setParameters($parameters) //send multiple paramenters
  3444.                 ->execute();*/
  3445.         
  3446.         $dialogueMeasureText "";
  3447.         
  3448.         if ($user->hasRole('ROLE_CSV')) {
  3449.              /*$myDialogues = $em->createQuery(
  3450.                         'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3451.                     left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3452.                     left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3453.                     left join App\Entity\Patient p with p.id = d.patient 
  3454.                     WHERE ( m.responsiblePerson = :user  and m.toDate is NULL) and d.deleted = false and d.status =1 and c.isClosed = false 
  3455.                     and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ASC'
  3456.                 )
  3457.                 ->setParameter('user', $user)
  3458.                 ->setParameter('dialogueType', $dialogueType)
  3459.                 ->execute();*/$myDialogues $em->getRepository(Dialogue::class)->myActiveCases('ROLE_CSV'$searchTerm$user$dialogueType$pagelimit$isDummyPatient);
  3460.         }else{
  3461.                 /*$myDialogues = $em->createQuery(
  3462.                         'SELECT DISTINCT d FROM App\Entity\Dialogue d 
  3463.                         left join App\Entity\DialogueCaseCard c with d.id = c.dialogue
  3464.                         left join App\Entity\DialogueCaseCardMeasure m with c.id = m.DialogueCaseCard
  3465.                         left join App\Entity\Patient p with p.id = d.patient 
  3466.                     WHERE ((c.createdBy = :user) or (m.responsiblePerson = :user and m.toDate is NULL)) and d.deleted = false and d.status =1 and c.isClosed = false
  3467.                     and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ASC'
  3468.                 )
  3469.                 ->setParameter('user', $user)
  3470.                 ->setParameter('dialogueType', $dialogueType)
  3471.                 ->execute();*/$myDialogues $em->getRepository(Dialogue::class)->myActiveCases('ROLE_DTS'$searchTerm$user$dialogueType$pagelimit$isDummyPatient);
  3472.         }
  3473.         //}
  3474.             
  3475.         $today = new \DateTime();
  3476.         $before30days $today->modify('-30 day')->format('Y-m-d');
  3477.         //var_dump(($myDialogues));
  3478.         if ($sortBy != null && $orderBy != null && $listType == 'newContent') {
  3479.             if ($sortBy == 'createdAt') {
  3480.                 $queryOther $em->createQuery(
  3481.                                 'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n 
  3482.                      left join App\Entity\Dialogue d with d.id = n.dialogue  
  3483.                      left join App\Entity\Patient p with p.id = n.patient 
  3484.                     WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate  > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by n.createdAt ' $orderBy
  3485.                         )
  3486.                         ->setParameter('user'$user)
  3487.                         ->setParameter('before30days'$before30days)
  3488.                         ->setParameter('dialogueId'$myDialogues)
  3489.                         ->setParameter('dialogueType'$dialogueType);
  3490.                 $newContentDialogues $queryOther->execute();
  3491.             } elseif ($sortBy == 'attachmentDate') {
  3492.                 $queryOther $em->createQuery(
  3493.                                 'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n 
  3494.                      left join App\Entity\Dialogue d with d.id = n.dialogue  
  3495.                      left join App\Entity\Patient p with p.id = n.patient 
  3496.                     WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate  > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by n.attachmentDate ' $orderBy
  3497.                         )
  3498.                         ->setParameter('user'$user)
  3499.                         ->setParameter('before30days'$before30days)
  3500.                         ->setParameter('dialogueId'$myDialogues)
  3501.                         ->setParameter('dialogueType'$dialogueType);
  3502.                 $newContentDialogues $queryOther->execute();
  3503.             } elseif ($sortBy == 'fullName') {
  3504.                 $queryOther $em->createQuery(
  3505.                                 'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n 
  3506.                      left join App\Entity\Dialogue d with d.id = n.dialogue   
  3507.                      left join App\Entity\Patient p with p.id = n.patient 
  3508.                     WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate  > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.firstName ' $orderBy
  3509.                         )
  3510.                         ->setParameter('user'$user)
  3511.                         ->setParameter('before30days'$before30days)
  3512.                         ->setParameter('dialogueId'$myDialogues)
  3513.                         ->setParameter('dialogueType'$dialogueType);
  3514.                 $newContentDialogues $queryOther->execute();
  3515.             } elseif ($sortBy == 'cpr') {
  3516.                 $queryOther $em->createQuery(
  3517.                                 'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n 
  3518.                      left join App\Entity\Dialogue d with d.id = n.dialogue   
  3519.                      left join App\Entity\Patient p with p.id = n.patient 
  3520.                     WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate  > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by p.cpr ' $orderBy
  3521.                         )
  3522.                         ->setParameter('user'$user)
  3523.                         ->setParameter('before30days'$before30days)
  3524.                         ->setParameter('dialogueId'$myDialogues)
  3525.                         ->setParameter('dialogueType'$dialogueType);
  3526.                 $newContentDialogues $queryOther->execute();
  3527.             } elseif ($sortBy == 'heading') {
  3528.                 $queryOther $em->createQuery(
  3529.                                 'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n 
  3530.                      left join App\Entity\Dialogue d with d.id = n.dialogue   
  3531.                      left join App\Entity\Patient p with p.id = n.patient 
  3532.                     WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate  > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by n.attachmentHeading ' $orderBy
  3533.                         )
  3534.                         ->setParameter('user'$user)
  3535.                         ->setParameter('before30days'$before30days)
  3536.                         ->setParameter('dialogueId'$myDialogues)
  3537.                         ->setParameter('dialogueType'$dialogueType);
  3538.                 $newContentDialogues $queryOther->execute();
  3539.             } elseif ($sortBy == 'userName') {
  3540.                 $queryOther $em->createQuery(
  3541.                                 'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n 
  3542.                      left join App\Entity\Dialogue d with d.id = n.dialogue   
  3543.                      left join App\Entity\Patient p with p.id = n.patient 
  3544.                      left join App\Entity\User u with u.id = n.user
  3545.                     WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate  > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' order by u.fullName ' $orderBy
  3546.                         )
  3547.                         ->setParameter('user'$user)
  3548.                         ->setParameter('before30days'$before30days)
  3549.                         ->setParameter('dialogueId'$myDialogues)
  3550.                         ->setParameter('dialogueType'$dialogueType);
  3551.                 $newContentDialogues $queryOther->execute();
  3552.             }
  3553.         } else {
  3554.             $newContentDialogues $em->createQuery(
  3555.                             'SELECT DISTINCT n FROM App\Entity\DialogueAttachmentDetails n
  3556.                         left join App\Entity\Dialogue d with d.id = n.dialogue
  3557.                         left join App\Entity\Patient p with p.id = n.patient 
  3558.                         WHERE (n.user <> :user and (n.isDraft = 0 or n.visibleStatus <> 1) and n.dialogue IN (:dialogueId) ) and n.deletedBy IS NULL and n.attachmentDate  > :before30days and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.'
  3559.                         order by n.createdAt desc'
  3560.                     )
  3561.                     ->setParameter('user'$user)
  3562.                     ->setParameter('before30days'$before30days)
  3563.                     ->setParameter('dialogueId'$myDialogues)
  3564.                     ->setParameter('dialogueType'$dialogueType)
  3565.                     ->execute();
  3566.         }
  3567.         return $this->render("default/viewMoreMyNewInfo.html.twig", array('newContentDialogues' => $newContentDialogues'dialogueMeasureText' => $dialogueMeasureText'user' => $user));
  3568.     }
  3569.     
  3570.     public function viewMoreAllInfo(Request $request) {
  3571.         $em $this->getDoctrine()->getManager();
  3572.         $session $request->getSession();
  3573.         $user $this->get('security.token_storage')->getToken()->getUser();
  3574.         $listType $request->get('listType');
  3575.         $sortBy $request->get('sortBy');
  3576.         $orderBy $request->get('orderBy');
  3577.         $isTestUser $user->getIsTestUser();
  3578.         $isDummyPatient $isTestUser 0;
  3579.         $loginUserCat $user->getCategory()->getName();
  3580.         
  3581.         $loginUserInstitutions $this->loginUserInstitutions($em$user);
  3582.         $currentSelectedInstitution $session->get('selectedInstitutionId') ? $session->get('selectedInstitutionId') : $loginUserInstitutions[0];
  3583.         $loginUserGroups $this->loginUserGroups($em$user);
  3584.         $dialogueType $user->hasRole('ROLE_CSV') ? : ($user->hasRole('ROLE_DTS') ? 0);
  3585.         
  3586.          if ($sortBy != null && $orderBy != null && $listType == 'all') {
  3587.             if ($sortBy == 'createdAt') {
  3588.                 $query $em->createQuery(
  3589.                                 'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d 
  3590.                                 left join App\Entity\Patient p with p.id = d.patient
  3591.                                 left join App\Entity\PatientInformation pi with p.id = pi.patient
  3592.                                 left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  3593.                                 left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3594.                          WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by d.createdAt ' $orderBy
  3595.                         )->setParameter('dialogueType'$dialogueType);//->setParameter('category', $loginUserCat);
  3596.                 $fetchAllDialogues $query->execute();
  3597.             } elseif ($sortBy == 'fullName') {
  3598.                 $query $em->createQuery(
  3599.                                 'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d 
  3600.                          left join App\Entity\Patient p with p.id = d.patient
  3601.                          left join App\Entity\PatientInformation pi with p.id = pi.patient
  3602.                          left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  3603.                          left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3604.                          WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by p.firstName ' $orderBy
  3605.                         )->setParameter('dialogueType'$dialogueType);//->setParameter('category', $loginUserCat);
  3606.                 $fetchAllDialogues $query->execute();
  3607.             } elseif ($sortBy == 'age') {
  3608.                 $query $em->createQuery(
  3609.                                 'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d 
  3610.                          left join App\Entity\Patient p with p.id = d.patient
  3611.                          left join App\Entity\PatientInformation pi with p.id = pi.patient
  3612.                          left join App\Entity\StilPerson sp with sp.civilregistrationnumber= p.cpr
  3613.                          left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3614.                          WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by p.childAge ' $orderBy
  3615.                         )->setParameter('dialogueType'$dialogueType);//->setParameter('category', $loginUserCat);
  3616.                         //var_dump($query);
  3617.                         //die;
  3618.                 $fetchAllDialogues $query->execute();
  3619.             } elseif ($sortBy == 'citizenInstitutionStatus') {
  3620.                 $query $em->createQuery(
  3621.                                 'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d 
  3622.                          left join App\Entity\Patient p with p.id = d.patient
  3623.                          left join App\Entity\PatientInformation pi with p.id = pi.patient
  3624.                          left join App\Entity\StilPerson sp with sp.civilregistrationnumber= p.cpr
  3625.                          left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3626.                          WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by groupName ' $orderBy
  3627.                         )->setParameter('dialogueType'$dialogueType);//->setParameter('category', $loginUserCat);
  3628.                 $fetchAllDialogues $query->execute();
  3629.             } elseif ($sortBy == 'gread') {
  3630.                 $query $em->createQuery(
  3631.                                 'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d 
  3632.                          left join App\Entity\Patient p with p.id = d.patient
  3633.                          left join App\Entity\PatientInformation pi with p.id = pi.patient
  3634.                          left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  3635.                          left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3636.                          WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by d.latestGrade ' $orderBy
  3637.                         )->setParameter('dialogueType'$dialogueType);//->setParameter('category', $loginUserCat);
  3638.                         $fetchAllDialogues $query->execute();
  3639.             } elseif ($sortBy == 'cpr') {
  3640.                 $query $em->createQuery(
  3641.                                 'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d 
  3642.                          left join App\Entity\Patient p with p.id = d.patient
  3643.                          left join App\Entity\PatientInformation pi with p.id = pi.patient
  3644.                          left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  3645.                          left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3646.                          WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') or sp.maingroupid in ('.$loginUserGroups.') order by p.cpr ' $orderBy
  3647.                         )->setParameter('dialogueType'$dialogueType);//->setParameter('category', $loginUserCat);
  3648.                 $fetchAllDialogues $query->execute();
  3649.             } elseif ($sortBy == 'updatedAt') {
  3650.                 $query $em->createQuery(
  3651.                                 'SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d 
  3652.                                 left join App\Entity\Patient p with p.id = d.patient
  3653.                                 left join App\Entity\PatientInformation pi with p.id = pi.patient
  3654.                                 left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  3655.                                 left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3656.                          WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType and p.isDummyPatient = '.$isDummyPatient.' and sp.institutionId in ('.$currentSelectedInstitution.') order by d.updatedAt ' $orderBy
  3657.                         )->setParameter('dialogueType'$dialogueType);//->setParameter('category', $loginUserCat);
  3658.                 $fetchAllDialogues $query->execute();
  3659.             }
  3660.         } else {
  3661.             //$fetchAllDialogues = $em->getRepository(Dialogue::class)->findBy(array('deleted' => false, 'status' => 1, 'dialogueType' => $dialogueType));           
  3662.             //if (strlen($searchTerm) > 6 && $searchTerm[6] == '-') {//when search by cpr number and 7th char is - then replace it and pass the search string
  3663.             //    $searchTerm = str_replace('-', '', $searchTerm);
  3664.            // } else {
  3665.            //     $searchTerm = $searchTerm;
  3666.             $parameters = [];
  3667.             $parameters['dialogueType'] = $dialogueType;
  3668.             $searchSqlStr "SELECT DISTINCT d, sig.groupname as groupName FROM App\Entity\Dialogue d                   
  3669.                    left join App\Entity\Patient p with p.id = d.patient 
  3670.                    left join App\Entity\User u with u.id = p.user
  3671.                    left join App\Entity\DialogueCaseCard dc with d.id = dc.dialogue
  3672.                    left join App\Entity\User a with a.id = d.anchor 
  3673.                    left join App\Entity\PatientInformation pi with p.id = pi.patient
  3674.                    left join App\Entity\Category c with a.category = c.id
  3675.                    left join App\Entity\DialogueAttachmentDetails dad with dad.dialogue = d.id
  3676.                    left join App\Entity\StilPerson sp with sp.civilregistrationnumber = p.cpr
  3677.                    left join App\Entity\StilInstitutionGroup sig with sp.maingroupid = sig.groupid
  3678.                    WHERE d.deleted = false and d.status =1 and d.dialogueType= :dialogueType AND dc.toDate IS NULL and p.isDummyPatient = ".$isDummyPatient." and sp.institutionId in (".$currentSelectedInstitution.") ";
  3679.                    
  3680.                                //echo $dialogueType." ".$searchSqlStr;
  3681.             $fetchAllDialogues $em->createQuery($searchSqlStr)
  3682.                     ->setParameters($parameters//send multiple paramenters
  3683.                     ->execute();
  3684.             }
  3685.             $dialogueMeasureText "";
  3686.         
  3687.         
  3688.         return $this->render("default/viewMoreAllInfo.html.twig", array('fetchAllDialogues' => $fetchAllDialogues'dialogueMeasureText' => $dialogueMeasureText'user' => $user));
  3689.     }
  3690.     
  3691.     public function loginUserInstitutions($em$user){
  3692.         //$loginUserInstitutions 
  3693.         $loginUserInstitutionsArray $em->createQuery("SELECT  distinct (sp.institutionId)  FROM App\Entity\StilPerson sp                  
  3694.                    left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser 
  3695.                    WHERE ac.user =".$user->getId() )
  3696.                 ->getScalarResult();
  3697.         $loginUserInstitutions array_map('current'$loginUserInstitutionsArray);
  3698.         if(count($loginUserInstitutions) == 0){
  3699.             $loginUserInstitutions[] = 0;
  3700.         }
  3701.         //var_dump($loginUserInstitutions);die;
  3702.         return $loginUserInstitutions;
  3703.     }
  3704.     
  3705.     public function loginUserGroups($em$user){
  3706.         //$loginUserGroups 
  3707.         $loginUserGroupsArray $em->createQuery("SELECT  distinct (spg.groupid)  FROM App\Entity\StilPerson sp 
  3708.                    left join App\Entity\StilPersonGroup spg with sp.id = spg.personId                  
  3709.                    left join App\Entity\JoAulaConnection ac with sp.userid = ac.aulaUser 
  3710.                    WHERE spg.groupid is not NULL and ac.user =".$user->getId() )
  3711.                 ->getScalarResult();
  3712.         $loginUserGroups array_map('current'$loginUserGroupsArray);
  3713.         if(count($loginUserGroups) == 0){
  3714.             $loginUserGroups[] = 0;
  3715.         }
  3716.         $comma_list "'" .implode("', '"$loginUserGroups) . "'";
  3717.         return $comma_list;
  3718.     }
  3719.     public function updatePatientInfo(Request $request){
  3720.         $em $this->getDoctrine()->getManager();
  3721.         $patientId $request->get('patientId');
  3722.         $instiStu trim($request->get('instiStu'));
  3723.         $instiEmail trim($request->get('instiEmail'));
  3724.         $instiTlf trim($request->get('instiTlf'));
  3725.         $schoolEmail trim($request->get('schoolEmail'));
  3726.         $schoolTlf trim($request->get('schoolTlf'));
  3727.         $instiHomepage trim($request->get('instiHomepage'));
  3728.         $instiLocation trim($request->get('instiLocation'));
  3729.         $patientObj $em->getRepository(PatientInformation::class)->find($patientId);
  3730.         $session $request->getSession();
  3731.         
  3732.         //if($instiStu != ""){
  3733.             $patientObj->setCitizenInstitutionStatus($instiStu);
  3734.         //}
  3735.         if($instiEmail != ""){
  3736.             $patientObj->setCitizenInstitutionMail($instiEmail);
  3737.         }
  3738.         //if($instiTlf != ""){
  3739.             $patientObj->setCitizenInstitutionTelephone($instiTlf);
  3740.         //}
  3741.         
  3742.         if($schoolEmail != ""){
  3743.             $patientObj->setCitizenSchoolMail($schoolEmail);
  3744.         }
  3745.         //if($schoolTlf != ""){
  3746.             $patientObj->setCitizenSchoolTelephone($schoolTlf);
  3747.         //}
  3748.         //if($instiHomepage != ""){
  3749.             $patientObj->setHomepage($instiHomepage);
  3750.         //}
  3751.         //if($instiLocation != ""){
  3752.             $patientObj->setCitizenInstitutionLocationName($instiLocation);
  3753.         //}
  3754.         
  3755.         $em->persist($patientObj);
  3756.         $em->flush();
  3757.         
  3758.         $selectedPatient $session->get("selectedPatient"false);
  3759.     $patientObj $em->getRepository(Patient::class)->find($selectedPatient->getId());
  3760.     
  3761.     $patientInfoObjTemp $em->getRepository(PatientInformation::class)->findBy(array('user' => $patientObj->getUser()));
  3762.             $patientInfoObj $patientInfoObjTemp $patientInfoObjTemp[0] : array();
  3763.   return $this->render("default/reloadDtsChildInfo.html.twig", array(
  3764.                     'patientObj' => $patientObj,
  3765.                     'patientInfoObj' => $patientInfoObj));
  3766.         
  3767.     }
  3768.     
  3769.     public function updateAllStamdata($patient$session) {
  3770.         $em $entityManager $this->getDoctrine()->getManager();
  3771.         $dialogueControllerObj = new DialogueController();
  3772.         if($patient->getIsFakeCpr() == || $patient->getIsDummyPatient() == 1){
  3773.             return true;
  3774.         }
  3775.         if ($patient) {
  3776.             $newPatient $patient;
  3777.             $cprNo $patient->getCpr();
  3778.             // Call service 208
  3779.             $serviceResponse $this->doSoapRequest(208$cprNo);
  3780.             if($serviceResponse){
  3781.             $patientObject $serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row[0];
  3782.             $isPatientDeceased trim($dialogueControllerObj->getFieldValue($patientObject'CNVN_STATUS'));
  3783.             if(isset($isPatientDeceased) && $isPatientDeceased == 90){
  3784.                 $newPatient->setIsDeceased(1);
  3785.                 $deceasedDateTime trim($dialogueControllerObj->getFieldValue($patientObject'CNVN_STATUSSTARTDATO'));
  3786.                 if(isset($deceasedDateTime)){
  3787.                     //var_dump($deceasedDateTime);
  3788.                     $deceasedDateTemp substr($deceasedDateTime0,8);
  3789.                     //var_dump($deceasedDateTemp);
  3790.                     $deceasedDate substr($deceasedDateTemp0,4).'-'.substr($deceasedDateTemp4,2).'-'.substr($deceasedDateTemp6,2);
  3791.                     //var_dump($deceasedDate);die;
  3792.                     $newPatient->setDeceaseDate(new \DateTime($deceasedDate));
  3793.                 }
  3794.             }
  3795.             //Update patient name
  3796.             $cprFirstName trim($this->getFieldValue($patientObject'CNVN_FORNVN')).' 'trim($this->getFieldValue($patientObject'CNVN_MELNVN'));
  3797.             $cprLastName trim($this->getFieldValue($patientObject'CNVN_EFTERNVN'));
  3798.             $newPatient->setLastName($cprFirstName);
  3799.             $newPatient->setFirstName($cprLastName);
  3800.             //Update patient address as well as user address
  3801.             $newPatient->setAddressLine1($dialogueControllerObj->getFieldValue($patientObject'STADR'));
  3802.             $patientAddressObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'PNR_FOEDDATO'$newPatient->getCpr());
  3803.             if ($patientAddressObject) {
  3804.                 $newPatient->setPostNumber($dialogueControllerObj->getFieldValue($patientAddressObject'CPST_POSTNR'));
  3805.                 $newPatient->setCity($dialogueControllerObj->getFieldValue($patientAddressObject'CPSN_POSTDISTTXT'));
  3806.             } else {
  3807.                 $newPatient->setPostNumber($dialogueControllerObj->getFieldValue($patientObject'POSTNR'));
  3808.                 $newPatient->setCity($dialogueControllerObj->getFieldValue($patientObject'BYNVN'));
  3809.             }
  3810.             
  3811.             //Also update the stamdata family members
  3812.             $this->updateMorFarGardianToStamdata($em$newPatient$patientObject$serviceResponse$dialogueControllerObj$session);
  3813.             
  3814.             $newPatientUserObj $newPatient->getUser();
  3815.             $newPatientUserObj->setAddress($newPatient->getAddressLine1());
  3816.             $newPatientUserObj->setPostNumber($newPatient->getPostNumber());
  3817.             $newPatientUserObj->setCity($newPatient->getCity());
  3818.             $newPatientUserObj->setFirstName($cprFirstName);
  3819.             $newPatientUserObj->setLastName($cprLastName);
  3820.             $newPatientUserObj->setFullName($cprFirstName." ".$cprLastName);
  3821.             $entityManager->persist($newPatientUserObj);
  3822.             
  3823.             //Call to findout siblings if child address match with mor or far then call the with parent cpr and get sublinks
  3824.             $siblingsArray $spouseArray = array();
  3825.             $loopCnt 0;
  3826.             foreach ($newPatient->getFamily() as $member) {
  3827.                 if (true || $member->getRelative()->getAddress() == $newPatient->getAddressLine1() && $member->getRelative()->getCity() == $newPatient->getCity() && $member->getRelative()->getPostNumber() == $newPatient->getPostNumber()) {
  3828.                     //$isParentAddressMatch++;
  3829.                     $parentCprNo $member->getRelative()->getUsername();
  3830.                     if(strlen($parentCprNo)=="10") {
  3831.                     // Call service 208
  3832.                     $parentServiceResponse $this->doSoapRequest(208$parentCprNo);
  3833.                     //$parentServiceObject = $parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row;
  3834.                     $patientNameObject $parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row[0];
  3835.                     $parentFirstName trim($dialogueControllerObj->getFieldValue($patientNameObject'CNVN_FORNVN'));
  3836.                     $parentMiddleName trim($dialogueControllerObj->getFieldValue($patientNameObject'CNVN_MELNVN'));
  3837.                     $parentLastName trim($dialogueControllerObj->getFieldValue($patientNameObject'CNVN_EFTERNVN'));
  3838.                     $isparentDeceased trim($dialogueControllerObj->getFieldValue($patientNameObject'CNVN_STATUS'));
  3839.                     if(isset($isparentDeceased) && $isparentDeceased == 90){
  3840.                         $member->setIsDeceased(1);
  3841.                         $deceasedDateTime trim($dialogueControllerObj->getFieldValue($patientNameObject'CNVN_STATUSSTARTDATO'));
  3842.                         if(isset($deceasedDateTime)){
  3843.                             $deceasedDateTemp substr($deceasedDateTime0,8);
  3844.                             $deceasedDate substr($deceasedDateTemp0,4).'-'.substr($deceasedDateTemp4,2).'-'.substr($deceasedDateTemp6,2);
  3845.                             $member->setDeceaseDate(new \DateTime($deceasedDate));
  3846.                         }
  3847.                     }
  3848.                     if ($parentFirstName != "" && $parentLastName != "") {
  3849.                         $member->getRelative()->setFirstName($parentFirstName ' ' $parentMiddleName);
  3850.                         $member->getRelative()->setLastName($parentLastName);
  3851.                     }
  3852.                     //In stam data we have check box for “Hemmelig adresse”. 
  3853.                     //If value found check it - if not it is blank (unchecked). do for parents
  3854.                     $isSecretAddressParent $dialogueControllerObj->getFieldValue($patientNameObject'BESKYT');
  3855.                     $isSecretAddressParentVal false;
  3856.                     if (!is_null($isSecretAddressParent)) {
  3857.                         $isSecretAddressParentVal true;
  3858.                     }
  3859.                     //if ($isSecretAddressParentVal) {
  3860.                         $newpatientUserObj $member->getRelative();
  3861.                         $member->getRelative()->setIsSecretAddress($isSecretAddressParentVal);
  3862.                     //}
  3863.                     $siblingObject $dialogueControllerObj->getChildMatchingObject($parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Barn');
  3864.                     if ($siblingObject) {
  3865.                         $siblingsArray $dialogueControllerObj->siblingsArrayData($siblingObject$newPatient$siblingsArray);
  3866.                     }
  3867.                     //Spouse - In parent lookup we need to look for FAMMRK "Ægtefælle" too.
  3868.                     //To find who the parent is currently married to. If divorced and remarried a new person will be listed here.
  3869.                     $spouseObject $dialogueControllerObj->getChildMatchingObject($parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Ægtefælle');
  3870.                     if ($spouseObject) {
  3871.                         $spouseBarnObject $dialogueControllerObj->getChildMatchingObject($parentServiceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Barn');
  3872.                         $siblingsArray $dialogueControllerObj->siblingsArrayData($spouseBarnObject$newPatient$siblingsArray);
  3873.                     }
  3874.                 
  3875.                     $entityManager->persist($member);
  3876.                     $entityManager->flush();
  3877.                 }
  3878.                 }
  3879.             }
  3880.             //var_dump($siblingsArray); die;
  3881.             $getPatientFullDate $dialogueControllerObj->getBirthDate($newPatient->getCpr());
  3882.             $patientBdateYear date_format($getPatientFullDate"d.m.Y");
  3883.             $patientDateDiff $dialogueControllerObj->getUserAge($patientBdateYear);
  3884.             $patientAgeDiff $patientDateDiff->y;
  3885.             // remove addressCallForSiblings 
  3886.             /*if ($patientAgeDiff < 18) {
  3887.                 $komk = $post = $hnr = $vejk = $etag = $sido = "";
  3888.                 $komk = trim($dialogueControllerObj->getFieldValue($patientObject, 'KOMKOD'));
  3889.                 $post = trim($dialogueControllerObj->getFieldValue($patientObject, 'POSTNR'));
  3890.                 $hnr = trim($dialogueControllerObj->getFieldValue($patientObject, 'HUSNR'));
  3891.                 $vejk = trim($dialogueControllerObj->getFieldValue($patientObject, 'VEJKOD'));
  3892.                 $etag = trim($dialogueControllerObj->getFieldValue($patientObject, 'ETAGE'));
  3893.                 $sido = trim($dialogueControllerObj->getFieldValue($patientObject, 'SIDEDOER'));
  3894.                 $addressCallForSiblings = $this->addressCallForSiblings($komk, $post, $hnr, $vejk, $etag, $sido);
  3895.                 $addressSiblingsObject = $addressCallForSiblings->Gctp->System->Service->CprData->Rolle->Table->Row;
  3896.                 foreach ($addressSiblingsObject as $addressSibling) {
  3897.                     $childDOB = trim($dialogueControllerObj->getFieldValue($addressSibling, 'CPRS_FOEDDATO'));
  3898.                     $childCpr = trim($dialogueControllerObj->getFieldValue($addressSibling, 'PNR'));
  3899.                     $childTempName = $dialogueControllerObj->getFieldValue($addressSibling, 'CNVN_ADRNVN');
  3900.                     if($childTempName){
  3901.                     $childExploadeName = explode(",", $childTempName);
  3902.                     $childFirstName = $childExploadeName[1];
  3903.                     $childLastName = $childExploadeName[0];
  3904.                     $childFullName = $childFirstName . ' ' . $childLastName;
  3905.                     $cYear = substr($childDOB, 0, 4);
  3906.                     $cMonth = substr($childDOB, 4, 2);
  3907.                     $cDate = substr($childDOB, 6, 2);
  3908.                     $bdateYear = $cDate . "." . $cMonth . "." . $cYear;
  3909.                     $dateDiff = $dialogueControllerObj->getUserAge($bdateYear);
  3910.                     $childAge = $dateDiff->y;
  3911.                     if ($childCpr != $newPatient->getCpr()) {
  3912.                         $childAddress = '';
  3913.                         $childPostNo = '';
  3914.                         $childCity = '';
  3915.                         if ($childAge < 18) {
  3916.                             $url_in_array = in_array($childCpr, array_column($siblingsArray, 'cprNo'));
  3917.                             if (!$url_in_array) {
  3918.                                 $siblingsArray[$loopCnt]['cprNo'] = $childCpr;
  3919.                                 $siblingsArray[$loopCnt]['fullName'] = $childFullName;
  3920.                                 $siblingsArray[$loopCnt]['address'] = $childAddress;
  3921.                                 $siblingsArray[$loopCnt]['postNo'] = $childPostNo;
  3922.                                 $siblingsArray[$loopCnt]['city'] = $childCity;
  3923.                                 if ($childAge) {
  3924.                                     $siblingsArray[$loopCnt]['age'] = $childAge;
  3925.                                 } else {
  3926.                                     $siblingsArray[$loopCnt]['age'] = 0;
  3927.                                 }
  3928.                                 $loopCnt = ($loopCnt + 1);
  3929.                             }
  3930.                         }
  3931.                     }
  3932.                     }
  3933.                 }
  3934.             }*/
  3935.             //var_dump($siblingsArray, $addressSiblingsObject); die;
  3936.             $newPatient->siblings $siblingsArray;
  3937.             $komunneIdsArray = array(
  3938.                 '0101' => 'København',
  3939.                 '0147' => 'Frederiksberg',
  3940.                 '0151' => 'Ballerup',
  3941.                 '0153' => 'Brøndby',
  3942.                 '0155' => 'Dragør',
  3943.                 '0157' => 'Gentofte',
  3944.                 '0159' => 'Gladsaxe',
  3945.                 '0161' => 'Glostrup',
  3946.                 '0163' => 'Herlev',
  3947.                 '0165' => 'Albertslund',
  3948.                 '0167' => 'Hvidovre',
  3949.                 '0169' => 'Høje-Taastrup',
  3950.                 '0173' => 'Lyngby-Taarbæk',
  3951.                 '0175' => 'Rødovre',
  3952.                 '0183' => 'Ishøj',
  3953.                 '0185' => 'Tårnby',
  3954.                 '0187' => 'Vallensbæk',
  3955.                 '0190' => 'Furesø',
  3956.                 '0201' => 'Allerød',
  3957.                 '0210' => 'Fredensborg',
  3958.                 '0217' => 'Helsingør',
  3959.                 '0219' => 'Hillerød',
  3960.                 '0223' => 'Hørsholm',
  3961.                 '0230' => 'Rudersdal',
  3962.                 '0240' => 'Egedal',
  3963.                 '0250' => 'Frederikssund',
  3964.                 '0253' => 'Greve',
  3965.                 '0259' => 'Køge',
  3966.                 '0260' => 'Halsnæs',
  3967.                 '0265' => 'Roskilde',
  3968.                 '0269' => 'Solrød',
  3969.                 '0270' => 'Gribskov',
  3970.                 '0306' => 'Odsherred',
  3971.                 '0316' => 'Holbæk',
  3972.                 '0320' => 'Faxe',
  3973.                 '0326' => 'Kalundborg',
  3974.                 '0329' => 'Ringsted',
  3975.                 '0330' => 'Slagelse',
  3976.                 '0336' => 'Stevns',
  3977.                 '0340' => 'Sorø',
  3978.                 '0350' => 'Lejre',
  3979.                 '0360' => 'Lolland',
  3980.                 '0370' => 'Næstved',
  3981.                 '0376' => 'Guldborgsund',
  3982.                 '0390' => 'Vordingborg',
  3983.                 '0400' => 'Bornholm',
  3984.                 '0410' => 'Middelfart',
  3985.                 '0411' => 'Christiansø',
  3986.                 '0420' => 'Assens',
  3987.                 '0430' => 'Faaborg-Midtfyn',
  3988.                 '0440' => 'Kerteminde',
  3989.                 '0450' => 'Nyborg',
  3990.                 '0461' => 'Odense',
  3991.                 '0479' => 'Svendborg',
  3992.                 '0480' => 'Nordfyns',
  3993.                 '0482' => 'Langeland',
  3994.                 '0492' => 'Ærø',
  3995.                 '0510' => 'Haderslev',
  3996.                 '0530' => 'Billund',
  3997.                 '0540' => 'Sønderborg',
  3998.                 '0550' => 'Tønder',
  3999.                 '0561' => 'Esbjerg',
  4000.                 '0563' => 'Fanø',
  4001.                 '0573' => 'Varde',
  4002.                 '0575' => 'Vejen',
  4003.                 '0580' => 'Aabenraa',
  4004.                 '0607' => 'Fredericia',
  4005.                 '0615' => 'Horsens',
  4006.                 '0621' => 'Kolding',
  4007.                 '0630' => 'Vejle',
  4008.                 '0657' => 'Herning',
  4009.                 '0661' => 'Holstebro',
  4010.                 '0665' => 'Lemvig',
  4011.                 '0671' => 'Struer',
  4012.                 '0706' => 'Syddjurs',
  4013.                 '0707' => 'Norddjurs',
  4014.                 '0710' => 'Favrskov',
  4015.                 '0727' => 'Odder',
  4016.                 '0730' => 'Randers',
  4017.                 '0740' => 'Silkeborg',
  4018.                 '0741' => 'Samsø',
  4019.                 '0746' => 'Skanderborg',
  4020.                 '0751' => 'Aarhus',
  4021.                 '0756' => 'Ikast-Brande',
  4022.                 '0760' => 'Ringkøbing-Skjern',
  4023.                 '0766' => 'Hedensted',
  4024.                 '0773' => 'Morsø',
  4025.                 '0779' => 'Skive',
  4026.                 '0787' => 'Thisted',
  4027.                 '0791' => 'Viborg',
  4028.                 '0810' => 'Brønderslev',
  4029.                 '0813' => 'Frederikshavn',
  4030.                 '0820' => 'Vesthimmerlands',
  4031.                 '0825' => 'Læsø',
  4032.                 '0840' => 'Rebild',
  4033.                 '0846' => 'Mariagerfjord',
  4034.                 '0849' => 'Jammerbugt',
  4035.                 '0851' => 'Aalborg',
  4036.                 '0860' => 'Hjørring');
  4037.             $komunneId trim($dialogueControllerObj->getFieldValue($patientObject'KOMKOD'));
  4038.             if (array_key_exists($komunneId$komunneIdsArray)) {
  4039.                 $komunneName $komunneIdsArray[$komunneId];
  4040.                 $session->set("komunneName"$komunneIdsArray[$komunneId]);
  4041.                 $session->set("komunneId",$komunneId);
  4042.             } else if($newPatient->getIsDummyPatient()) {
  4043.                 $komunneName "Københavns";
  4044.                 $session->set("komunneName""Københavns");
  4045.                 $session->set("komunneId",0);
  4046.             } else {
  4047.                 $komunneName "Københavns";
  4048.                 $session->set("komunneName""");
  4049.                 $session->set("komunneId","");
  4050.             }
  4051.             $newPatient->setKommuneId($komunneId$komunneId:null);
  4052.             //var_dump($komunneName); die;
  4053.             
  4054.             //Save patient
  4055.             $getFullDate $dialogueControllerObj->getBirthDate($newPatient->getCpr());
  4056.             $bdateYear date_format($getFullDate"d.m.Y");
  4057.             $dateDiff $dialogueControllerObj->getUserAge($bdateYear);
  4058.             if($newPatient->getIsFakeCpr() != '1'){
  4059.                 $newPatient->setChildAge($dateDiff->y);
  4060.             }
  4061.             if (count($newPatient->siblings) > 0) {
  4062.                 foreach ($newPatient->siblings as $sibling) {
  4063.                     $patientSiblingObj $em->getRepository(PatientSibling::class)->findOneBy(array( 'patient' => $newPatient'cpr' => $sibling['cprNo']));
  4064.                     if(!$patientSiblingObj){
  4065.                         $patientSiblingObj = new PatientSibling();
  4066.                         $patientSiblingObj->setPatient($newPatient);
  4067.                         $patientSiblingObj->setCpr($sibling['cprNo']);
  4068.                         $patientSiblingObj->setFullName($sibling['fullName']);
  4069.                         $patientSiblingObj->setAddress($sibling['address']);
  4070.                         $patientSiblingObj->setPostNo($sibling['postNo']);
  4071.                         $patientSiblingObj->setCity($sibling['city']);
  4072.                         $patientSiblingObj->setAge($sibling['age']);
  4073.                         $entityManager->persist($patientSiblingObj);
  4074.                         $entityManager->flush();
  4075.                     }else{
  4076.                         $patientSiblingUpdateObj $em->getRepository(PatientSibling::class)->findBy(array('patient' => $newPatient));
  4077.                         foreach ($patientSiblingUpdateObj as $siblingUpdateObj) {
  4078.                             if(($siblingUpdateObj && $patientSiblingObj) && ($siblingUpdateObj->getId() == $patientSiblingObj->getId())){
  4079.                                 $siblingUpdateObj->setIsDeleted(false);
  4080.                                 $siblingUpdateObj->setAddress($sibling['address']);
  4081.                                 $siblingUpdateObj->setPostNo($sibling['postNo']);
  4082.                                 $siblingUpdateObj->setCity($sibling['city']);
  4083.                                 $siblingUpdateObj->setAge($sibling['age']);
  4084.                                 $entityManager->persist($siblingUpdateObj);
  4085.                                 $entityManager->flush();
  4086.                             }else{
  4087.                                 $siblingUpdateObj->setIsDeleted(true);
  4088.                                 $entityManager->persist($siblingUpdateObj);
  4089.                                 $entityManager->flush();
  4090.                             }
  4091.                         }
  4092.                     }
  4093.                 }
  4094.             }else{
  4095.                 $patientSiblingUpdateObj $em->getRepository(PatientSibling::class)->findBy(array('patient' => $newPatient));
  4096.                 foreach ($patientSiblingUpdateObj as $siblingUpdateObj) {
  4097.                     $siblingUpdateObj->setIsDeleted(true);
  4098.                     $entityManager->persist($siblingUpdateObj);
  4099.                     $entityManager->flush();
  4100.                 }
  4101.             }
  4102.             //In stam data we have check box for “Hemmelig adresse”. 
  4103.             //If value found check it - if not it is blank (unchecked).
  4104.             $isSecretAddress $dialogueControllerObj->getFieldValue($patientObject'BESKYT');
  4105.             $isSecretAddressVal false;
  4106.             if (!is_null($isSecretAddress)) {
  4107.                 $isSecretAddressVal true;
  4108.             }
  4109.             //if ($isSecretAddressVal) {
  4110.                 $newpatientUserObj $newPatient->getUser();
  4111.                 $newpatientUserObj->setIsSecretAddress($isSecretAddressVal);
  4112.                 $entityManager->persist($newpatientUserObj);
  4113.                 $entityManager->flush();
  4114.             //}
  4115.             //var_dump($isSecretAddressVal,$isSecretAddress); die;
  4116.             if (!$newPatient->isPatientMajor()) {
  4117.                 
  4118.                 $newPatient->patientInformationObject $this->getUserProfileI2Calls($newPatient->getCpr());
  4119.                 $sessionPatientInformationObject $session->set('sessionPatientInformationObject'$newPatient->patientInformationObject);
  4120.                 $newPatient->patientInformationObject $session->get('sessionPatientInformationObject');
  4121.                 if (count($newPatient->patientInformationObject) > 0) {
  4122.                     $loopIndex 0;
  4123.                     foreach ($newPatient->patientInformationObject as $patientInformation) {
  4124.                         //If only one record found in patientInformationObject then we have to
  4125.                         //Stored data only in PatientInformation entity
  4126.                         //If more than one records are exist then we have to stored first record
  4127.                         //in PatientInformation entity and setIsMultiple record = true and then other all
  4128.                         //entries are stored in PatientInformationDetails entity
  4129.                         if ($loopIndex == 0) {
  4130.                             //$patientInformationObj = $em->getRepository(PatientInformation::class)->findOneBy(array("patient" => $newPatient, "bookingId" => $patientInformation['bookingId']));
  4131.                             $patientInformationObj $em->getRepository(PatientInformation::class)->findOneBy(array("patient" => $newPatient));
  4132.                             if (!$patientInformationObj) {
  4133.                                 $patientInformationObj = new PatientInformation();
  4134.                             }
  4135.                             if (count($newPatient->patientInformationObject) > 1) {
  4136.                                 $patientInformationObj->setIsMultiple(true);
  4137.                             } else {
  4138.                                 $patientInformationObj->setIsMultiple(false);
  4139.                             }
  4140.                             $shortName $patientInformation['institutionShortName'];
  4141.                             if ($shortName != "") {
  4142.                                 $institudeResponce $this->getI2InstitudeDataCalls($shortName);
  4143.                                 if ($institudeResponce) {
  4144.                                     /* $patientInformationObj->setCitizenInstitutionKKInstitutionType($institudeResponce['institution']['careType']);
  4145.                                       $patientInformationObj->setCitizenInstitutionOwner($institudeResponce['institution']['dayCareType']); */
  4146.                                     $careAndDayCareTypeArray = array('careTypeKey' => $institudeResponce['institution']['careType'], 'dayCareTypeKey' => $institudeResponce['institution']['dayCareType']);
  4147.                                     $i2InstitutionValue $dialogueControllerObj->getInstitutionValueI2Call($careAndDayCareTypeArray);
  4148.                                     $patientInformationObj->setCitizenInstitutionKKInstitutionType($i2InstitutionValue['citizenInstitutionKkinstitutionType']);
  4149.                                     $patientInformationObj->setCitizenInstitutionOwner($i2InstitutionValue['citizenInstitutionOwner']);
  4150.                                 }
  4151.                             }
  4152.                             //enhedstrae call
  4153.                             //Get institute master information
  4154.                             if (array_key_exists("institutionShortName"$patientInformation)) {
  4155.                                 $citizenInstitutionNumber trim($patientInformation['institutionShortName']);
  4156.                                 $patientInstitutionMasterObj $em->getRepository(JoMasterInformation::class)->findOneBy(array("inr" => $citizenInstitutionNumber));
  4157.                                 if ($patientInstitutionMasterObj) {
  4158.                                     //Page 5 JOSA Elev call and enhedstrae call mapping 30 Apl 2020.pdf
  4159.                                     $patientInformationObj->setCitizenInstitutionMail($patientInstitutionMasterObj->getMail());
  4160.                                     $patientInformationObj->setCitizenInstitutionTelephone($patientInstitutionMasterObj->getTelefon());
  4161.                                     $patientInformationObj->setCitizenInstitutionArea($patientInstitutionMasterObj->getDistrikt());
  4162.                                     $patientInformationObj->setCitizenInstitutionManager($patientInstitutionMasterObj->getNavn());
  4163.                                     //Page 6 JOSA Elev call and enhedstrae call mapping 30 Apl 2020.pdf
  4164.                                     $patientInformationObj->setCitizenInstitutionKKInstitutionType($patientInstitutionMasterObj->getOrganisationstype());
  4165.                                     $patientInformationObj->setHomepage($patientInstitutionMasterObj->getWww());
  4166.                                     $patientInformationObj->setCitizenInstitutionAddress($patientInstitutionMasterObj->getAdresse());
  4167.                                     $patientInformationObj->setCitizenInstitutionTownArea($patientInstitutionMasterObj->getBydel());
  4168.                                     $patientInformationObj->setDepartment($patientInstitutionMasterObj->getLokationsnavn());
  4169.                                     $patientInformationObj->setCitizenInstitutionLocationType($patientInstitutionMasterObj->getIType());
  4170.                                     $patientUserObj $newPatient->getUser();
  4171.                                     $patientUserObj->setCvrNo($patientInstitutionMasterObj->getCvr());
  4172.                                     $entityManager->persist($patientUserObj);
  4173.                                     $entityManager->flush();
  4174.                                 }
  4175.                             }
  4176.                         } else {
  4177.                             $patientInformationObj $em->getRepository(PatientInformationDetails::class)->findOneBy(array("patient" => $newPatient));
  4178.                             if (!$patientInformationObj) {
  4179.                                 $patientInformationObj = new PatientInformationDetails();
  4180.                             }
  4181.                         }
  4182.                         $patientInformationObj->setUser($newPatient->getUser());
  4183.                         $patientInformationObj->setPatient($newPatient);
  4184.                         if (array_key_exists("bookingId"$patientInformation)) {
  4185.                             $patientInformationObj->setBookingId($patientInformation['bookingId']);
  4186.                         }
  4187.                         if (array_key_exists("institutionName"$patientInformation)) {
  4188.                             $patientInformationObj->setCitizenInstitutionName(trim($patientInformation['institutionName']));
  4189.                         }
  4190.                         if (array_key_exists("institutionShortName"$patientInformation)) {
  4191.                             $patientInformationObj->setCitizenInstitutionNumber(trim($patientInformation['institutionShortName']));
  4192.                         }
  4193.                         if (array_key_exists("startDate"$patientInformation)) {
  4194.                             $patientInformationObj->setCitizen_institution_from_date(new \Datetime(date('Y-m-d'strtotime($patientInformation['startDate']))));
  4195.                         }
  4196.                         if (array_key_exists("endDate"$patientInformation)) {
  4197.                             $patientInformationObj->setCitizenInstitutionToDate(new \Datetime(date('Y-m-d'strtotime($patientInformation['endDate']))));
  4198.                         }
  4199.                         if (array_key_exists("module"$patientInformation)) {
  4200.                             if (array_key_exists("description"$patientInformation['module'])) {
  4201.                                 $patientInformationObj->setInstitutionType($patientInformation['module']['description']);
  4202.                             }
  4203.                             if (array_key_exists("name"$patientInformation['module'])) {
  4204.                                 $patientInformationObj->setCitizenInstitutionModul($patientInformation['module']['name']);
  4205.                             }
  4206.                         }
  4207.                         if (array_key_exists("room"$patientInformation)) {
  4208.                             $patientInformationObj->setCitizenInstitutionStatus($patientInformation['room']);
  4209.                         }
  4210.                         $entityManager->persist($patientInformationObj);
  4211.                         $entityManager->flush();
  4212.                         $loopIndex = ($loopIndex 1);
  4213.                     }
  4214.                 }
  4215.                 $newPatient->patientSchoolObject $this->getI2ElevSchoolCalls($newPatient->getCpr());
  4216.                 $sessionPatientSchoolObject $session->set('sessionPatientSchoolObject'$newPatient->patientSchoolObject);
  4217.                 $newPatient->patientSchoolObject $session->get('sessionPatientSchoolObject');
  4218.                 if (count($newPatient->patientSchoolObject) > 0) {
  4219.                     $schoolLoopIndex 0;
  4220.                     $lastLoopIndex 0;
  4221.                     $isMultipleRecords false;
  4222.                     if (array_key_exists('historik'$newPatient->patientSchoolObject)) {
  4223.                         $lastLoopIndex = (count($newPatient->patientSchoolObject['historik']) - 1);
  4224.                         $isMultipleRecords true;
  4225.                     }
  4226.                     $patientSchoolInformation $newPatient->patientSchoolObject;
  4227.                     $patientInformationObj $em->getRepository(PatientInformation::class)->findOneBy(array("patient" => $newPatient));
  4228.                     if (!$patientInformationObj) {
  4229.                         $patientInformationObj = new PatientInformation();
  4230.                     }
  4231.                     if ($isMultipleRecords && count($newPatient->patientSchoolObject['historik']) > 1) {
  4232.                         $patientInformationObj->setIsMultiple(true);
  4233.                     } else {
  4234.                         $patientInformationObj->setIsMultiple(false);
  4235.                     }
  4236.                     $patientInformationObj->setUser($newPatient->getUser());
  4237.                     $patientInformationObj->setPatient($newPatient);
  4238.                     if (array_key_exists("skolenavn"$patientSchoolInformation)) {
  4239.                         $patientInformationObj->setCitizenSchoolName($patientSchoolInformation['skolenavn']);
  4240.                     }
  4241.                     if (array_key_exists("klassetrin"$patientSchoolInformation)) {
  4242.                         $patientInformationObj->setCitizenSchoolLevel($patientSchoolInformation['klassetrin']);
  4243.                     }
  4244.                     if (array_key_exists("klassebetegnelse"$patientSchoolInformation)) {
  4245.                         $patientInformationObj->setCitizenSchoolClass($patientSchoolInformation['klassebetegnelse']);
  4246.                     }
  4247.                     if (array_key_exists("skolenr"$patientSchoolInformation)) {
  4248.                         $patientInformationObj->setCitizenSchoolNumber($patientSchoolInformation['skolenr']);
  4249.                     }
  4250.                     if (array_key_exists("skoletype"$patientSchoolInformation)) {
  4251.                         $patientInformationObj->setCitizenSchoolType($patientSchoolInformation['skoletype']);
  4252.                     }
  4253.                     if (array_key_exists("grunddistrSkolenavn"$patientSchoolInformation)) {
  4254.                         $patientInformationObj->setCitizenSchoolDistrict($patientSchoolInformation['grunddistrSkolenavn']);
  4255.                     }
  4256.                     if (array_key_exists("elevartTxt"$patientSchoolInformation)) {
  4257.                         $patientInformationObj->setCitizenPupilCat($patientSchoolInformation['elevartTxt']);
  4258.                     }
  4259.                     if (array_key_exists("klasselaererNavn"$patientSchoolInformation)) {
  4260.                         $patientInformationObj->setCitizenSchoolTeacher($patientSchoolInformation['klasselaererNavn']);
  4261.                     }
  4262.                     if (array_key_exists("klasseartTxt"$patientSchoolInformation)) {
  4263.                         $patientInformationObj->setCitizenClasseCat($patientSchoolInformation['klasseartTxt']);
  4264.                     }
  4265.                     if (array_key_exists("klassetypeTxt"$patientSchoolInformation)) {
  4266.                         $patientInformationObj->setCitizenClasseType($patientSchoolInformation['klassetypeTxt']);
  4267.                     }
  4268.                     if (array_key_exists("historik"$patientSchoolInformation)) {
  4269.                         if (array_key_exists("klasselaererInit"$patientSchoolInformation['historik'][$lastLoopIndex])) {
  4270.                             $patientInformationObj->setCitizenSchoolTeacherIntials($patientSchoolInformation['historik'][$lastLoopIndex]['klasselaererInit']);
  4271.                         }
  4272.                         if (array_key_exists("skoleklasseFraDato"$patientSchoolInformation['historik'][$lastLoopIndex])) {
  4273.                             $patientInformationObj->setCitizenSchoolYear(substr($patientSchoolInformation['historik'][$lastLoopIndex]['skoleklasseFraDato'], 69) . "/" date("Y"));
  4274.                         }
  4275.                         if (array_key_exists("skoleklasseFraDato"$patientSchoolInformation['historik'][0])) {
  4276.                             $patientInformationObj->setCitizenSchoolStart(str_replace("/""."$patientSchoolInformation['historik'][0]['skoleklasseFraDato']));
  4277.                         }
  4278.                         if (array_key_exists("skoleklasseTilDato"$patientSchoolInformation['historik'][0])) {
  4279.                             $patientInformationObj->setCitizenSchoolEnd($patientSchoolInformation['historik'][0]['skoleklasseTilDato']);
  4280.                         }
  4281.                     }
  4282.                     if (array_key_exists("primaerFagansvarlig"$patientSchoolInformation)) {
  4283.                         if (array_key_exists("medarbejdernavn"$patientSchoolInformation['primaerFagansvarlig'])) {
  4284.                             $adkode "";
  4285.                             if (array_key_exists("adkode"$patientSchoolInformation['primaerFagansvarlig'])) {
  4286.                                 $adkode ", ".$patientSchoolInformation['primaerFagansvarlig']['adkode'];
  4287.                             }
  4288.                             $patientInformationObj->setCitizenSchoolNurse($patientSchoolInformation['primaerFagansvarlig']['medarbejdernavn'].$adkode);
  4289.                         }
  4290.                     }
  4291.                     if (array_key_exists("modersmaal"$patientSchoolInformation)) {
  4292.                         $nativeLanguage $patientSchoolInformation['modersmaal'];
  4293.                         $newPatientUserObj $newPatient->getUser();
  4294.                         if (strlen($nativeLanguage) > 0) {
  4295.                             $newPatientUserObj->setNativeLanguage($nativeLanguage);
  4296.                         }
  4297.                     }
  4298.                     //enhedstrae call
  4299.                     //Get school master information
  4300.                     if (array_key_exists("skolenr"$patientSchoolInformation)) {
  4301.                         $citizenSchoolNumber $patientSchoolInformation['skolenr'];
  4302.                         $patientSchoolMasterObj $em->getRepository(JoMasterInformation::class)->findOneBy(array("skolenr" => $citizenSchoolNumber));
  4303.                         if ($patientSchoolMasterObj) {
  4304.                             //Page 1  JOSA Elev call and enhedstrae call mapping 30 Apl 2020.pdf
  4305.                             $patientInformationObj->setCitizenSchoolMail($patientSchoolMasterObj->getEmail());
  4306.                             $patientInformationObj->setCitizenSchoolTelephone($patientSchoolMasterObj->getTelephone());
  4307.                             $patientInformationObj->setCitizenSchoolArea($patientSchoolMasterObj->getDistrikt());
  4308.                             if (trim($patientInformationObj->getCitizenSchoolManager()) == "") {
  4309.                                 $patientInformationObj->setCitizenSchoolManager($patientSchoolMasterObj->getSkoleleder());
  4310.                             }
  4311.                             //Page 2  JOSA Elev call and enhedstrae call mapping 30 Apl 2020.pdf
  4312.                             $patientInformationObj->setCitizenSchoolTownArea($patientSchoolMasterObj->getBydel());
  4313.                             $patientInformationObj->setCitizenSchoolOwner($patientSchoolMasterObj->getEjerforhold());
  4314.                             if ($patientInformationObj->getCitizenSchoolAdress() == "") {
  4315.                                 $patientInformationObj->setCitizenSchoolAdress($patientSchoolMasterObj->getAdresse() . ", " $patientSchoolMasterObj->getPostnr() . " " $patientSchoolMasterObj->getSBy());
  4316.                             }
  4317.                         }
  4318.                     }
  4319.                     $entityManager->persist($patientInformationObj);
  4320.                     $entityManager->flush();
  4321.                     if ($isMultipleRecords && count($newPatient->patientSchoolObject['historik']) > 1) {
  4322.                         $historyLoopIndex 0;
  4323.                         foreach ($newPatient->patientSchoolObject['historik'] as $patientSchoolInformationHistory) {
  4324.                             //if($historyLoopIndex > 0) {
  4325.                             $patientInformationObj $em->getRepository(PatientInformationDetails::class)->findOneBy(array("patient" => $newPatient));
  4326.                             if(!$patientInformationObj) {
  4327.                                 $patientInformationObj = new PatientInformationDetails();
  4328.                             }
  4329.                             $patientInformationObj->setUser($newPatient->getUser());
  4330.                             $patientInformationObj->setPatient($newPatient);
  4331.                             if (array_key_exists("klasselaererInit"$newPatient->patientSchoolObject['historik'][$lastLoopIndex])) {
  4332.                                 $patientInformationObj->setCitizenSchoolTeacherIntials($newPatient->patientSchoolObject['historik'][$lastLoopIndex]['klasselaererInit']);
  4333.                             }
  4334.                             if (array_key_exists("skoleklasseFraDato"$newPatient->patientSchoolObject['historik'][$lastLoopIndex])) {
  4335.                                 $patientInformationObj->setCitizenSchoolYear($newPatient->patientSchoolObject['historik'][$lastLoopIndex]['skoleklasseFraDato']);
  4336.                             }
  4337.                             if (array_key_exists("skoleklasseFraDato"$patientSchoolInformationHistory)) {
  4338.                                 $patientInformationObj->setCitizenSchoolStart(str_replace("/""."$patientSchoolInformationHistory['skoleklasseFraDato']));
  4339.                             }
  4340.                             if (array_key_exists("skoleklasseTilDato"$patientSchoolInformationHistory)) {
  4341.                                 $patientInformationObj->setCitizenSchoolEnd(str_replace("/""."$patientSchoolInformationHistory['skoleklasseTilDato']));
  4342.                             }
  4343.                             if (array_key_exists("skolenavn"$patientSchoolInformationHistory)) {
  4344.                                 $patientInformationObj->setCitizenSchoolName($patientSchoolInformationHistory['skolenavn']);
  4345.                             }
  4346.                             if (array_key_exists("klasse"$patientSchoolInformationHistory)) {
  4347.                                 $patientInformationObj->setCitizenSchoolClass($patientSchoolInformationHistory['klasse']);
  4348.                             }
  4349.                             if (array_key_exists("skoletrin"$patientSchoolInformationHistory)) {
  4350.                                 $patientInformationObj->setCitizenSchoolLevel($patientSchoolInformationHistory['skoletrin']);
  4351.                             }
  4352.                             if (array_key_exists("klasseart"$patientSchoolInformationHistory)) {
  4353.                                 $patientInformationObj->setCitizenClasseCat($patientSchoolInformationHistory['klasseart']);
  4354.                             }
  4355.                             $entityManager->persist($patientInformationObj);
  4356.                             $entityManager->flush();
  4357.                             //}
  4358.                             $historyLoopIndex = ($historyLoopIndex 1);
  4359.                         }
  4360.                     }
  4361.                     $schoolLoopIndex = ($schoolLoopIndex 1);
  4362.                     //}
  4363.                 }
  4364.             }
  4365.             $newPatient->setUpdatedAt(new \DateTime());
  4366.             $entityManager->persist($newPatient);
  4367.             $entityManager->flush();
  4368.         }
  4369.     }
  4370.         return true;
  4371.     }
  4372.     private function doSoapRequest($service$cprNo) {
  4373.         $par '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="Familie+"> <CprServiceHeader r="Familie+"> <Key> <Field r="PNR" v="' $cprNo '"/> </Key> </CprServiceHeader> </Service> </System> </Gctp> ]]>';
  4374.         $_cdata = new \SoapVar($parXSD_ANYXML);
  4375.         $gctpMessage = new \SoapParam(new \SoapVar($parXSD_ANYXML), 'gctpMessage');
  4376.         $wsdl $this->get('kernel')->getRootDir() . '/cprservice/CprLookupService.wsdl';
  4377.         $endpoint 'https://prod.serviceplatformen.dk/service/CPRLookup/CPRLookup/2';
  4378.         $certificate $this->get('kernel')->getRootDir() . '/cprservice/cert/alldialogue_16mar.cert.key.pem';
  4379.         $password 'Werner1978';
  4380.         $options = array(
  4381.             'location' => $endpoint,
  4382.             'keep_alive' => true,
  4383.             'trace' => 1,
  4384.             'local_cert' => $certificate,
  4385.             'passphrase' => $password,
  4386.             'cache_wsdl' => WSDL_CACHE_NONE
  4387.         );
  4388.         try {
  4389.             $parametros[] = new \SoapParam(new \SoapVar(1067XSD_STRINGnullnull'InvocationContext''urn'), 'InvocationContext');
  4390.             $parametros[] = new \SoapParam(new \SoapVar('site'XSD_STRINGnullnull'canalVenda''urn'), 'canalVenda');
  4391.             $parametros[] = new \SoapParam(1067'operacaoparceiro');
  4392.             $parametros[] = new \SoapParam(new \SoapVar($parXSD_ANYXML), 'InvocationContext');
  4393.             $soapClient = new SoapClientDebug($wsdl$options);
  4394.             $reqData = array('callGCTPCheckServiceRequest' => array('InvocationContext' => array(
  4395.                         'ServiceAgreementUUID' => '24ed133a-ad35-4b59-8ef5-f7cfcc058a40',  //serviceaftale UUID for josaFaxe (Familie+)
  4396.                         'UserSystemUUID' => 'ffa2ea04-bc05-461f-8e8e-59833045eef8'//System UUID same for all
  4397.                         'UserUUID' => '6a4a5130-d96c-4ddd-a2df-d095bc40a813'//KOMMUNE UUID for josaFaxe
  4398.                         'ServiceUUID' => 'a34cf599-26e4-4609-bfbd-2490d3d1c3ab'))); //Familie+ UUID
  4399.             $reqData['callGCTPCheckServiceRequest']['gctpMessage'] = ($par);
  4400.             $data = ($soapClient->__call('callGctpService'$reqData));
  4401.         } catch (Exception $e) {
  4402.             $code $e->getCode();
  4403.             return false;
  4404.         }
  4405.         //print_r($data->result); die;
  4406.         //file_put_contents("D:/test/".$cprNo.".xml", $data->result);
  4407.         $xml simplexml_load_string($data->result);
  4408.         return $xml;
  4409.     }
  4410.     
  4411.     public function addressCallForSiblings($komk,$post,$hnr,$vejk,$etag,$sido) {
  4412.         //var_dump($komk,$post,$hnr,$vejk,$etag,$sido);//die('ff');
  4413.         
  4414.         $eTagString ='<Field r="ETAG" v="'.$etag.'"/>';
  4415.         $sideDoerString '<Field r="SIDO" v="'.$sido.'"/>';
  4416.         
  4417.         $parString '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/><Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
  4418.         if($etag !="" && $sido == "") {
  4419.             $parString '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/>'.$eTagString.'<Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
  4420.         }
  4421.         if($etag == "" && $sido !="") {
  4422.             $parString '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/>'.$sideDoerString.'<Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
  4423.         }
  4424.         if($etag != "" && $sido !="") {
  4425.             $parString '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/>'.$eTagString.$sideDoerString.'<Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
  4426.         }
  4427.         
  4428.         $par $parString;
  4429.         //$par = '<![CDATA[ <Gctp v="1.0"> <System r="CprSoeg"> <Service r="ADRSOG1"> <CprServiceHeader r="ADRSOG1"><Key><Field r="KOMK" v="'.$komk.'"/><Field r="POST" v="'.$post.'"/><Field r="HNR" v="'.$hnr.'"/><Field r="VEJK" v="'.$vejk.'"/><Field r="ETAG" v="'.$etag.'"/><Field r="SIDO" v="'.$sido.'"/><Field r="ADRBESKYT" v=""/></Key></CprServiceHeader></Service></System></Gctp> ]]>';
  4430.         //var_dump($par); //die;
  4431.         
  4432.         $_cdata = new \SoapVar($parXSD_ANYXML);
  4433.         $gctpMessage = new \SoapParam(new \SoapVar($parXSD_ANYXML), 'gctpMessage');
  4434.         //$wsdl = 'G:/liveprojects/cprservice/CprLookupService.wsdl';
  4435.         //$certificate = 'G:/liveprojects/cprservice/cert/alldialogue_16mar.cert.key.pem';
  4436.         $wsdl $this->get('kernel')->getRootDir() . '/cprservice/CprLookupService.wsdl';
  4437.         $endpoint 'https://prod.serviceplatformen.dk/service/CPRLookup/CPRLookup/2';
  4438.         $certificate $this->get('kernel')->getRootDir() . '/cprservice/cert/alldialogue_16mar.cert.key.pem';
  4439.         $password 'Werner1978';
  4440.         $options = array(
  4441.             'location' => $endpoint,
  4442.             'keep_alive' => true,
  4443.             'trace' => 1,
  4444.             'local_cert' => $certificate,
  4445.             'passphrase' => $password,
  4446.             'cache_wsdl' => WSDL_CACHE_NONE
  4447.         );
  4448.         try {
  4449.             $soapClient = new SoapClientDebug($wsdl$options);
  4450.             $reqData = array('callGCTPCheckServiceRequest' => array('InvocationContext' => array(
  4451.                         'ServiceAgreementUUID' => '1ea87a27-1f9f-4985-94f3-723cbc950d29',  //serviceaftale UUID for josaFaxe (ADRSOG1)
  4452.                         'UserSystemUUID' => 'ffa2ea04-bc05-461f-8e8e-59833045eef8'//System UUID same for all
  4453.                         'UserUUID' => '6a4a5130-d96c-4ddd-a2df-d095bc40a813'//KOMMUNE UUID for josaFaxe
  4454.                         'ServiceUUID' => '6538f113-b1e6-4b21-8fe1-28b7bf78a1bd'))); //ADRSOG1 UUID
  4455.             $reqData['callGCTPCheckServiceRequest']['gctpMessage'] = ($par);
  4456.             $data = ($soapClient->__call('callGctpService'$reqData));
  4457.             //print_r($data->result); die;
  4458.         } catch (Exception $e) {
  4459.             var_dump($e);
  4460.         }
  4461.         
  4462.         $xml simplexml_load_string($data->result);
  4463.         return $xml;
  4464.     }
  4465.     
  4466.     public function getUserProfileI2Calls($username) {
  4467.         $I2HostURL $this->container->getParameter('I2HostURL');
  4468.         $I2SubscriptionKey $this->container->getParameter('I2InstSubscriptionKey');
  4469.         $isCopenhagen $this->container->getParameter('isCopenhagen');
  4470.         $callId $isCopenhagen 101 320//101 for København : 320 for faxe
  4471.         
  4472.         try {
  4473.             // this header is added to all requests made by this client
  4474.             $client HttpClient::create(['headers' => [
  4475.                 //'Accept' => 'text/plain',
  4476.                 'Ocp-Apim-Subscription-Key' => $I2SubscriptionKey,
  4477.                 'Content-Type' => 'application/json',
  4478.             ]]);
  4479.             $getRequestUrl "https://$I2HostURL/ww/api/v1/municipalities/$callId/enrollments/forchild";
  4480.             $response $client->request('POST'$getRequestUrl, [
  4481.                 // defining data using an array of parameters
  4482.                 //'body' => '1204075502',
  4483.                 'body' => "'".$username."'",
  4484.             ]);
  4485.             $statusCode $response->getStatusCode();
  4486.             // $statusCode = 200
  4487.             if($statusCode == 200){
  4488.                 $contentType $response->getHeaders()['content-type'][0];
  4489.                 // $contentType = 'application/json'
  4490.                 $content $response->getContent();
  4491.                 $isJSON $this->isJSON($content);
  4492.                 //var_dump($isJSON); die;
  4493.                 if($isJSON) {
  4494.                     // $content = '{"id":521583, "name":"symfony-docs", ...}'
  4495.                     $content $response->toArray();
  4496.                     // $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
  4497.                     //var_dump($content); die("end");
  4498.                     return $content;
  4499.                 } else {
  4500.                     return array();
  4501.                 }
  4502.             } else {
  4503.                 //throw new \Exception('Error code:'.$statusCode);
  4504.                 //return array('Error code' => $statusCode);
  4505.                 return array();
  4506.             }
  4507.         } catch (TransportException $e) {
  4508.             
  4509.             //var_dump($e->getMessage());
  4510.             //die;
  4511.             return array();
  4512.         } catch(Exception $p){return array();}
  4513.         return $content;
  4514.     }
  4515.     
  4516.     public function isJSON($string){
  4517.         return is_string($string) && is_array(json_decode($stringtrue)) && (json_last_error() == JSON_ERROR_NONE) && strlen($string) > true false;
  4518.     }
  4519.     
  4520.     private function getI2InstitudeDataCalls($shortName) {
  4521.         $I2HostURL $this->container->getParameter('I2HostURL');
  4522.         $I2InstSubscriptionKey $this->container->getParameter('I2InstSubscriptionKey');
  4523.         $isCopenhagen $this->container->getParameter('isCopenhagen');
  4524.         $callId $isCopenhagen 101 320//101 for København : 320 for faxe
  4525.         
  4526.         //var_dump($I2HostURL, $I2InstSubscriptionKey, $shortName); die;
  4527.         try{
  4528.             // this header is added to all requests made by this client
  4529.             $client HttpClient::create(['headers' => [
  4530.                 //'Accept' => 'text/plain',
  4531.                 'Ocp-Apim-Subscription-Key' => $I2InstSubscriptionKey,
  4532.                 'Content-Type' => 'application/json',
  4533.             ]]);
  4534.             $getRequestUrl "https://$I2HostURL/ww/api/v1/municipalities/$callId/institutions/byShortName/$shortName/details";
  4535.             $response $client->request('GET'$getRequestUrl, [
  4536.                 // defining data using an array of parameters
  4537.                 //'body' => '1204075502',
  4538.                 //'body' => "'".$username."'",
  4539.             ]);
  4540.             $statusCode $response->getStatusCode();
  4541.             // $statusCode = 200
  4542.             if($statusCode == 200){
  4543.                 $contentType $response->getHeaders()['content-type'][0];
  4544.                 // $contentType = 'application/json'
  4545.                 $content $response->getContent();
  4546.                 $isJSON $this->isJSON($content);
  4547.                 //var_dump($isJSON); die;
  4548.                 if($isJSON) {
  4549.                     // $content = '{"id":521583, "name":"symfony-docs", ...}'
  4550.                     $content $response->toArray();
  4551.                     // $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
  4552.                     //var_dump($content); die("end");
  4553.                     return $content;
  4554.                 } else {
  4555.                     return array();
  4556.                 }
  4557.             } else {
  4558.                 //throw new \Exception('Error code:'.$statusCode);
  4559.                 //return array('Error code' => $statusCode);
  4560.                 return array();
  4561.             }
  4562.         } catch (TransportException $e) {
  4563.             
  4564.             //var_dump($e->getMessage());
  4565.             //die;
  4566.             return array();
  4567.         } catch(Exception $p){return array();}
  4568.         return $content;
  4569.     }
  4570.     
  4571.     private function getI2ElevSchoolCalls($username) {
  4572.         /*$stresponce = file_get_contents('C:/projects/josa/josa/2106065678.json');
  4573.         if($stresponce) {
  4574.             $content = json_decode($stresponce, true);
  4575.             //var_Dump($content);die;
  4576.             return $content;
  4577.         }*/
  4578.         
  4579.         $profileAuthentication $this->container->getParameter('profileAuthentication');
  4580.         $profileBaseUrl $this->container->getParameter('profileBaseUrl');
  4581.         $profileToken $this->container->getParameter('profileToken');
  4582.         try {
  4583.             // this header is added to all requests made by this client
  4584.             $client HttpClient::create(['verify_host'=>false,'headers' => [
  4585.                 //'Accept' => 'text/plain',
  4586.                 'Authorization' => $profileAuthentication,
  4587.                 'Ocp-Apim-Subscription-Key' => $profileToken,
  4588.                 'Accept' => 'text/plain',
  4589.             ]]);
  4590.             $getRequestUrl "https://$profileBaseUrl/josa/v1/elev";
  4591.             $response $client->request('GET'$getRequestUrl, [
  4592.                 // defining data using an array of parameters
  4593.                 //'body' => '2106065678',
  4594.                 //'cprNr' => "'".$username."'",
  4595.                 'query' => [
  4596.                     'cprNr' => "$username",
  4597.                 ],
  4598.             ]);
  4599.             $statusCode $response->getStatusCode();
  4600.             // $statusCode = 200
  4601.             if($statusCode == 200){
  4602.                 $contentType $response->getHeaders()['content-type'][0];
  4603.                 // $contentType = 'application/json'
  4604.                 $content $response->getContent();
  4605.                 $isJSON $this->isJSON($content);
  4606.                 //var_dump($isJSON, $content); die;
  4607.                 if($isJSON) {
  4608.                     // $content = '{"id":521583, "name":"symfony-docs", ...}'
  4609.                     $content $response->toArray();
  4610.                     // $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
  4611.                     //var_dump($content); die("end");
  4612.                     return $content;
  4613.                 } else {
  4614.                     return array();
  4615.                 }
  4616.             } else {
  4617.                 //throw new \Exception('Error code:'.$statusCode);
  4618.                 //return array('Error code' => $statusCode);
  4619.                 return array();
  4620.             }
  4621.         } catch (TransportException $e) {
  4622.             
  4623.             //var_dump($e->getMessage());
  4624.             //die;
  4625.             return array();
  4626.         } catch(Exception $p){return array();}
  4627.         return $content;
  4628.     }
  4629.     
  4630.     public function setNotificationData($em$dialogue$user$type$message) {
  4631.         //$em = $this->getDoctrine()->getManager();
  4632.         $notificationObj = new JoNotification();
  4633.         $notificationObj->setDialogue($dialogue);
  4634.         $notificationObj->setUser($user);
  4635.         $notificationObj->setType($type);
  4636.         $notificationObj->setMessage($message);
  4637.         $notificationObj->setCreatedAt(new \DateTime());
  4638.         $notificationObj->setUpdatedAt(new \DateTime());
  4639.         $em->persist($notificationObj);
  4640.         $em->flush();
  4641.         return $notificationObj;
  4642.     }
  4643.     
  4644.     public function setNotificationLogData($em$dialogue$user$notificationObj) {
  4645.         $notificationLogObj $em->getRepository(JoNotificationLog::class)->findOneBy(array('dialogue' => $dialogue'user' => $user'notification' => $notificationObj));
  4646.         if (!$notificationLogObj) {
  4647.             $notificationLogObj = new JoNotificationLog();
  4648.             if ($notificationLogObj) {
  4649.                 $notificationLogObj->setDialogue($dialogue);
  4650.                 $notificationLogObj->setUser($user);
  4651.                 $notificationLogObj->setNotification($notificationObj);
  4652.                 $notificationLogObj->setCreatedAt(new \DateTime());
  4653.                 $em->persist($notificationLogObj);
  4654.                 $em->flush();
  4655.                 return $notificationLogObj;
  4656.             }
  4657.         }
  4658.     }
  4659.     
  4660.     public function getDialogueCaseCardHoldsMeasure(Request $request$dccId) {
  4661.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  4662.         $em $this->getDoctrine()->getManager();
  4663.         $session $request->getSession();
  4664.         $selectedPatient $session->get("selectedPatient"false);
  4665.         $selectedDialogue $session->get("selectedDialogue"false);
  4666.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  4667.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  4668.         $user $this->get('security.token_storage')->getToken()->getUser();
  4669.         $dialogueCaseCardObj $em->getRepository(DialogueCaseCard::class)->find($dccId);
  4670.         $today = new \DateTime();
  4671.         $holds = [];
  4672.         if ($dialogue->getdialogueType() == '1' || $dialogue->getdialogueType() == '2') {
  4673.             $queryHoldIds $em->createQuery(
  4674.                             "SELECT h FROM App\Entity\JoCaseCardHold  h
  4675.             left join App\Entity\DialogueCaseCardMeasure dcm with dcm.id = h.measure  
  4676.             left join App\Entity\DialogueCaseCard dcc with dcm.DialogueCaseCard = dcc.id
  4677.             WHERE dcc.pCaseCardId = :predefinedCC and h.id IN (SELECT IDENTITY (hr.JoCaseCardHold) FROM App\Entity\HoldResponsiblePerson hr where hr.User = :patientUser and hr.responsibleType = 'GP' ) and (dcm.toDate >=:today or dcm.toDate IS NULL ) ")
  4678.                     ->setParameter('predefinedCC'$dialogueCaseCardObj->getPCaseCardId())
  4679.                     ->setParameter('patientUser'$patient->getUser())
  4680.                     ->setParameter("today"$today->format('Y-m-d'));
  4681.             $holdTemps $queryHoldIds->execute();
  4682.             foreach ($holdTemps as $hold) {
  4683.                 if ($hold->getMeasure()->getDialogueCaseCard()->getDialogue()->getFirstJoGroup()) {
  4684.                     $holds[] = $hold;
  4685.                 }
  4686.             }
  4687.         }
  4688.         
  4689.         return $this->render("default/getDialogueCaseCardHoldsMeasure.html.twig", array(
  4690.                     'holds' => $holds,
  4691.         ));
  4692.     }
  4693.     
  4694.     public function shareActivity(Request $request) {
  4695.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  4696.         $em $this->getDoctrine()->getManager();
  4697.         $session $request->getSession();
  4698.         $selectedPatient $session->get("selectedPatient"false);
  4699.         $selectedDialogue $session->get("selectedDialogue"false);
  4700.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  4701.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  4702.         $user $this->get('security.token_storage')->getToken()->getUser();
  4703.         
  4704.         $shareListIds $request->get('shareListIds');
  4705.         $skalering_content $request->get('skaleringContent');
  4706.         
  4707.         $activityListQuery $em->createQuery(
  4708.             "SELECT dad FROM App\Entity\DialogueAttachmentDetails  dad
  4709.             WHERE  dad.id IN (:shareListIds) order by dad.attachmentDate DESC")
  4710.                     ->setParameter('shareListIds'explode(','$shareListIds));
  4711.         
  4712.         $activityList $activityListQuery->execute();
  4713.         
  4714.         $listId explode(','$shareListIds);
  4715.         $fileCount= array();
  4716.         foreach ($listId as $id){
  4717.             $query $em->createQuery(
  4718.             "SELECT IDENTITY(da.dialogueAttachmentDetailId) as attachId, count(da) as filesCount from App\Entity\DialogueAttachments da WHERE da.dialogueAttachmentDetailId = :shareListIds")
  4719.             ->setParameter('shareListIds'$id);
  4720.             
  4721.             $fileResult $query->execute();
  4722.             
  4723.             foreach($fileResult as $list){
  4724.                 $fileCount[$list['attachId']]['id'] = $list['filesCount'];
  4725.                 $fileCount[$list['attachId']]['size'] = $this->getFilesSize($user,$em,$list['attachId'],'unit');
  4726.             }
  4727.         }
  4728.         $shareUsers = array();
  4729.         //if($patient->getChildAge() < 18){
  4730.             $patientFamilyObj $em->getRepository(Family::class)->findBy(array('patient' => $patient));
  4731.             foreach ($patientFamilyObj as $family){
  4732.                 if($family->getIsDeceased()!=1){
  4733.                     if($family->getCustodySince() != ''){
  4734.                         $shareUsers[] = $family;
  4735.                     }
  4736.                     if ($family->getRelation() == "9" && $family->getRelative()->getCprNo() != null && $family->getRelative()->getDeletedBy() == null) {
  4737.                         $shareUsers[] = $family;
  4738.                     }
  4739.                 }
  4740.             }
  4741.         //}
  4742.         
  4743.         $shareUsersExternal = array();
  4744.         $JoActivitySharing $em->getRepository(JoActivitySharing::class)->findOneBy(array('dialogue' => $dialogue));
  4745.         if($JoActivitySharing){
  4746.         $participants $JoActivitySharing->getJoActivitySharingParticipants();
  4747.         foreach ($participants as $participant){
  4748.             if($participant->getUserType() != && $participant->getUserType() != null){
  4749.                 if(count($participant->getJoConsentApproveStatuses())){
  4750.                     if($participant->getReversedArrayStatuses()[0]->getApprovedStatus() == 1){
  4751.                         $shareUsersExternal[] = $participant;
  4752.                     }
  4753.                 }
  4754.             }
  4755.         }
  4756.         }
  4757.         
  4758.         //$patientInfoObjTemp = $em->getRepository(PatientInformation::class)->findBy(array('patient' => $patient));
  4759.         //$patientInfoObj = $patientInfoObjTemp ? $patientInfoObjTemp[0] : array();
  4760.         $isTestServer $this->container->getParameter('isTestServer');
  4761.         return $this->render("dialogueAttachment/_shareActivity.html.twig", array(
  4762.                     'activityList' => $activityList,
  4763.                     'shareListIds' => $shareListIds,
  4764.                     'skalering_content' => $skalering_content,
  4765.                     'patient' => $patient,
  4766.                     'shareUsers' => $shareUsers,
  4767.                     'shareUsersExternal' => $shareUsersExternal,
  4768.                     'isTestServer' => $isTestServer,
  4769.                     'fileCount' => $fileCount
  4770.                     //'patientInfoObj' => $patientInfoObj,
  4771.                     
  4772.         ));
  4773.         
  4774.     }
  4775.     
  4776.     public function saveShareActivity(Request $request) {
  4777.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  4778.         $em $this->getDoctrine()->getManager();
  4779.         $session $request->getSession();
  4780.         $selectedPatient $session->get("selectedPatient"false);
  4781.         $selectedDialogue $session->get("selectedDialogue"false);
  4782.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  4783.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  4784.         $user $this->get('security.token_storage')->getToken()->getUser();
  4785.         
  4786.         $sharetype $request->get('sharetype');
  4787.         $shareListIds $request->get('shareListIds');
  4788.         $shareListIdArr explode(','$shareListIds);
  4789.         $shareListIdArr array_unique($shareListIdArr);
  4790.         $participantUserIds $request->get('participant_user_id');
  4791.         $participantRelations $request->get('participant_relation');
  4792.         $participantCategories $request->get('participant_category');
  4793.         $participantMessages $request->get('participant_message');
  4794.         $external_recipient_texts $request->get('external_recipient_text');
  4795.         $participantEmails $request->get('participant_email');
  4796.         $cprNoList = ['0301782721','30598539'];
  4797.         $isTestServer $this->container->getParameter('isTestServer');
  4798.         $shareTemplateSelectType $request->get('share_template_select_type');
  4799.         $participantRapportPdfs $request->get('participant_rapport_pdf');
  4800.         $participantFolgebrevPdfs $request->get('participant_folgebrev_pdf');
  4801.         if($sharetype == 'pdf'){
  4802.             $sharingType 0;
  4803.         }elseif($sharetype == 'via_josa'){
  4804.             $sharingType 1;
  4805.         }
  4806.         $sendEbookEmail=1;
  4807.         //var_dump($participantMessage); var_dump($participantRelation); var_dump($participantUserId);die;
  4808.         //var_dump($shareListIdArr);die;
  4809.         
  4810.         if($participantUserIds !="" && count($participantUserIds) > 0) {
  4811.             //add in JoActivitySharing
  4812.             if($sharingType == 1){
  4813.                 $JoActivitySharing $em->getRepository(JoActivitySharing::class)->findOneBy(array('dialogue' => $dialogue));
  4814.                 if(!$JoActivitySharing){
  4815.                     $JoActivitySharing = new JoActivitySharing();
  4816.                     $JoActivitySharing->setDialogue($dialogue);
  4817.                     $JoActivitySharing->setSharingType($sharingType);
  4818.                     $JoActivitySharing->setCreatedAt(new \DateTime());
  4819.                     $JoActivitySharing->setUpdatedAt(new \DateTime());
  4820.                 }
  4821.                 $JoActivitySharing->setCreatedBy($user);
  4822.                 $em->persist($JoActivitySharing);
  4823.                 $em->flush();
  4824.             
  4825.                 $index 0;
  4826.                 
  4827.                 //add new notification for citizen
  4828.                 $type 3;
  4829.                 $message 5;
  4830.                 $notificationObj $this->setNotificationData($em$dialogue$user$type$message);
  4831.             
  4832.                 $newParticipantCount 0;
  4833.                 foreach ($participantUserIds as $participantUserId){
  4834.                     $participantUser $em->getRepository(User::class)->find($participantUserId);
  4835.                     $userEmail $participantUser->getEmail();
  4836.                     $isNewParticipant false;
  4837.                 
  4838.                     $JoActivitySharingParticipant $em->getRepository(JoActivitySharingParticipant::class)->findOneBy(array('user' => $participantUserId'joActivitySharing' => $JoActivitySharing));
  4839.                     if(!$JoActivitySharingParticipant){
  4840.                         $JoActivitySharingParticipant = new JoActivitySharingParticipant();
  4841.                         $JoActivitySharingParticipant->setJoActivitySharing($JoActivitySharing);
  4842.                         $JoActivitySharingParticipant->setUser($participantUser);
  4843.                         //$JoActivitySharingParticipant->setActivity($activity);
  4844.                         $JoActivitySharingParticipant->setRelationText($participantRelations[$index]);
  4845.                         $JoActivitySharingParticipant->setSupplementsText($participantMessages[$index]);
  4846.                         $JoActivitySharingParticipant->setCreatedAt(new \DateTime());
  4847.                         $JoActivitySharingParticipant->setUpdatedAt(new \DateTime());
  4848.                         if($participantCategories){
  4849.                             $JoActivitySharingParticipant->setUserType(9);
  4850.                         }else{
  4851.                             $JoActivitySharingParticipant->setUserType(8);
  4852.                         }
  4853.                         $JoActivitySharingParticipant->setCreatedBy($user);
  4854.                     
  4855.                         $newParticipantCount++;
  4856.                         $isNewParticipant true;
  4857.                     }
  4858.                     //$JoActivitySharingParticipant->setSharingType($sharingType);
  4859.                     $em->persist($JoActivitySharingParticipant);
  4860.                     $em->flush();
  4861.                     
  4862.                     foreach ($shareListIdArr as $shareListId){
  4863.                         //add in JOactivitysharingParticipant
  4864.                         $activity $em->getRepository(DialogueAttachmentDetails::class)->find($shareListId);
  4865.                     
  4866.                         $JoParticipantSharingActivity $em->getRepository(JoParticipantSharingActivity::class)->findOneBy(array('JoActivitySharingParticipant' => $JoActivitySharingParticipant'Activity' => $activity));
  4867.                     
  4868.                         if(!$JoParticipantSharingActivity){
  4869.                             $JoParticipantSharingActivity = new JoParticipantSharingActivity();
  4870.                             $JoParticipantSharingActivity->setJoActivitySharingParticipant($JoActivitySharingParticipant);
  4871.                             $JoParticipantSharingActivity->setActivity($activity);
  4872.                         }
  4873.                         $JoParticipantSharingActivity->setSharingType($sharingType);
  4874.                         $em->persist($JoParticipantSharingActivity);
  4875.                         $em->flush();
  4876.                     }
  4877.                 
  4878.                     if($isNewParticipant){
  4879.                         $JoParticipantNotification1 = new JoParticipantNotification();
  4880.                         $JoParticipantNotification1->setJoActivitySharingParticipant($JoActivitySharingParticipant);
  4881.                         $JoParticipantNotification1->setJoNotification($notificationObj);
  4882.                         $JoParticipantNotification1->setCreatedAt(new \DateTime());
  4883.                         $em->persist($JoParticipantNotification1);
  4884.                         $em->flush();
  4885.                     }
  4886.                     if((($participantUser->hasRole('ROLE_EXTERN') || $user->getCategory()->getId() == 2) && $isTestServer == && $userEmail == 'lsh@alldialogue.com') || (($participantUser->hasRole('ROLE_EXTERN') || $user->getCategory()->getId() == 2) && $isTestServer == 0)){
  4887.                         $participantMessage $participantMessages[$index];
  4888.                         $container $this->container;
  4889.                         $mailSubject $dialogue->getSharedInvitationTitle()." - Delte dokumenter";
  4890.                         $messageTextConsent $this->get('templating')->render('message/shared_josa_case_activity.html.twig', array(
  4891.                         'invitationTitle' => $dialogue->getSharedInvitationTitle(),
  4892.                         'participantMessage' => $participantMessage,
  4893.                         'userObj' => $participantUser,
  4894.                         'patient' => $patient,
  4895.                         'dialogue' => $dialogue,
  4896.                         'loginUserObj' => $user
  4897.                         ));
  4898.                         $dialogueAttachmentControllerObj = new DialogueAttachmentController();
  4899.                         $responce $dialogueAttachmentControllerObj->sendEmailMessage($em,$user,$container,'share_josa_case_activity_email',$mailSubject,$messageTextConsent,$userEmail,'post@jo-sa.dk','','','','');
  4900.                         //var_dump($responce);
  4901.                         //die;
  4902.                         if($responce || $responce == 0){
  4903.                             $fromUserId $user->getId();
  4904.                             $toUserId $participantUser->getId();
  4905.                             $dialogueId $dialogue->getId();
  4906.                             $logFileName '';
  4907.                             $logType 'share_josa_case_activity_email';
  4908.                             $saveLogData $dialogueAttachmentControllerObj->saveSkebelonLog($em,$responce,$fromUserId,$toUserId,$logType,$dialogueId,$logFileName,'','');
  4909.                         }
  4910.                     }
  4911.                     $index++;
  4912.                 }
  4913.                 
  4914.                 if($newParticipantCount == 0){
  4915.                     $em->remove($notificationObj);
  4916.                     $em->flush();
  4917.                 }
  4918.             }else{
  4919.                 $caseActivityId='';
  4920.                 $index 0;
  4921.                 $participantMessage='';
  4922.                 $tunnelUserObj $participantUser ='';
  4923.                 foreach ($participantUserIds as $participantUserId){
  4924.                     $participantMessage $participantMessages[$index];
  4925.                     if($shareTemplateSelectType == 1){
  4926.                         $participantUserArr explode("_",$participantUserId);
  4927.                         $participantUser= isset($participantUserArr[0])? $participantUserArr[0]:$participantUserId;
  4928.                         $tunnelUserObj $em->getRepository(SepoTunnelliste::class)->findOneBy(array("rid" => $participantUser));
  4929.                     }else{
  4930.                         $participantUser $em->getRepository(User::class)->find($participantUserId);
  4931.                     }
  4932.                     $predefinedType $em->getRepository(PredefinedAttachmentType::class)->findOneBy(array('attachmentType' =>'Rapport'));
  4933.                     $predefinedAttachmentTypeObj $em->getRepository(PredefinedAttachmentType::class)->find($predefinedType->getId());
  4934.                     $joPredefinedCaseCardObj $em->getRepository(PredefinedCaseCard::class)->findOneBy(array("caseCardType" => 'josa_rapport'));
  4935.                     $heading 'Notater delt med aktør';
  4936.                     $selectedDateAttachment '';
  4937.                     $isDraft 0;
  4938.                     $dialogueAttachmentDetailObj = new DialogueAttachmentDetails();
  4939.                     $dialogueAttachmentDetailObj->setPCaseCardId($joPredefinedCaseCardObj);
  4940.                     $dialogueAttachmentDetailObj->setPatient($patient);
  4941.                     $dialogueAttachmentDetailObj->setDialogue($dialogue);
  4942.                     $dialogueAttachmentDetailObj->setDialogueCaseCard(NULL);
  4943.                     $dialogueAttachmentDetailObj->setDialogueCaseCardMeasureId(NULL);
  4944.                     $dialogueAttachmentDetailObj->setMeasureId(NULL);
  4945.                     $dialogueAttachmentDetailObj->setUser($user);
  4946.                     $dialogueAttachmentDetailObj->setPAtttachmentType($predefinedAttachmentTypeObj);
  4947.                 
  4948.                     $selectedDate = new \DateTime($selectedDateAttachment);
  4949.                     $time_now = new \DateTime();
  4950.                     $merge = new \DateTime($selectedDate->format('Y-m-d') . ' ' $time_now->format('H:i:s'));
  4951.                     $setSelectedDate $merge->format('Y-m-d H:i:s');
  4952.                     $dialogueAttachmentDetailObj->setAttachmentDate(new \DateTime($setSelectedDate)); 
  4953.                     $dialogueAttachmentDetailObj->setTypeHeading($predefinedAttachmentTypeObj->getAttachmentType());
  4954.         
  4955.                     $dialogueAttachmentDetailObj->setIsDraft($isDraft);
  4956.                     $dialogueAttachmentDetailObj->setVisibleStatus(0);
  4957.                     $dialogueAttachmentDetailObj->setActivityType(12);
  4958.                     $dialogueAttachmentDetailObj->setAttachmentHeading($heading);
  4959.                     if($shareTemplateSelectType == 1){
  4960.                         $dialogueAttachmentDetailObj->setTunnelListId($tunnelUserObj->getRid());
  4961.                         $dialogueAttachmentDetailObj->setLetterRecevierName($tunnelUserObj->getName());
  4962.                         $relations $participantEmails[$index];
  4963.                         $dialogueAttachmentDetailObj->setLetterRecevierUnit($relations);
  4964.                     }else if($shareTemplateSelectType == || $shareTemplateSelectType == 3){
  4965.                         $dialogueAttachmentDetailObj->setLetterRecevier($participantUser);
  4966.                         $relations $participantRelations[$index].", ".$participantEmails[$index];
  4967.                         $dialogueAttachmentDetailObj->setLetterRecevierUnit($relations);
  4968.                     }else{
  4969.                         $dialogueAttachmentDetailObj->setLetterRecevier($participantUser);
  4970.                         $patientFamilyObj $em->getRepository(Family::class)->findOneBy(array('relative' => $participantUser));
  4971.                         $dialogueAttachmentDetailObj->setLetterRecevierUnit('Borger');
  4972.                         if($patientFamilyObj){
  4973.                             if($patientFamilyObj->getCustodySince() != ''){
  4974.                                 if($patientFamilyObj->getRelation() == 1){
  4975.                                     $dialogueAttachmentDetailObj->setLetterRecevierUnit('Forældre 1');
  4976.                                 }
  4977.                                 if($patientFamilyObj->getRelation() == 2){
  4978.                                     $dialogueAttachmentDetailObj->setLetterRecevierUnit('Forældre 2');
  4979.                                 }
  4980.                             }
  4981.                             if($patientFamilyObj->getRelation() == 9){
  4982.                                 $dialogueAttachmentDetailObj->setLetterRecevierUnit($patientFamilyObj->getRelative()->getStamdataLabel());
  4983.                             }
  4984.                         }
  4985.                     }
  4986.                     $dialogueAttachmentDetailObj->setSahreTemplateType($shareTemplateSelectType);
  4987.                     if($shareTemplateSelectType == || $shareTemplateSelectType == || $shareTemplateSelectType == || $shareTemplateSelectType == 3){
  4988.                         $dialogueAttachmentDetailObj->setExternalParticipantText($external_recipient_texts[$index]);
  4989.                     }
  4990.                     $em->persist($dialogueAttachmentDetailObj);
  4991.                     $em->flush();
  4992.                     $session->set('activityDetailUpdated'$dialogueAttachmentDetailObj->getId());
  4993.                     $newFilePath '';
  4994.                     $webPath $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
  4995.                     $fileName pathinfo($participantRapportPdfs[$index], PATHINFO_FILENAME).".pdf";
  4996.                     $selectedFile $webPath.$participantRapportPdfs[$index];
  4997.                     //File upload code for new records
  4998.                     if (file_exists($selectedFile) && $sharetype == 'pdf') {
  4999.                         $ext pathinfo($selectedFilePATHINFO_EXTENSION);
  5000.                         $onlyFileName pathinfo($selectedFilePATHINFO_FILENAME);
  5001.                         $newFilename $onlyFileName."." $ext;
  5002.                         $newFilePath $webPath $newFilename;
  5003.                         $originalFileName 'Delte notater'"." $ext;
  5004.                         $dialogueAttachmentRapportObj = new DialogueAttachments();
  5005.                         $dialogueAttachmentRapportObj->setPatient($patient);
  5006.                         $dialogueAttachmentRapportObj->setDialogue($dialogue);
  5007.                         $dialogueAttachmentRapportObj->setUser($user);
  5008.                         $dialogueAttachmentRapportObj->setDialogueAttachmentDetailId($dialogueAttachmentDetailObj);
  5009.                         $dialogueAttachmentRapportObj->setAttachmentName($newFilename);
  5010.                         $dialogueAttachmentRapportObj->setOriginalName($originalFileName);
  5011.                         $dialogueAttachmentRapportObj->setIsDeleted(false);
  5012.                         $em->persist($dialogueAttachmentRapportObj);
  5013.                         $em->flush();
  5014.                     }
  5015.                     if (file_exists($selectedFile) && $sharetype == 'pdf') {
  5016.                         if($shareTemplateSelectType == || $shareTemplateSelectType == 3){
  5017.                             $fromUserId $user->getId();
  5018.                             if($shareTemplateSelectType == 1){
  5019.                                 $toUserId $tunnelUserObj->getRid();
  5020.                                 $toEmail $participantEmails[$index];//$tunnelUserObj->getEmail();
  5021.                                 $receiver $tunnelUserObj->getName()."_".$participantEmails[$index];//$tunnelUserObj->getEmail();
  5022.                             }else{
  5023.                                 $toUserId $participantUser->getId();
  5024.                                 $toEmail $participantUser->getEmail();
  5025.                                 $receiver $participantUser->getfullName()."_".$participantUser->getEmail();
  5026.                             }
  5027.                             $dialogueId $dialogue->getId();
  5028.                             $mailSubject "Delte dokumenter ";//$dialogue->getSharedExternalTitle();
  5029.                             $displayFileName "Rapport sagsakter";
  5030.                             $logType 'share_activity_brev_email';
  5031.                             $message='';
  5032.                             //$toEmail = $tunnelUserObj->getEmail();
  5033.                             $logFileName $newFilename;
  5034.                             //$receiver = $tunnelUserObj->getName()."_".$tunnelUserObj->getEmail();
  5035.                             if($isTestServer == && $toEmail == 'lsh@alldialogue.com' || $isTestServer == 0){
  5036.                                 $citizenAddressFilePath $webPath.$participantFolgebrevPdfs[$index];
  5037.                                 if($citizenAddressFilePath){
  5038.                                     $ext pathinfo($citizenAddressFilePathPATHINFO_EXTENSION);
  5039.                                     $onlyFileName pathinfo($citizenAddressFilePathPATHINFO_FILENAME);
  5040.                                     $newFilename $onlyFileName."." $ext;
  5041.                                     $originlName "Følgebrev.PDF";
  5042.                                     $dialogueAttachmentFolbrevObj = new DialogueAttachments();
  5043.                                     $dialogueAttachmentFolbrevObj->setPatient($patient);
  5044.                                     $dialogueAttachmentFolbrevObj->setDialogue($dialogue);
  5045.                                     $dialogueAttachmentFolbrevObj->setUser($user);
  5046.                                     $dialogueAttachmentFolbrevObj->setDialogueAttachmentDetailId($dialogueAttachmentDetailObj);
  5047.                                     $dialogueAttachmentFolbrevObj->setAttachmentName($newFilename);
  5048.                                     $dialogueAttachmentFolbrevObj->setOriginalName($originlName);
  5049.                                     $dialogueAttachmentFolbrevObj->setIsDeleted(false);
  5050.                                     $em->persist($dialogueAttachmentFolbrevObj);
  5051.                                     $em->flush();
  5052.                                 }
  5053.                                 $messageTextConsentForEmail $this->get('templating')->render('message/share_activity-external-tunnel-dialogue-citizen.html.twig', array(
  5054.                                 'participantMessage' => $participantMessage,
  5055.                                 'userObj' => $tunnelUserObj,
  5056.                                 'participantUser' => $participantUser,
  5057.                                 'patient' => $patient,
  5058.                                 'dialogueObj' => $dialogue,
  5059.                                 'loginUserObj' => $user,
  5060.                                 'shareTemplateSelectType' => $shareTemplateSelectType
  5061.                                 ));
  5062.                                 $dialogueAttachmentControllerObj = new DialogueAttachmentController();
  5063.                                 $responce =  $dialogueAttachmentControllerObj->sendEmailMessage($em,$user,$this->container,"share_activity_brev_email",$mailSubject,$messageTextConsentForEmail,$toEmail,'post@jo-sa.dk'$displayFileName,$newFilePath,$shareListIdArr,'');
  5064.                                 if($responce || $responce == 0){
  5065.                                     $dialogueAttachmentControllerObj->saveSkebelonLog($em,$responce,$fromUserId,$toUserId,$logType,$dialogueId,$logFileName,$receiver,$dialogueAttachmentDetailObj->getId());
  5066.                                 }else{
  5067.                                     $sendEbookEmail=0;
  5068.                                     //remove rapport
  5069.                                     $em->remove($dialogueAttachmentRapportObj);
  5070.                                     $em->flush();
  5071.                                     //remove Følgebrev pdf
  5072.                                     $em->remove($dialogueAttachmentFolbrevObj);
  5073.                                     $em->flush();
  5074.                                     //remove activity because email was not sent
  5075.                                     $em->remove($dialogueAttachmentDetailObj);
  5076.                                     $em->flush();
  5077.                                 }
  5078.                             }
  5079.                         }else{
  5080.                             $fromUserId $user->getId();
  5081.                             $toUserId $participantUser->getId();
  5082.                             $dialogueId $dialogue->getId();
  5083.                             $logFileName $fileName;
  5084.                             $newFilePath $selectedFile;
  5085.                             $mailSubject $dialogue->getKommuneName();
  5086.                             $logType 'case_activity_ebook';
  5087.                             $username $participantUser->getUsername();
  5088.                             $userCpr $participantUser->getCprNo();
  5089.                             $cprNo='';
  5090.                             if ($participantUser->hasRole('ROLE_TUNNEL_EXTERN')) {
  5091.                                 $username $participantUser->getCvrNo();
  5092.                                 if(strlen($username) == 8) {
  5093.                                     $cprNo is_numeric($username)? $username '0';
  5094.                                 }
  5095.                             }else{
  5096.                                 $username $participantUser->getUsername();
  5097.                                 if(strlen($username) >= && strlen($username) <= 11) {
  5098.                                     $cprNo is_numeric($username)? $username '0';
  5099.                                 }else{
  5100.                                     $cprNo is_numeric($userCpr)? $userCpr '0';
  5101.                                 }
  5102.                             }
  5103.                             $folgebrevPdf $webPath.$participantFolgebrevPdfs[$index];
  5104.                             if(($isTestServer == && in_array($cprNo$cprNoList) && $cprNo) || ($isTestServer == && $cprNo)){
  5105.                                 $container $this->container;
  5106.                                 $dialogueAttachmentControllerObj = new DialogueAttachmentController();
  5107.                                 $responce $dialogueAttachmentControllerObj->sendDoc2MailDialogueMessage($em,$user,$container,$newFilePath,$cprNo$participantUser,$mailSubject$dialogue,$dialogueAttachmentDetailObj,$dialogueAttachmentRapportObj,$shareListIdArr,'','',$participantMessage,$folgebrevPdf);
  5108.                                 if($responce || $responce == 0){
  5109.                                     $saveLogData $dialogueAttachmentControllerObj->saveSkebelonLog($em,$responce,$fromUserId,$toUserId,$logType,$dialogueId,$logFileName,'',$dialogueAttachmentDetailObj->getId());
  5110.                                 }
  5111.                             }
  5112.                         }
  5113.                     }
  5114.                     $index++;
  5115.                 }
  5116.             }
  5117.         }
  5118.         $responce 'success';
  5119.         $response = new Response(json_encode(array('result' => $responce,'sharetype' => $sharetype,'send' => $sendEbookEmail)));
  5120.         $response->headers->set('Content-Type''application/json');
  5121.         return $response;
  5122.     }
  5123.     
  5124.     public function checkUserAgent($request$session) {
  5125.         $userAgent strtolower($request->headers->get('user-agent'));
  5126.         //var_dump($userAgent); die;
  5127.         //strpos($userAgent,"ipad") === false &&  
  5128.         if ( preg_match('/(alcatel|amoi|android|ipad|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|
  5129.             iemobile|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|
  5130.             philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|
  5131.             up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i'$userAgent
  5132.                 )
  5133.         ) {
  5134.             //$request->setRequestFormat('mobile', 'text/html');
  5135.             $session->set('templateVersion''mobile');
  5136.         } else {
  5137.             //$request->setRequestFormat('html', 'text/html');
  5138.             $session->set('templateVersion''web');
  5139.         }
  5140.     }
  5141.     /**
  5142.      * @Route("/therapist/changeUserCategory/{category_id}", name="change_user_category", methods={"GET", "POST"})
  5143.      */
  5144.     public function changeUserCategory(Request $request$category_id){
  5145.         $em $this->getDoctrine()->getManager();
  5146.         $response = new Response();
  5147.         $response->headers->set('Content-Type''application/json');
  5148.         /** TODO: Make this array using a config template; then render; then getContent() on rendered output */
  5149.         $user_array = [];
  5150.         $user_array[59996] = ["host"=>["nbg2-1-dev1.jo-sa.dk"], "categories"=>[45,48], "groups"=>[45=>"FAGGRUPPE_FAMILIEHUSET"48=>"FAGGRUPPE_PPR"]];
  5151.         $user_array[1648] = ["host"=>["holbaek.jo-sa.dk"], "categories"=>[53,64], "groups"=>[53=>"FAGGRUPPE_FAMILIEHUSET"64=>"FAGGRUPPE_PPR"]];
  5152.         $user $this->get('security.token_storage')->getToken()->getUser();
  5153.         if(!isset($user_array[$user->getId()])){
  5154.             $response->setContent(json_encode(["result"=>"failed: user not allowed to change category"]));
  5155.             return $response;
  5156.         }
  5157.         if(!in_array($_SERVER['HTTP_HOST'], $user_array[$user->getId()]["host"]) ){
  5158.             $response->setContent(json_encode(["result"=>"failed: user not allowed to change category on this site"]));
  5159.             return $response;
  5160.         }
  5161.         if(!in_array($category_id$user_array[$user->getId()]["categories"]) ){
  5162.             $response->setContent(json_encode(["result"=>"failed: user not allowed to change to that category"]));
  5163.             return $response;
  5164.         }
  5165.         $category $em->getRepository(Category::class)->findOneBy(["id"=>$category_id]);
  5166.         $user->setCategory($category);
  5167.         $em->persist($user);
  5168.         $em->flush();
  5169.         $stmt $em->getConnection()->prepare("select roles from jo_user where id = ".$user->getId());
  5170.         $stmt->execute();
  5171.         $row $stmt->fetch();
  5172.         $roles unserialize($row["roles"]);
  5173.         
  5174.         $new_roles = [];
  5175.         foreach($roles as $role){
  5176.             if(!preg_match("/FAGGRUPPE_/"$role)){
  5177.                 $new_roles[] = $role;
  5178.             }
  5179.         }
  5180.         $new_roles[] = $user_array[$user->getId()]["groups"][$category_id];
  5181.         $stmt $em->getConnection()->prepare("update jo_user set roles='".serialize($new_roles)."' where id = ".$user->getId());
  5182.         $stmt->execute();
  5183.         
  5184.         $response->setContent(json_encode(["result"=>"success"]));
  5185.         return $response;
  5186.     }
  5187.     
  5188.         
  5189.     public function updateMorFarGardianToStamdata($em$newPatient$patientObject$serviceResponse$dialogueControllerObj$session) {
  5190.         $motherObject $fatherObject $guardianObject null;
  5191.         $parentCategory $em->getRepository(Category::class)->findOneBy(array("id" => 1));
  5192.         $userFullName strlen($dialogueControllerObj->getFieldValue($patientObject'CNVN_FORNVN'));
  5193.         if ($userFullName 0) {
  5194.             //This is normal code
  5195.             $patientAddressObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'PNR_FOEDDATO'$newPatient->getCpr());
  5196.             $newPatient->setLastName(trim($dialogueControllerObj->getFieldValue($patientObject'CNVN_EFTERNVN')));
  5197.             $newPatient->setFirstName($dialogueControllerObj->getFieldValue($patientObject'CNVN_FORNVN') . ' ' trim($dialogueControllerObj->getFieldValue($patientObject'CNVN_MELNVN')));
  5198.             $newPatient->setAddressLine1($dialogueControllerObj->getFieldValue($patientObject'STADR'));
  5199.             $isPatientDeceased trim($dialogueControllerObj->getFieldValue($patientObject'CNVN_STATUS'));
  5200.             if (isset($isPatientDeceased) && $isPatientDeceased == 90) {
  5201.                 $newPatient->setIsDeceased(1);
  5202.                 $deceasedDateTime trim($dialogueControllerObj->getFieldValue($patientObject'CNVN_STATUSSTARTDATO'));
  5203.                 if (isset($deceasedDateTime)) {
  5204.                     //var_dump($deceasedDateTime);
  5205.                     $deceasedDateTemp substr($deceasedDateTime08);
  5206.                     //var_dump($deceasedDateTemp);
  5207.                     $deceasedDate substr($deceasedDateTemp04) . '-' substr($deceasedDateTemp42) . '-' substr($deceasedDateTemp62);
  5208.                     //var_dump($deceasedDate);die;
  5209.                     $newPatient->setDeceaseDate(new \DateTime($deceasedDate));
  5210.                 }
  5211.             }
  5212.             if ($patientAddressObject) {
  5213.                 $newPatient->setPostNumber($dialogueControllerObj->getFieldValue($patientAddressObject'CPST_POSTNR'));
  5214.                 $newPatient->setCity($dialogueControllerObj->getFieldValue($patientAddressObject'CPSN_POSTDISTTXT'));
  5215.             } else {
  5216.                 $newPatient->setPostNumber($dialogueControllerObj->getFieldValue($patientObject'POSTNR'));
  5217.                 $newPatient->setCity($dialogueControllerObj->getFieldValue($patientObject'BYNVN'));
  5218.             }
  5219.             $session->set('cpr_naname'false);
  5220.         } else {
  5221.             //This code for child has no name i.e. untitled
  5222.             //In that case set Mor Last name + Mor Address must be set to match MOTHER info with child.
  5223.             $isMotherListed false;
  5224.             foreach (array('CFMY_RELTYPA''CFMY_RELTYPB''CFMY_RELTYPC') as $v) {
  5225.                 $rType $dialogueControllerObj->getFieldValue($patientObject$v);
  5226.                 if ($rType == '00003') {
  5227.                     $isMotherListed true;
  5228.                     break;
  5229.                 }
  5230.             }
  5231.             if ($isMotherListed) {
  5232.                 $motherObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Mor');
  5233.                 if ($motherObject) {
  5234.                     $tmpMother $this->createRelative($motherObject);
  5235.                     $newPatient->setFirstName("Unavngivet");
  5236.                     $newPatient->setLastName($tmpMother->getLastName());
  5237.                     $newPatient->setAddressLine1($tmpMother->getAddress());
  5238.                     $newPatient->setPostNumber($tmpMother->getPostNumber());
  5239.                     $newPatient->setCity($tmpMother->getCity());
  5240.                     $session->set('cpr_naname'true);
  5241.                 }
  5242.             }
  5243.         }
  5244.         if (!$newPatient->isPatientMajor()) {
  5245.             $rTypes = array();
  5246.             $rTypesText = array('00003' => 'Mor''00004' => 'Far''00005' => 'Værge');
  5247.             $whoIsHavingCustody = array();
  5248.             $relationNumber 0;
  5249.             $custodyDates = array();
  5250.             foreach (array('CFMY_RELTYPA' => 'CFMY_STARTDATOA''CFMY_RELTYPB' => 'CFMY_STARTDATOB''CFMY_RELTYPC' => 'CFMY_STARTDATOC') as $k => $v) {
  5251.                 $rType $dialogueControllerObj->getFieldValue($patientObject$k);
  5252.                 if ($rType) {
  5253.                     $rTypes[] = $rType;
  5254.                     $custodyDates[$rType] = $dialogueControllerObj->getFieldValue($patientObject$v);
  5255.                 }
  5256.             }
  5257.             foreach ($rTypes as $relation) {
  5258.                 if ($relation == '00003') {
  5259.                     $motherObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Mor');
  5260.                 } else if ($relation == '00004') {
  5261.                     $fatherObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Far');
  5262.                 }if ($relation == '00005') {
  5263.                     $guardianObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Værge');
  5264.                 }if ($relation == '00006') {
  5265.                     $guardianObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Værge');
  5266.                 }
  5267.                 if(!in_array($relation$whoIsHavingCustody)) {
  5268.                     array_push($whoIsHavingCustody,$relation);
  5269.                 }
  5270.             }
  5271.             //var_dump($guardianObject, $whoIsHavingCustody); die("ddd");
  5272.             if (isset($motherObject) && $motherObject) {
  5273.                 $mothercprNo $dialogueControllerObj->getFieldValue($motherObject'PNR_FOEDDATO');
  5274.                 $u $em->getRepository(User::class)->findOneBy(array('username' => $mothercprNo));
  5275.                 $mother $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5276.                 if (!$mother) {
  5277.                     $mother = new Family();
  5278.                     $u $this->createRelative($motherObject);
  5279.                     if (!$u->hasRole('ROLE_PARENT')) {
  5280.                         $u->addRole('ROLE_PARENT');
  5281.                         $u->setCategory($parentCategory);
  5282.                         $u->setEnabled(true);
  5283.                     }
  5284.                 } else {
  5285.                     $u $this->createRelative($motherObject);
  5286.                     $mother->setRelation(Family::REL_MOTHER);
  5287.                 }
  5288.                 if (trim($u->getStamdataLabel()) == "-") {
  5289.                     $u->setStamdataLabel(NULL);
  5290.                 }
  5291.                 $mother->setHasCustody(false);
  5292.                 $mother->setCustodySince(NULL);
  5293.                 $mother->setRelative($u);
  5294.                 if (isset($custodyDates['00003'])) {
  5295.                     $mother->setHasCustody(true);
  5296.                     $mother->setCustodySince(new \DateTime($custodyDates['00003']));
  5297.                     $relationNumber 1;
  5298.                     $stamdataLabel = ((($mothercprNo 10) % 2) == 0)? "Forælder $relationNumber (KVINDE)" "Forælder $relationNumber (MAND)";
  5299.                     if($u){
  5300.                         $u->setStamdataLabel($stamdataLabel);
  5301.                         $u->setAddress($this->getFieldValue($motherObject'STADR'));
  5302.                         $u->setPostNumber($this->getFieldValue($motherObject'CPST_POSTNR'));
  5303.                         $u->setCity($this->getFieldValue($motherObject'CPSN_POSTDISTTXT'));
  5304.                     }
  5305.                 }
  5306.                 $newPatient->setMother($mother);
  5307.             } else {
  5308.                 $motherObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Mor');
  5309.                 if($motherObject) {
  5310.                     $mothercprNo $dialogueControllerObj->getFieldValue($motherObject'PNR_FOEDDATO');
  5311.                     $u $em->getRepository(User::class)->findOneBy(array('username' => $mothercprNo));
  5312.                     $mother $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5313.                     if($motherObject)  {
  5314.                         $relationNumber 1;
  5315.                     }
  5316.                     $stamdataLabel = ((($mothercprNo 10) % 2) == 0)? "Forælder $relationNumber (KVINDE)" "Forælder $relationNumber (MAND)";
  5317.                     if($u){
  5318.                         $u->setStamdataLabel($stamdataLabel);
  5319.                         $u->setAddress($this->getFieldValue($motherObject'STADR'));
  5320.                         $u->setPostNumber($this->getFieldValue($motherObject'CPST_POSTNR'));
  5321.                         $u->setCity($this->getFieldValue($motherObject'CPSN_POSTDISTTXT'));
  5322.                     }
  5323.                     if((!(isset($custodyDates['00003']))) && $mother){
  5324.                         $mother->setHasCustody(false);
  5325.                         $mother->setCustodySince(NULL);
  5326.                     }
  5327.                 }
  5328.             }
  5329.             if (isset($fatherObject) && $fatherObject) {
  5330.                 $fathercprNo $dialogueControllerObj->getFieldValue($fatherObject'PNR_FOEDDATO');
  5331.                 $u $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
  5332.                 $father $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5333.                 if (!$father) {
  5334.                     $father = new Family();
  5335.                     $u $this->createRelative($fatherObject);
  5336.                     if (!$u->hasRole('ROLE_PARENT')) {
  5337.                         $u->addRole('ROLE_PARENT');
  5338.                         $u->setCategory($parentCategory);
  5339.                         $u->setEnabled(true);
  5340.                     }
  5341.                 } else {
  5342.                     $u $this->createRelative($fatherObject);
  5343.                     $father->setRelation(Family::REL_FATHER);
  5344.                 }
  5345.                 if (trim($u->getStamdataLabel()) == "-") {
  5346.                     $u->setStamdataLabel(NULL);
  5347.                 }
  5348.                 $father->setHasCustody(false);
  5349.                 $father->setCustodySince(NULL);
  5350.                 $father->setRelative($u);
  5351.                 if (isset($custodyDates['00004'])) {
  5352.                     $father->setHasCustody(true);
  5353.                     $father->setCustodySince(new \DateTime($custodyDates['00004']));
  5354.                     if (isset($custodyDates['00003'])){
  5355.                         $relationNumber 2;
  5356.                     } else {
  5357.                         $relationNumber 1;
  5358.                     }
  5359.                     $stamdataLabel = ((($fathercprNo 10) % 2) == 0)? "Forælder $relationNumber (KVINDE)" "Forælder $relationNumber (MAND)";
  5360.                     if($u){
  5361.                         $u->setStamdataLabel($stamdataLabel);
  5362.                         $u->setAddress($this->getFieldValue($fatherObject'STADR'));
  5363.                         $u->setPostNumber($this->getFieldValue($fatherObject'CPST_POSTNR'));
  5364.                         $u->setCity($this->getFieldValue($fatherObject'CPSN_POSTDISTTXT'));
  5365.                     }
  5366.                 }
  5367.                 $newPatient->setFather($father);
  5368.             } else {
  5369.                 $motherObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Mor');
  5370.                 $fatherObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Far');
  5371.                 if($fatherObject) {
  5372.                     $fathercprNo $dialogueControllerObj->getFieldValue($fatherObject'PNR_FOEDDATO');
  5373.                     $u $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
  5374.                     $father $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5375.                     if($motherObject)  {
  5376.                         $relationNumber 2;
  5377.                     } else {
  5378.                         $relationNumber 1;
  5379.                     }
  5380.                     $stamdataLabel = ((($fathercprNo 10) % 2) == 0)? "Forælder $relationNumber (KVINDE)" "Forælder $relationNumber (MAND)";
  5381.                     if($u){
  5382.                         $u->setStamdataLabel($stamdataLabel);
  5383.                         $u->setAddress($this->getFieldValue($fatherObject'STADR'));
  5384.                         $u->setPostNumber($this->getFieldValue($fatherObject'CPST_POSTNR'));
  5385.                         $u->setCity($this->getFieldValue($fatherObject'CPSN_POSTDISTTXT'));
  5386.                     }
  5387.                     if((!(isset($custodyDates['00004']))) && $father){
  5388.                         $father->setHasCustody(false);
  5389.                         $father->setCustodySince(NULL);
  5390.                     }
  5391.                 }
  5392.             }
  5393.             if (isset($guardianObject) && $guardianObject) {
  5394.                 $guardiancprNo $dialogueControllerObj->getFieldValue($guardianObject'PNR_FOEDDATO');
  5395.                 $u $em->getRepository(User::class)->findOneBy(array('username' => $guardiancprNo));
  5396.                 $guardian $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5397.                 if (!$guardian) {
  5398.                     $guardian = new Family();
  5399.                     $u $this->createRelative($guardianObject);
  5400.                     if (!$u->hasRole('ROLE_PARENT')) {
  5401.                         $u->addRole('ROLE_PARENT');
  5402.                         $u->setCategory($parentCategory);
  5403.                         $u->setEnabled(true);
  5404.                     }
  5405.                 } else {
  5406.                     $u $this->createRelative($guardianObject);
  5407.                     $guardian->setRelation(Family::REL_GUARDIAN);
  5408.                 }
  5409.                 if (trim($u->getStamdataLabel()) == "-") {
  5410.                     $u->setStamdataLabel(NULL);
  5411.                 }
  5412.                 $guardian->setHasCustody(false);
  5413.                 $guardian->setCustodySince(NULL);
  5414.                 $guardian->setRelative($u);
  5415.                 if (isset($custodyDates['00005'])) {
  5416.                     $guardian->setHasCustody(true);
  5417.                     $guardian->setCustodySince(new \DateTime($custodyDates['00005']));
  5418.                 }
  5419.                 $newPatient->setGuardian($guardian);
  5420.             } else {
  5421.                 $guardianObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Værge');
  5422.                 if($guardianObject) {
  5423.                     $guardiancprNo $dialogueControllerObj->getFieldValue($guardianObject'PNR_FOEDDATO');
  5424.                     $u $em->getRepository(User::class)->findOneBy(array('username' => $guardiancprNo));
  5425.                     $guardian $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5426.                     if((!(isset($custodyDates['00005']))) && $guardian){
  5427.                         $guardian->setHasCustody(false);
  5428.                         $guardian->setCustodySince(NULL);
  5429.                     } else if((!(isset($custodyDates['00006']))) && $guardian){
  5430.                         $guardian->setHasCustody(false);
  5431.                         $guardian->setCustodySince(NULL);
  5432.                     }
  5433.                 } else {
  5434.                     //JOSA custody update.pdf
  5435.                     if (in_array('00005'$whoIsHavingCustody)) {
  5436.                         $custodyFarSinceDate trim($dialogueControllerObj->getFieldValue($patientObject'CFMY_STARTDATOA'));
  5437.                         $custodyFatherCprNo trim($dialogueControllerObj->getFieldValue($patientObject'FORAELDRE_MYN_PNRA'));
  5438.                         $fatherUserObj $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
  5439.                         if (($fathercprNo === $custodyFatherCprNo) && $father) {
  5440.                             if (isset($custodyFarSinceDate) && strlen($custodyFarSinceDate) > 0) {
  5441.                                 $father->setHasCustody(true);
  5442.                                 $father->setCustodySince(new \DateTime($custodyFarSinceDate));
  5443.                             }
  5444.                         }
  5445.                     } else if (in_array('00006'$whoIsHavingCustody)) {
  5446.                         $custodyMorSinceDate trim($dialogueControllerObj->getFieldValue($patientObject'CFMY_STARTDATOB'));
  5447.                         $custodyMotherCprNo trim($dialogueControllerObj->getFieldValue($patientObject'FORAELDRE_MYN_PNRB'));
  5448.                         $motherUserObj $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
  5449.                         if (($mothercprNo === $custodyMotherCprNo) && $mother) {
  5450.                             if (isset($custodyMorSinceDate) && strlen($custodyMorSinceDate) > 0) {
  5451.                                 $mother->setHasCustody(true);
  5452.                                 $mother->setCustodySince(new \DateTime($custodyMorSinceDate));
  5453.                             }
  5454.                         }
  5455.                     }
  5456.                 }
  5457.             }
  5458.         }
  5459.         if (is_null($motherObject) && is_null($fatherObject) && is_null($guardianObject) && (!$newPatient->isPatientMajor())) {
  5460.             /* 21-11-2017 New code for new cpr functionality * */
  5461.             $motherObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Mor');
  5462.             $fatherObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Far');
  5463.             $guardianObject $dialogueControllerObj->getMatchingObject($serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row'FAMMRK''Værge');
  5464.             $childrenCPR $dialogueControllerObj->getFieldValue($patientObject'PNR');
  5465.             $getFullDate $this->getFullDateFromCPR($childrenCPR);
  5466.             if (isset($motherObject) && $motherObject) {
  5467.                 $mothercprNo $dialogueControllerObj->getFieldValue($motherObject'PNR_FOEDDATO');
  5468.                 $u $em->getRepository(User::class)->findOneBy(array('username' => $mothercprNo));
  5469.                 $mother $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5470.                 if (!$mother) {
  5471.                     $mother = new Family();
  5472.                     $u $this->createRelative($motherObject);
  5473.                     if (!$u->hasRole('ROLE_PARENT')) {
  5474.                         $u->addRole('ROLE_PARENT');
  5475.                         $u->setCategory($parentCategory);
  5476.                         $u->setEnabled(true);
  5477.                     }
  5478.                 } else {
  5479.                     $u $this->createRelative($motherObject);
  5480.                     $mother->setRelation(Family::REL_MOTHER);
  5481.                 }
  5482.                 if (trim($u->getStamdataLabel()) == "-") {
  5483.                     $u->setStamdataLabel(NULL);
  5484.                 }
  5485.                 $mother->setHasCustody(false);
  5486.                 $mother->setCustodySince(NULL);
  5487.                 $mother->setIsParticipant(false);
  5488.                 $mother->setRelative($u);
  5489.                 if (isset($custodyDates['00003'])) {
  5490.                     $mother->setHasCustody(true);
  5491.                     $mother->setCustodySince(new \DateTime($custodyDates['00003']));
  5492.                 } else {
  5493.                     $needToUpdateCustody true;
  5494.                     //$mother->setCustodySince(new \DateTime($getFullDate));
  5495.                 }
  5496.                 $newPatient->setMother($mother);
  5497.             }
  5498.             if (isset($fatherObject) && $fatherObject) {
  5499.                 $fathercprNo $dialogueControllerObj->getFieldValue($fatherObject'PNR_FOEDDATO');
  5500.                 $u $em->getRepository(User::class)->findOneBy(array('username' => $fathercprNo));
  5501.                 $father $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5502.                 if (!$father) {
  5503.                     $father = new Family();
  5504.                     $u $this->createRelative($fatherObject);
  5505.                     if (!$u->hasRole('ROLE_PARENT')) {
  5506.                         $u->addRole('ROLE_PARENT');
  5507.                         $u->setCategory($parentCategory);
  5508.                         $u->setEnabled(true);
  5509.                     }
  5510.                 } else {
  5511.                     $u $this->createRelative($fatherObject);
  5512.                     $father->setRelation(Family::REL_FATHER);
  5513.                 }
  5514.                 if (trim($u->getStamdataLabel()) == "-") {
  5515.                     $u->setStamdataLabel(NULL);
  5516.                 }
  5517.                 $father->setHasCustody(false);
  5518.                 $father->setCustodySince(NULL);
  5519.                 $father->setIsParticipant(false);
  5520.                 $father->setRelative($u);
  5521.                 if (isset($custodyDates['00004'])) {
  5522.                     $father->setHasCustody(true);
  5523.                     $father->setCustodySince(new \DateTime($custodyDates['00004']));
  5524.                 } else {
  5525.                     $needToUpdateCustody true;
  5526.                     //$father->setCustodySince(new \DateTime($getFullDate));
  5527.                 }
  5528.                 $newPatient->setFather($father);
  5529.             }
  5530.             if (isset($guardianObject) && $guardianObject) {
  5531.                 $guardiancprNo $dialogueControllerObj->getFieldValue($guardianObject'PNR_FOEDDATO');
  5532.                 $u $em->getRepository(User::class)->findOneBy(array('username' => $guardiancprNo));
  5533.                 $guardian $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  5534.                 if (!$guardian) {
  5535.                     $guardian = new Family();
  5536.                     $u $this->createRelative($guardianObject);
  5537.                     if (!$u->hasRole('ROLE_PARENT')) {
  5538.                         $u->addRole('ROLE_PARENT');
  5539.                         $u->setCategory($parentCategory);
  5540.                         $u->setEnabled(true);
  5541.                     }
  5542.                 } else {
  5543.                     $u $this->createRelative($guardianObject);
  5544.                     $guardian->setRelation(Family::REL_GUARDIAN);
  5545.                 }
  5546.                 if (trim($u->getStamdataLabel()) == "-") {
  5547.                     $u->setStamdataLabel(NULL);
  5548.                 }
  5549.                 $guardian->setHasCustody(false);
  5550.                 $guardian->setCustodySince(NULL);
  5551.                 $guardian->setIsParticipant(false);
  5552.                 $guardian->setRelative($u);
  5553.                 if (isset($custodyDates['00005'])) {
  5554.                     $guardian->setHasCustody(true);
  5555.                     $guardian->setCustodySince(new \DateTime($custodyDates['00005']));
  5556.                 } else {
  5557.                     $needToUpdateCustody true;
  5558.                     //$guardian->setCustodySince(new \DateTime($getFullDate));
  5559.                 }
  5560.                 $newPatient->setGuardian($guardian);
  5561.             }
  5562.             //$form = $this->createForm(new PatientType(), $newPatient);
  5563.             /* 21-11-2017 New code for new cpr functionality * */
  5564.             if (is_null($guardianObject) && (isset($custodyDates['00005']) || isset($custodyDates['00006']) ) && (!$newPatient->isPatientMajor())) {
  5565.                 //die("you need to do code here");
  5566.                 $userLabelText "Værge 1";
  5567.                 $userAddress $userPostno $userCity $guardianCustodySince NULL;
  5568.                 $guardianHasCustody false;
  5569.                 
  5570.                 $guardiancprNo = ($dialogueControllerObj->getFieldValue($patientObject'FORAELDRE_MYN_PNRA'));
  5571.                 $getGuardianIsShowAddress = ($dialogueControllerObj->getFieldValue($patientObject'MYN_BESKYTA'));
  5572.                 $guardianFullName = ($dialogueControllerObj->getFieldValue($patientObject'NAVNA'));
  5573.                 $guardianIsShowAddress = ($getGuardianIsShowAddress == "00001") ? true false
  5574.                 if(isset($custodyDates['00005'])) {
  5575.                     $userLabelText "Værge 1";
  5576.                     $guardianHasCustody true;
  5577.                     $guardianCustodySince = (new \DateTime($custodyDates['00005']));
  5578.                     
  5579.                     $guardian $this->createPatientGardian($em$newPatient$parentCategory$userLabelText$guardianHasCustody$guardianCustodySince$guardiancprNo$guardianFullName$guardianIsShowAddress$userAddress$userPostno$userCity);
  5580.                     $newPatient->setGuardian($guardian);
  5581.                 }
  5582.                 
  5583.                 if(isset($custodyDates['00006']) && !isset($custodyDates['00005']) ) {
  5584.                     $userLabelText "Værge 1";
  5585.                     $guardianHasCustody true;
  5586.                     $guardianCustodySince = (new \DateTime($custodyDates['00006']));
  5587.                     
  5588.                     $guardian $this->createPatientGardian($em$newPatient$parentCategory$userLabelText$guardianHasCustody$guardianCustodySince$guardiancprNo$guardianFullName$guardianIsShowAddress$userAddress$userPostno$userCity);
  5589.                     $newPatient->setGuardian($guardian);
  5590.                 }
  5591.                 
  5592.                 if(isset($custodyDates['00006']) && isset($custodyDates['00005']) ) {
  5593.                     $userLabelText "Værge 2";
  5594.                     $guardianHasCustody true;
  5595.                     $guardianCustodySince = (new \DateTime($custodyDates['00006']));
  5596.                     $guardiancprNo = ($dialogueControllerObj->getFieldValue($patientObject'FORAELDRE_MYN_PNRB'));
  5597.                     $guardianFullName = ($dialogueControllerObj->getFieldValue($patientObject'NAVNB'));
  5598.                     
  5599.                     $guardian $this->createPatientGardian($em$newPatient$parentCategory$userLabelText$guardianHasCustody$guardianCustodySince$guardiancprNo$guardianFullName$guardianIsShowAddress$userAddress$userPostno$userCity);
  5600.                     $newPatient->setGuardian($guardian);
  5601.                 }
  5602.                 
  5603.                 //createGardianRelative($usercpr, $userFirstname, $userLastname, $userAddress=NULL, $userPostno=NULL, $userCity=NULL);
  5604.             }
  5605.             //die("Final");
  5606.             //$errorMsg = "Ingen oplysninger om forældremyndighed for dette CPR-nummer. Dialog kan ikke oprettes. Kontakt evt. Statsforvaltningen.";
  5607.             //$cprLookupform->get('cpr')->addError(new FormError($errorMsg));
  5608.         }
  5609.     }
  5610.     public function createRelative($relativeObject) {
  5611.         $serviceResponse $this->doSoapRequest(208$this->getFieldValue($relativeObject'PNR_FOEDDATO'));
  5612.         $parentObject $serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row[0];
  5613.         //Check this user is already exist or not
  5614.         $em $this->getDoctrine()->getManager();
  5615.         $cprNo $this->getFieldValue($relativeObject'PNR_FOEDDATO');
  5616.         $user $em->getRepository(User::class)->findBy(array('username' => $cprNo));
  5617.         if($user) {
  5618.             $user $user $user[0] : NULL;
  5619.         } else {
  5620.             $user = new Relative();
  5621.         }
  5622.         $user->setLastName(trim($this->getFieldValue($parentObject'CNVN_EFTERNVN')));
  5623.         $user->setFirstName($this->getFieldValue($parentObject'CNVN_FORNVN'). ' '.trim($this->getFieldValue($parentObject'CNVN_MELNVN')));
  5624.         $user->setUsername($this->getFieldValue($relativeObject'PNR_FOEDDATO'));
  5625.         $user->setAddress($this->getFieldValue($relativeObject'STADR'));
  5626.         //$user->setAddressLine2('');
  5627.         $user->setPostNumber($this->getFieldValue($relativeObject'CPST_POSTNR'));
  5628.         $user->setCity($this->getFieldValue($relativeObject'CPSN_POSTDISTTXT'));
  5629.         return $user;
  5630.     }
  5631.     
  5632.     public function getFieldValue($x$id) {
  5633.         if(!is_null($x)){
  5634.             foreach ($x as $e) {
  5635.                 if ($e['r'] == $id) {
  5636.                     return (string) $e['v'];
  5637.                 }
  5638.             }
  5639.         }
  5640.         return null;
  5641.     }
  5642.     
  5643.     /* 21-11-2017 New code for new cpr functionality **/
  5644.     private function getFullDateFromCPR($date) {
  5645.         $datebegin substr($date06);
  5646.         $dateOnly substr($date02);
  5647.         $monthOnly substr($date22);
  5648.         
  5649.         $dateend substr($datebegin42);
  5650.         $yn date("y");
  5651.         if ($dateend $yn && $dateend 100) {
  5652.             $year2 19;
  5653.         } else if ($dateend <= $yn) {
  5654.             $year2 20;
  5655.         }
  5656.         $date $dateOnly "-" $monthOnly "-" $year2 $dateend;
  5657.         return $date;
  5658.     }
  5659.     
  5660.     public function generateShareActivityPdf(Request $request) {
  5661.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  5662.         $em $this->getDoctrine()->getManager();
  5663.         $session $request->getSession();
  5664.         $selectedPatient $session->get("selectedPatient"false);
  5665.         $selectedDialogue $session->get("selectedDialogue"false);
  5666.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  5667.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  5668.         $user $this->get('security.token_storage')->getToken()->getUser();
  5669.         $shareListIds $request->get('shareListIds');
  5670.         $skeleringFormContentHtmlData$request->get('skeleringFormContentHtmlData');
  5671.     
  5672.         $exploded explode(','$shareListIds);
  5673.         $exploded array_unique($exploded);
  5674.         $participantUserIds $request->get('participant_user_id');
  5675.         $generatedPDFFile $this->processShareActivityPdfWithoutUser($em,$this->container,$dialogue,$patient,$user,$exploded,'view_pdf',$skeleringFormContentHtmlData);
  5676.         /*$caseActivityId='';
  5677.         foreach ($exploded as $shareListId) {
  5678.             $caseActivityId .= "_".$shareListId;
  5679.         }*/
  5680.         $fileName "CaseActivityTemplate.pdf";
  5681.         return $this->file($generatedPDFFile$fileNameResponseHeaderBag::DISPOSITION_INLINE);
  5682.     }
  5683.     public function processShareActivityPdf($em,$container,$dialogue,$patient,$user,$participantUserIds,$exploded,$type,$skeleringFormContentHtmlData){
  5684.         $imageData $this->container->getParameter('image_data');
  5685.         if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')   
  5686.         $url "https://";   
  5687.         else  
  5688.             $url "http://";  
  5689.             
  5690.         $url.= $_SERVER['HTTP_HOST'];
  5691.         //$url = $this->get('kernel')->getProjectDir().'/public';
  5692.         $activityListQuery $em->createQuery(
  5693.             "SELECT dad FROM App\Entity\DialogueAttachmentDetails  dad
  5694.             WHERE  dad.id IN (:shareListIds) order by dad.attachmentDate DESC")
  5695.                     ->setParameter('shareListIds'$exploded);
  5696.         
  5697.         $activityList $activityListQuery->execute();
  5698.         $activityCount count($activityList);
  5699.         foreach ($participantUserIds as $participantUserId){
  5700.             $participantUserObj $em->getRepository(User::class)->find($participantUserId);
  5701.             $cnt=0;$messageText=$caseActivityId='';
  5702.             $shareActivityArray = array();
  5703.             foreach ($activityList as $activityObj) {
  5704.                 $attachmentDate $activityObj->getAttachmentDate()->format('d-m-Y');
  5705.                 //$activityObj = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array('id' => $shareListId));
  5706.                 $tunnelshareActivity=array();
  5707.                 $tunnelRid$activityObj->getTunnelListId();
  5708.                 if($tunnelRid){
  5709.                     $tunnelDetailsObj $em->getRepository(SepoTunnelliste::class)->findOneBy(array('rid' => $tunnelRid));
  5710.                     if($tunnelDetailsObj){
  5711.                         $tunnelshareActivity[$tunnelRid]=  array('name' =>  $tunnelDetailsObj->getName());
  5712.                     }
  5713.                 }
  5714.                 $dialogueAttachments $em->getRepository(DialogueAttachments::class)->findBy(array('dialogue' => $dialogue'patient' => $patient));
  5715.                 $dialogueAttachmentFileName = array();
  5716.                 foreach ($dialogueAttachments as $dialogueAttachment) {
  5717.                     $id $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
  5718.                     $dialogueAttachmentFileName[$id]['files'][] = $dialogueAttachment;
  5719.                     $fileIsImported false;
  5720.                     $isSharedJournal false;
  5721.                     if(isset($dialogueAttachment) && !empty($dialogueAttachment)) {
  5722.                         $fileIsImported $dialogueAttachment->getIsImported();
  5723.                         $isSharedJournal $dialogueAttachment->getIsSharedJournal();
  5724.                     }
  5725.                     if($isSharedJournal) {
  5726.                         $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/attachmentsJournal/';
  5727.                     } else if($fileIsImported) {
  5728.                         /*if($user->hasRole('ROLE_CSV')){
  5729.                             $webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/kingo_src/';
  5730.                         }else{*/
  5731.                             $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/kingo/';
  5732.                         //}
  5733.                     } else {
  5734.                         $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/attachments/';
  5735.                     }
  5736.                     if(file_exists($webPath.$dialogueAttachment->getAttachmentName())){
  5737.                         $filesize filesize($webPath.$dialogueAttachment->getAttachmentName());
  5738.                         $dialogueAttachmentFileName[$id]['size'][] = $this->formatSizeUnits($filesize);
  5739.                     }else{
  5740.                         $dialogueAttachmentFileName[$id]['size'][] = '';
  5741.                     }
  5742.                 }
  5743.                 $noteDetails=[];
  5744.                 if($activityObj->getPAtttachmentType()->getId() == 5){
  5745.                     $noteDetails $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('parentId' => $activityObj->getId()),array('id' => 'DESC'));
  5746.                 }
  5747.                  //featchScaleGraph detils
  5748.                  $res=$this->featchAllScalingGraphDetails($em,$activityObj);
  5749.                  if($res){
  5750.                      $scaleGraphArray[$activityObj->getId()] = isset($res['scalingIndividualGraphArray'][$activityObj->getId()])?$res['scalingIndividualGraphArray'][$activityObj->getId()]:[];
  5751.                  }
  5752.                 $array json_decode($imageDatatrue);
  5753.                 $skelelonText =  $container->get('templating')->render('message/case_activity-success.html.twig', array('dialogueObj'=>$dialogue,'userObj'=> $user'participantUserObj'=>$participantUserObj,'activityObj' => $activityObj,'dialogueAttachmentFileName' => $dialogueAttachmentFileName,'cnt'=>$cnt,'schemeAndHost'=>$url,'imageData'=>$array,'patient'=>$patient,'tunnelshareActivity'=>$tunnelshareActivity,'activityList'=>$activityList,'skeleringFormContentHtmlData'=>$skeleringFormContentHtmlData,'scaleGraphArray'=>$scaleGraphArray,'noteDetails'=> $noteDetails'attachmentDate'=>$attachmentDate'activityCount' => $activityCount));
  5754.                 if($activityObj->getPAtttachmentType()->getAttachmentType() == 'Skabelon'){
  5755.                     $skelelonText str_replace('class="h70"','class="h70 hide"',$skelelonText);
  5756.                     $skelelonText str_replace('section_area','section_area'.$cnt,$skelelonText);
  5757.                     $skelelonText str_replace('header_area','header_area'.$cnt." hide",$skelelonText);
  5758.                     $skelelonText str_replace('footer_area','footer_area'.$cnt." hide",$skelelonText);
  5759.                     $skelelonText str_replace('sarea_1','sarea_1'.$cnt,$skelelonText);
  5760.                     $skelelonText str_replace('sarea_2','sarea_2'.$cnt,$skelelonText);
  5761.                     $skelelonText str_replace('sarea_3','sarea_3'.$cnt,$skelelonText);
  5762.                     $skelelonText str_replace('sarea_4','sarea_4'.$cnt,$skelelonText);
  5763.                     $skelelonText str_replace('sarea_5','sarea_5'.$cnt,$skelelonText);
  5764.                     $skelelonText str_replace('sarea_6','sarea_6'.$cnt,$skelelonText);
  5765.                     $skelelonText str_replace('sarea_7','sarea_7'.$cnt,$skelelonText);
  5766.                     $skelelonText str_replace('sarea_8','sarea_8'.$cnt,$skelelonText);
  5767.                     $skelelonText str_replace('sarea_9','sarea_9'.$cnt,$skelelonText);
  5768.                     $skelelonText str_replace('sarea_10','sarea_10'.$cnt,$skelelonText);
  5769.                     $skelelonText str_replace('sopt_1','sopt_1'.$cnt,$skelelonText);
  5770.                     $skelelonText str_replace('sopt_2','sopt_2'.$cnt,$skelelonText);
  5771.                     $skelelonText str_replace('nbr_sections','nbr_sections'.$cnt,$skelelonText);
  5772.                     $skelelonText str_replace('<span class="editable_div" contenteditable="true" data-text="Skriv her…"></span>','<span class="editable_div" contenteditable="true" data-text="Skriv her…">-</span>',$skelelonText);
  5773.                     $skelelonText str_replace('<span class="editable_div limit_length w259" max-length="35" contenteditable="true" data-text="Skriv her…"></span>','<span class="editable_div limit_length w259" max-length="35" contenteditable="true" data-text="Skriv her…">-</span>',$skelelonText);
  5774.                     $skelelonText str_replace('<span class="editable_div limit_length w122" contenteditable="true" max-length="14" data-text="Skriv her…"></span>','<span class="editable_div limit_length w122" contenteditable="true" max-length="14" data-text="Skriv her…">-</span>',$skelelonText);                   
  5775.                 }
  5776.                 $dialogueAttachmentControllerObj = new DialogueAttachmentController();
  5777.                 $skelelonText $dialogueAttachmentControllerObj->replaceMessageTextForPdf(true,$container,$skelelonText,'',$attachmentDate);
  5778.                 $messageText .= $skelelonText;
  5779.                 $caseActivityId .= "_".$participantUserId;
  5780.                 $cnt++;
  5781.             }
  5782.         }
  5783.         $messageText str_replace('Skriv note her...','',$messageText);
  5784.         $messageTextstr_replace('<img class="content-img" src="../template/res/cfk-header-543x703.jpg" alt="">','',$messageText);
  5785.         $html1 $messageText;
  5786.         //echo $html1;
  5787.         //die;
  5788.         $webPathDoc_2_mail $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
  5789.         //if($type != 'view_pdf'){
  5790.             $caseActivityId "_".uniqid(''true);
  5791.         //}
  5792.         $htmlFileName "CaseActivityTemplate".$caseActivityId".html";
  5793.         $pdfFileName "CaseActivityTemplate".$caseActivityId".pdf";
  5794.         $generatedHtmlFile$webPathDoc_2_mail $htmlFileName;
  5795.         $generatedPDFFile$webPathDoc_2_mail $pdfFileName;
  5796.         $data file_put_contents($generatedHtmlFile$html1);
  5797.         $filePath $generatedPDFFile;
  5798.         $html $webPathDoc_2_mail."CaseActivityTemplate".$caseActivityId".html ";
  5799.         $fileName "CaseActivityTemplate".$caseActivityId".pdf ";
  5800.         $outputFilePath $webPathDoc_2_mail.$fileName;
  5801.         if (file_exists($filePath)) {
  5802.             unlink($filePath);
  5803.         }
  5804.         if (!file_exists($generatedPDFFile)) {
  5805.             $dialogueAttachmentControllerObj = new DialogueAttachmentController();
  5806.             $res $dialogueAttachmentControllerObj->createTemplatePdf($html,$fileName,$outputFilePath);
  5807.             //var_dump($res);
  5808.             //die;
  5809.             if (file_exists($generatedHtmlFile)) {
  5810.                 unlink($generatedHtmlFile);
  5811.             }
  5812.         } 
  5813.         return $generatedPDFFile;
  5814.     }
  5815.     public function processShareActivityPdfWithoutUser($em,$container,$dialogue,$patient,$user,$exploded,$type,$skeleringFormContentHtmlData){
  5816.         $imageData $this->container->getParameter('image_data');
  5817.         if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')   
  5818.         $url "https://";   
  5819.         else  
  5820.             $url "http://";  
  5821.             
  5822.         $url.= $_SERVER['HTTP_HOST'];
  5823.         //$url = $this->get('kernel')->getProjectDir().'/public';
  5824.         $activityListQuery $em->createQuery(
  5825.             "SELECT dad FROM App\Entity\DialogueAttachmentDetails  dad
  5826.             WHERE  dad.id IN (:shareListIds) order by dad.attachmentDate DESC")
  5827.                     ->setParameter('shareListIds'$exploded);
  5828.         
  5829.         $activityList $activityListQuery->execute();
  5830.         //foreach ($participantUserIds as $participantUserId){
  5831.             //$participantUserObj = $em->getRepository(User::class)->find($participantUserId);
  5832.             $cnt=0;$messageText=$caseActivityId='';
  5833.             $shareActivityArray $scaleGraphArray = array();
  5834.             $activityCount count($activityList);
  5835.             foreach ($activityList as $activityObj) {
  5836.                 $attachmentDate $activityObj->getAttachmentDate()->format('d-m-Y');
  5837.                 //$activityObj = $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array('id' => $shareListId));
  5838.                 $tunnelshareActivity=array();
  5839.                 $tunnelRid$activityObj->getTunnelListId();
  5840.                 if($tunnelRid){
  5841.                     $tunnelDetailsObj $em->getRepository(SepoTunnelliste::class)->findOneBy(array('rid' => $tunnelRid));
  5842.                     if($tunnelDetailsObj){
  5843.                         $tunnelshareActivity[$tunnelRid]=  array('name' =>  $tunnelDetailsObj->getName());
  5844.                     }
  5845.                 }
  5846.                 $dialogueAttachments $em->getRepository(DialogueAttachments::class)->findBy(array('dialogue' => $dialogue'patient' => $patient));
  5847.                 $dialogueAttachmentFileName = array();
  5848.                 foreach ($dialogueAttachments as $dialogueAttachment) {
  5849.                     $id $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
  5850.                     $dialogueAttachmentFileName[$id]['files'][] = $dialogueAttachment;
  5851.                     $fileIsImported false;
  5852.                     $isSharedJournal false;
  5853.                     if(isset($dialogueAttachment) && !empty($dialogueAttachment)) {
  5854.                         $fileIsImported $dialogueAttachment->getIsImported();
  5855.                         $isSharedJournal $dialogueAttachment->getIsSharedJournal();
  5856.                     }
  5857.                     if($isSharedJournal) {
  5858.                         $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/attachmentsJournal/';
  5859.                     } else if($fileIsImported) {
  5860.                         /*if($user->hasRole('ROLE_CSV')){
  5861.                             $webPath = $this->get('kernel')->getProjectDir() . '/public/uploads/kingo_src/';
  5862.                         }else{*/
  5863.                             $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/kingo/';
  5864.                         //}
  5865.                     } else {
  5866.                         $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/attachments/';
  5867.                     }
  5868.                     if(file_exists($webPath.$dialogueAttachment->getAttachmentName())){
  5869.                         $filesize filesize($webPath.$dialogueAttachment->getAttachmentName());
  5870.                         $dialogueAttachmentFileName[$id]['size'][] = $this->formatSizeUnits($filesize);
  5871.                     }else{
  5872.                         $dialogueAttachmentFileName[$id]['size'][] = '';
  5873.                     }
  5874.                 }
  5875.                 $noteDetails=[];
  5876.                 if($activityObj->getPAtttachmentType()->getId() == 5){
  5877.                     $noteDetails $em->getRepository(DialogueAttachmentDetails::class)->findBy(array('parentId' => $activityObj->getId()),array('id' => 'DESC'));
  5878.                 }
  5879.                 //featchScaleGraph detils
  5880.                 $res=$this->featchAllScalingGraphDetails($em,$activityObj);
  5881.                 if($res){
  5882.                     $scaleGraphArray[$activityObj->getId()] = isset($res['scalingIndividualGraphArray'][$activityObj->getId()])?$res['scalingIndividualGraphArray'][$activityObj->getId()]:[];
  5883.                 }
  5884.                 $array json_decode($imageDatatrue);
  5885.                 $skelelonText =  $container->get('templating')->render('message/case_activity-success.html.twig', array('dialogueObj'=>$dialogue,'userObj'=> $user'participantUserObj'=>'','activityObj' => $activityObj,'dialogueAttachmentFileName' => $dialogueAttachmentFileName,'cnt'=>$cnt,'schemeAndHost'=>$url,'imageData'=>$array,'patient'=>$patient,'tunnelshareActivity'=>$tunnelshareActivity,'activityList'=>$activityList,'skeleringFormContentHtmlData'=>$skeleringFormContentHtmlData,'scaleGraphArray'=>$scaleGraphArray,'noteDetails'=> $noteDetails'attachmentDate'=>$attachmentDate'activityCount' => $activityCount));
  5886.                 if($activityObj->getPAtttachmentType()->getAttachmentType() == 'Skabelon'){
  5887.                     $skelelonText str_replace('class="h70"','class="h70 hide"',$skelelonText);
  5888.                     $skelelonText str_replace('section_area','section_area'.$cnt,$skelelonText);
  5889.                     $skelelonText str_replace('header_area','header_area'.$cnt." hide",$skelelonText);
  5890.                     $skelelonText str_replace('footer_area','footer_area'.$cnt." hide",$skelelonText);
  5891.                     $skelelonText str_replace('sarea_1','sarea_1'.$cnt,$skelelonText);
  5892.                     $skelelonText str_replace('sarea_2','sarea_2'.$cnt,$skelelonText);
  5893.                     $skelelonText str_replace('sarea_3','sarea_3'.$cnt,$skelelonText);
  5894.                     $skelelonText str_replace('sarea_4','sarea_4'.$cnt,$skelelonText);
  5895.                     $skelelonText str_replace('sarea_5','sarea_5'.$cnt,$skelelonText);
  5896.                     $skelelonText str_replace('sarea_6','sarea_6'.$cnt,$skelelonText);
  5897.                     $skelelonText str_replace('sarea_7','sarea_7'.$cnt,$skelelonText);
  5898.                     $skelelonText str_replace('sarea_8','sarea_8'.$cnt,$skelelonText);
  5899.                     $skelelonText str_replace('sarea_9','sarea_9'.$cnt,$skelelonText);
  5900.                     $skelelonText str_replace('sarea_10','sarea_10'.$cnt,$skelelonText);
  5901.                     $skelelonText str_replace('sopt_1','sopt_1'.$cnt,$skelelonText);
  5902.                     $skelelonText str_replace('sopt_2','sopt_2'.$cnt,$skelelonText);
  5903.                     $skelelonText str_replace('nbr_sections','nbr_sections'.$cnt,$skelelonText);
  5904.                     $skelelonText str_replace('<span class="editable_div" contenteditable="true" data-text="Skriv her…"></span>','<span class="editable_div" contenteditable="true" data-text="Skriv her…">-</span>',$skelelonText);
  5905.                     $skelelonText str_replace('<span class="editable_div limit_length w259" max-length="35" contenteditable="true" data-text="Skriv her…"></span>','<span class="editable_div limit_length w259" max-length="35" contenteditable="true" data-text="Skriv her…">-</span>',$skelelonText);
  5906.                     $skelelonText str_replace('<span class="editable_div limit_length w122" contenteditable="true" max-length="14" data-text="Skriv her…"></span>','<span class="editable_div limit_length w122" contenteditable="true" max-length="14" data-text="Skriv her…">-</span>',$skelelonText);
  5907.                 }
  5908.                     $dialogueAttachmentControllerObj = new DialogueAttachmentController();
  5909.                     $skelelonText $dialogueAttachmentControllerObj->replaceMessageTextForPdf(true,$container,$skelelonText,'',$attachmentDate);
  5910.                 $messageText .= $skelelonText;
  5911.                 //$caseActivityId .= "_".$participantUserId;
  5912.                 $cnt++;
  5913.             }
  5914.         //}
  5915.         $messageText str_replace('Skriv note her...','',$messageText);
  5916.         $messageTextstr_replace('<img class="content-img" src="../template/res/cfk-header-543x703.jpg" alt="">','',$messageText);
  5917.         $html1 $messageText;
  5918.         //echo $html1;
  5919.         //die;
  5920.         $webPathDoc_2_mail $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
  5921.         //if($type != 'view_pdf'){
  5922.             $caseActivityId "_".uniqid(''true);
  5923.         //}
  5924.         $htmlFileName "CaseActivityTemplate".$caseActivityId".html";
  5925.         $pdfFileName "CaseActivityTemplate".$caseActivityId".pdf";
  5926.         $generatedHtmlFile$webPathDoc_2_mail $htmlFileName;
  5927.         $generatedPDFFile$webPathDoc_2_mail $pdfFileName;
  5928.         $data file_put_contents($generatedHtmlFile$html1);
  5929.         $filePath $generatedPDFFile;
  5930.         $html $webPathDoc_2_mail."CaseActivityTemplate".$caseActivityId".html ";
  5931.         $fileName "CaseActivityTemplate".$caseActivityId".pdf ";
  5932.         $outputFilePath $webPathDoc_2_mail.$fileName;
  5933.         if (file_exists($filePath)) {
  5934.             unlink($filePath);
  5935.         }
  5936.         if (!file_exists($generatedPDFFile)) {
  5937.             $dialogueAttachmentControllerObj = new DialogueAttachmentController();
  5938.             $res $dialogueAttachmentControllerObj->createTemplatePdf($html,$fileName,$outputFilePath);
  5939.             //var_dump($res);
  5940.             //die;
  5941.             if (file_exists($generatedHtmlFile)) {
  5942.                 unlink($generatedHtmlFile);
  5943.             }
  5944.         } 
  5945.         return $generatedPDFFile;
  5946.     }
  5947.     
  5948.     public function checkSessionTimeout(Request $request) {
  5949.         $responce 'success';
  5950.         $user $this->get('security.token_storage')->getToken()->getUser();
  5951.         //if (!($user)) {
  5952.         if (!is_object($user)) {
  5953.             $responce 'fail';
  5954.         }
  5955.         //var_dump($user, $responce); die;
  5956.         $response = new Response(json_encode(array('result' => $responce)));
  5957.         $response->headers->set('Content-Type''application/json');
  5958.         return $response;
  5959.     }
  5960.     public function updateStamdataISTElevData($patient$session) {
  5961.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  5962.         $em $entityManager $this->getDoctrine()->getManager();
  5963.         if ($patient) {
  5964.             $cprNumber $patient->getCpr();
  5965.             $isMultipleRecords false;
  5966.             $fetchPatientIstElevData $em->getRepository(IstElev::class)->findOneByCpr($cprNumber);
  5967.             $fetchPatientLastSchoolIstElevUdvData $em->getRepository(IstElevUdv::class)->findLastSchoolByCpr($cprNumber);
  5968.             $fetchPatientAllIstElevUdvData $em->getRepository(IstElevUdv::class)->findAllByCpr($cprNumber);
  5969.             //var_dump($fetchPatientLastSchoolIstElevUdvData);
  5970.             //die;
  5971.             //var_dump($cprNumber, $fetchPatientIstElevData);
  5972.             if ($fetchPatientIstElevData) {
  5973.                 $skolekode $fetchPatientLastSchoolIstElevUdvData $fetchPatientLastSchoolIstElevUdvData->getSkolekode() : $fetchPatientIstElevData->getSkolekode();
  5974.                 $skolenavn $fetchPatientLastSchoolIstElevUdvData $fetchPatientLastSchoolIstElevUdvData->getSkolenavn() : $fetchPatientIstElevData->getSkolenavn();
  5975.                 $skoletype $fetchPatientLastSchoolIstElevUdvData $fetchPatientLastSchoolIstElevUdvData->getSkoletype() : NULL;
  5976.                 $klassetype $fetchPatientLastSchoolIstElevUdvData $fetchPatientLastSchoolIstElevUdvData->getKlassetype() : $fetchPatientIstElevData->getKlassetype();
  5977.                 $elevklassetrin $fetchPatientLastSchoolIstElevUdvData $fetchPatientLastSchoolIstElevUdvData->getElevklassetrin() : NULL;
  5978.                 $klassebetegnelse $fetchPatientLastSchoolIstElevUdvData $fetchPatientLastSchoolIstElevUdvData->getKlassebetegnelse() : NULL;
  5979.                 $fradato $fetchPatientLastSchoolIstElevUdvData $fetchPatientLastSchoolIstElevUdvData->getFradato() : NULL;
  5980.                 $tildato $fetchPatientLastSchoolIstElevUdvData $fetchPatientLastSchoolIstElevUdvData->getTildato() : NULL;
  5981.                 $schoolStartDate $schoolEndDate NULL;
  5982.                 $patientInformationObj $em->getRepository(PatientInformation::class)->findOneBy(array("patient" => $patient));
  5983.                 if (!$patientInformationObj) {
  5984.                     $patientInformationObj = new PatientInformation();
  5985.                 }
  5986.                 if (count($fetchPatientAllIstElevUdvData) > 0) {
  5987.                     $isMultipleRecords true;
  5988.                     $patientInformationObj->setIsMultiple(true);
  5989.                 } else {
  5990.                     $patientInformationObj->setIsMultiple(false);
  5991.                 }
  5992.                 $patientInformationObj->setUser($patient->getUser());
  5993.                 $patientInformationObj->setPatient($patient);
  5994.                 if (strlen($skolenavn) > && strlen($patientInformationObj->getCitizenSchoolName()) >= 0) {
  5995.                     $patientInformationObj->setCitizenSchoolName($skolenavn);
  5996.                 }
  5997.                 if (strlen($skolekode) > && strlen($patientInformationObj->getCitizenSchoolNumber()) >= 0) {
  5998.                     $patientInformationObj->setCitizenSchoolNumber($skolekode);
  5999.                 }
  6000.                 if (strlen($skoletype) > && strlen($patientInformationObj->getCitizenSchoolType()) >= 0) {
  6001.                     $patientInformationObj->setCitizenSchoolType($skoletype);
  6002.                 }
  6003.                 if (strlen($fradato) > 0) {
  6004.                     $schoolStartDate date("d.m.Y"strtotime($fradato));
  6005.                 }
  6006.                 if (strlen($tildato) > 0) {
  6007.                     $schoolEndDate date("d.m.Y"strtotime($tildato));
  6008.                 }
  6009.                 if (strlen($schoolStartDate) > 0) {
  6010.                     $patientInformationObj->setCitizenSchoolStart($schoolStartDate);
  6011.                 }
  6012.                 if (strlen($schoolEndDate) > 0) {
  6013.                     $patientInformationObj->setCitizenSchoolEnd($schoolEndDate);
  6014.                 }
  6015.                 if (strlen($klassetype) > && strlen($patientInformationObj->getCitizenClasseType()) >= 0) {
  6016.                     $patientInformationObj->setCitizenClasseType($klassetype);
  6017.                 }
  6018.                 if (strlen($klassebetegnelse) > && strlen($patientInformationObj->getCitizenSchoolClass()) >= 0) {
  6019.                     $patientInformationObj->setCitizenSchoolClass($klassebetegnelse);
  6020.                 }
  6021.                 if (strlen($elevklassetrin) > && strlen($patientInformationObj->getCitizenSchoolLevel()) >= 0) {
  6022.                     $patientInformationObj->setCitizenSchoolLevel($elevklassetrin);
  6023.                 }
  6024.                 $entityManager->persist($patientInformationObj);
  6025.             }
  6026.             //To store school history
  6027.             if ($fetchPatientAllIstElevUdvData) {
  6028.                 
  6029.                 //$allBlankSchoolPatientInformationObj = $em->createQuery('SELECT pd FROM  App\Entity\PatientInformationDetails pd WHERE pd.patient = :patient and pd.skoleRef IS NULL')
  6030.                 $allBlankSchoolPatientInformationObj $em->createQuery('SELECT pd FROM  App\Entity\PatientInformationDetails pd WHERE pd.patient = :patient')
  6031.                             ->setParameter('patient'$patient)
  6032.                             ->execute();
  6033.                 if(count($allBlankSchoolPatientInformationObj) > 0) {
  6034.                     foreach($allBlankSchoolPatientInformationObj as $blankSchoolPatientInformationObj) {
  6035.                         $entityManager->remove($blankSchoolPatientInformationObj);
  6036.                     }
  6037.                     $entityManager->flush();
  6038.                 }
  6039.             
  6040.                 //var_dump($fetchPatientAllIstElevUdvData); die;
  6041.                 foreach ($fetchPatientAllIstElevUdvData as $fetchPatientIstElevUdvDataT) {
  6042.                     $fetchPatientIstElevUdvData $fetchPatientIstElevUdvDataT[0];
  6043.                     //var_dump($fetchPatientIstElevUdvData);
  6044.                     $schoolStartDate $schoolEndDate NULL;
  6045.                     $schoolIstElevUdvRef $fetchPatientIstElevUdvData->getid();
  6046.                     $patientInformationObj $em->getRepository(PatientInformationDetails::class)->findOneBy(array("patient" => $patient"skoleRef" => $schoolIstElevUdvRef));
  6047.                     if (!$patientInformationObj) {
  6048.                         $patientInformationObj = new PatientInformationDetails();
  6049.                     }
  6050.                     $patientInformationObj->setUser($patient->getUser());
  6051.                     $patientInformationObj->setPatient($patient);
  6052.                     $Skoletype $fetchPatientIstElevUdvData $fetchPatientIstElevUdvData->getSkoletype() : NULL;
  6053.                     $skolenavn $fetchPatientIstElevUdvData $fetchPatientIstElevUdvData->getSkolenavn() : NULL;
  6054.                     $klassebetegnelse $fetchPatientIstElevUdvData $fetchPatientIstElevUdvData->getKlassebetegnelse() : NULL;
  6055.                     $elevklassetrin $fetchPatientIstElevUdvData $fetchPatientIstElevUdvData->getElevklassetrin() : NULL;
  6056.                     $fradato $fetchPatientIstElevUdvData $fetchPatientIstElevUdvData->getFradato() : NULL;
  6057.                     $tildato $fetchPatientIstElevUdvData $fetchPatientIstElevUdvData->getTildato() : NULL;
  6058.                     if (strlen($skolenavn) > && strlen($patientInformationObj->getCitizenSchoolName()) == 0) {
  6059.                         $patientInformationObj->setCitizenSchoolName($skolenavn);
  6060.                     }
  6061.                     if (strlen($fradato) > 0) {
  6062.                         $schoolStartDate date("d.m.Y"strtotime($fradato));
  6063.                     }
  6064.                     if (strlen($tildato) > 0) {
  6065.                         $schoolEndDate date("d.m.Y"strtotime($tildato));
  6066.                     }
  6067.                     if (strlen($schoolStartDate) > 0) {
  6068.                         $patientInformationObj->setCitizenSchoolStart($schoolStartDate);
  6069.                     }
  6070.                     if (strlen($schoolEndDate) > 0) {
  6071.                         $patientInformationObj->setCitizenSchoolEnd($schoolEndDate);
  6072.                     }
  6073.                     if (strlen($klassebetegnelse) > && strlen($patientInformationObj->getCitizenSchoolClass()) == 0) {
  6074.                         $patientInformationObj->setCitizenSchoolClass($klassebetegnelse);
  6075.                     }
  6076.                     if (strlen($elevklassetrin) > && strlen($patientInformationObj->getCitizenSchoolLevel()) == 0) {
  6077.                         $patientInformationObj->setCitizenSchoolLevel($elevklassetrin);
  6078.                     }
  6079.                     $patientInformationObj->setSkoleRef($schoolIstElevUdvRef);
  6080.                     $entityManager->persist($patientInformationObj);
  6081.                 }
  6082.             }
  6083.             $entityManager->flush();
  6084.             //die("Success");
  6085.         }
  6086.     }
  6087.     
  6088.     public function josaCheckEnvironment(Request $request) {
  6089.         $responce "Success";
  6090.         $APP_DEBUG = ( isset($_SERVER['APP_DEBUG']) && $_SERVER['APP_DEBUG']) ? "True" "False";
  6091.         $isCprLookupActiveVal = ( isset($_SERVER['isCprLookupActiveVal']) && $_SERVER['isCprLookupActiveVal']) ? "True" "False";
  6092.         $showRapportUrl = ( isset($_SERVER['showRapportUrl']) && $_SERVER['showRapportUrl']) ? "True" "False";
  6093.         $isCopenhagen = ( isset($_SERVER['isCopenhagen']) && $_SERVER['isCopenhagen']) ? "True" "False";
  6094.         $isBackendEnabled = ( isset($_SERVER['isBackendEnabled']) && $_SERVER['isBackendEnabled']) ? "True" "False";
  6095.         $isTestServer = ( isset($_SERVER['isTestServer']) && $_SERVER['isTestServer']) ? "True" "False";
  6096.         $pageResultLimit = ( isset($_SERVER['pageResultLimit']) && $_SERVER['pageResultLimit']) ? $_SERVER['pageResultLimit'] : "False";
  6097.         $indexPageSearchLimit = ( isset($_SERVER['indexPageSearchLimit']) && $_SERVER['indexPageSearchLimit']) ? $_SERVER['indexPageSearchLimit'] : "False";
  6098.         $isBorgerPlanLetterEnabled = ( isset($_SERVER['isBorgerPlanLetterEnabled']) && $_SERVER['isBorgerPlanLetterEnabled']) ? "True" "False";
  6099.         $image_data = ( isset($_SERVER['image_data']) && $_SERVER['image_data']) ? $_SERVER['image_data'] : "False";
  6100.         $image_data_cubf = ( isset($_SERVER['image_data_cubf']) && $_SERVER['image_data_cubf']) ? $_SERVER['image_data_cubf'] : "False";
  6101.         $image_data_rfc = ( isset($_SERVER['image_data_rfc']) && $_SERVER['image_data_rfc']) ? $_SERVER['image_data_rfc'] : "False";
  6102.         $isBorgerPlanLetterEnabled = ( isset($_SERVER['isBorgerPlanLetterEnabled']) && $_SERVER['isBorgerPlanLetterEnabled']) ? "True" "False";
  6103.         $isActivityAccessSet = ( isset($_SERVER['isActivityAccessSet']) && $_SERVER['isActivityAccessSet']) ? "True" "False";
  6104.     
  6105.         $cssStyle "<style>
  6106.             table { width='600px';text-align: left;width: 950px;border-collapse: collapse;padding: 10px;}
  6107.             table th {  width: 40%;  border: 1px solid black;  padding: 10px;}
  6108.             table td {  width: 60%;  border: 1px solid black;  padding: 10px;}
  6109.         </style>";
  6110.         echo $cssStyle "<table>"
  6111.         "<tr><th>APP_DEBUG</th><td>$APP_DEBUG</td></tr>"
  6112.         "<tr><th>isCprLookupActiveVal</th><td>$isCprLookupActiveVal</td></tr>"
  6113.         "<tr><th>showRapportUrl</th><td>$showRapportUrl</td></tr>"
  6114.         "<tr><th>isCopenhagen</th><td>$isCopenhagen</td></tr>"
  6115.         "<tr><th>isBackendEnabled</th><td>$isBackendEnabled</td></tr>"
  6116.         "<tr><th>isTestServer</th><td>$isTestServer</td></tr>"
  6117.         "<tr><th>pageResultLimit listing 5 section</th><td>$pageResultLimit</td></tr>"
  6118.         "<tr><th>indexPageSearchLimit</th><td>$indexPageSearchLimit</td></tr>"
  6119.         "<tr><th>isBorgerPlanLetterEnabled</th><td>$isBorgerPlanLetterEnabled</td></tr>"
  6120.         "<tr><th>image_data</th><td>$image_data</td></tr>"
  6121.         "<tr><th>image_data_cubf</th><td>$image_data_cubf</td></tr>"
  6122.         "<tr><th>image_data_rfc</th><td>$image_data_rfc</td></tr>"
  6123.         "<tr><th>isActivityAccessSet</th><td>$isActivityAccessSet</td></tr>"
  6124.         "</table>";
  6125.         die("\n" $responce);
  6126.     }
  6127.     
  6128.     public function getRapportPdf(Request $request) {
  6129.         $em $this->getDoctrine()->getManager();
  6130.         $session $request->getSession();
  6131.         $selectedPatient $session->get("selectedPatient"false);
  6132.         $selectedDialogue $session->get("selectedDialogue"false);
  6133.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  6134.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  6135.         $user $this->get('security.token_storage')->getToken()->getUser();
  6136.         $webPath $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
  6137.         $shareListIds $request->get('shareListIds');
  6138.         $shareListIdArr explode(','$shareListIds);
  6139.         $shareListIdArr array_unique($shareListIdArr);
  6140.         $participantUserIds $request->get('participantUserIds');
  6141.         $participantMessages $request->get('participant_message');
  6142.         $shareTemplateSelectType $request->get('share_template_select_type');
  6143.         $skeleringFormContentHtmlData$request->get('skaleringContent');
  6144.         //$sharetype = $request->get('shareType');
  6145.         $container $this->container;
  6146.         $caseActivityId '';
  6147.         $profession $user->getProfession();
  6148.         //$dialogueAttachmentObj = new DialogueAttachmentController();
  6149.         
  6150.         if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')   
  6151.             $url "https://";   
  6152.         else  
  6153.             $url "http://";  
  6154.              
  6155.         $url.= $_SERVER['HTTP_HOST'];
  6156.         //for sagsakter pdf
  6157.         $generatedPDFFile $this->processShareActivityPdf($em,$container,$dialogue,$patient,$user,$participantUserIds,$shareListIdArr,'',$skeleringFormContentHtmlData);
  6158.         $selectedFile $generatedPDFFile;
  6159.         //$selectedFile = "CaseActivityTemplate_61c314511b7ab8.46814130.pdf";
  6160.         $ext pathinfo($selectedFilePATHINFO_EXTENSION);
  6161.         $onlyFileName pathinfo($selectedFilePATHINFO_FILENAME);
  6162.         $newFilename $onlyFileName."." $ext;
  6163.         $rapportSagsakPdf $newFilename;
  6164.         $folgebrevFiles = array();
  6165.         $index 0;
  6166.         foreach ($participantUserIds as $participantUserId){
  6167.             $participantMessage $participantMessages[$index];
  6168.             $tunnelUserObj=$participantUser=$fileNameNew='';
  6169.             if($shareTemplateSelectType == 1){
  6170.                 $tunnelUserObj $em->getRepository(SepoTunnelliste::class)->findOneBy(array("rid" => $participantUserId));
  6171.             }else{
  6172.                 $participantUser $em->getRepository(User::class)->find($participantUserId);
  6173.             }
  6174.             $dialogueAttachmentControllerObj = new DialogueAttachmentController();
  6175.             if($shareTemplateSelectType == || $shareTemplateSelectType == 3){
  6176.                 $mailSubject "Delte dokumenter";//$dialogue->getSharedExternalTitle($user);
  6177.                 $messageTextConsentForPdf $this->get('templating')->render('message/share_activity-external-tunnel-dialogue-citizen-pdf.html.twig', array(
  6178.                 'participantMessage' => $participantMessage,
  6179.                 'userObj' => $tunnelUserObj,
  6180.                 'participantUser' => $participantUser,
  6181.                 'patient' => $patient,
  6182.                 'dialogueObj' => $dialogue,
  6183.                 'loginUserObj' => $user,
  6184.                 'subject' => $mailSubject,
  6185.                 'shareTemplateSelectType' => $shareTemplateSelectType
  6186.                 ));
  6187.                 $citizenAddressFilePath $dialogueAttachmentControllerObj->getTunnelExternlCitizenAddress($container,$dialogue,$user,$tunnelUserObj,$participantUser,$messageTextConsentForPdf,'',$shareTemplateSelectType);
  6188.             }else{
  6189.                 $citizenAddressFilePath $dialogueAttachmentControllerObj->getRapportCitizenAddress($container,$dialogue,$user,$participantUser,$shareListIdArr,$participantMessage,'');
  6190.             }
  6191.             $selectedFolgebrevFile $citizenAddressFilePath;
  6192.             //$selectedFolgebrevFile = "RapportPageOneTemplate_61c314896af429.09612605_89.pdf ";
  6193.             $ext2 pathinfo($selectedFolgebrevFilePATHINFO_EXTENSION);
  6194.             $fileName pathinfo($selectedFolgebrevFilePATHINFO_FILENAME);
  6195.             $fileNameNew $fileName."." $ext2;
  6196.             $folgebrevFiles[$participantUserId] ['folgebrevFilePath'] = $fileNameNew;
  6197.             $index++;
  6198.         }
  6199.         $listId explode(','$shareListIds);
  6200.         $totalSize 0;
  6201.         foreach ($listId as $id){
  6202.             $fileSize $this->getFilesSize($user,$em,$id,'');
  6203.             $totalSize += $fileSize;
  6204.         }
  6205.         $totalSize += filesize($webPath.$newFilename) + filesize($webPath.$fileNameNew);
  6206.         $responce 'success';
  6207.         $response = new Response(json_encode(array('result' => $responce'rapportSagsakPdf' => $rapportSagsakPdf'folgebrevFiles' => $folgebrevFiles,'fileSizes' => $totalSize)));
  6208.         $response->headers->set('Content-Type''application/json');
  6209.         return $response
  6210.     }
  6211.     public function getDeleteRapportPdf(Request $request) {
  6212.         $em $this->getDoctrine()->getManager();
  6213.         $session $request->getSession();
  6214.         $selectedPatient $session->get("selectedPatient"false);
  6215.         $selectedDialogue $session->get("selectedDialogue"false);
  6216.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  6217.         $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  6218.         $user $this->get('security.token_storage')->getToken()->getUser();
  6219.         $webPath $this->get('kernel')->getProjectDir().'/public/uploads/attachments/';
  6220.         $participantPdfs $request->get('participantPdfs');
  6221.         $folgebrevPdfs $request->get('folgebrevPdfs');
  6222.         //delete participantPdfs
  6223.         foreach ($participantPdfs as $participantPdf){
  6224.             $ext2 pathinfo($participantPdfPATHINFO_EXTENSION);
  6225.             $fileName pathinfo($participantPdfPATHINFO_FILENAME);
  6226.             $fileNameNew $fileName."." $ext2;
  6227.             $filePath $webPath $fileNameNew;
  6228.             if (file_exists($filePath)) {
  6229.                 unlink($filePath);
  6230.             }
  6231.         }
  6232.         //delete folgebrevPdfs
  6233.         foreach ($folgebrevPdfs as $folgebrevPdf){
  6234.             $ext21 pathinfo($folgebrevPdfPATHINFO_EXTENSION);
  6235.             $fileName1 pathinfo($folgebrevPdfPATHINFO_FILENAME);
  6236.             $fileNameNew1 $fileName1."." $ext21;
  6237.             $filePath1 $webPath $fileNameNew1;
  6238.             if (file_exists($filePath1)) {
  6239.                 unlink($filePath1);
  6240.             }
  6241.         }
  6242.         $responce 'success';
  6243.         $response = new Response(json_encode(array('result' => $responce)));
  6244.         $response->headers->set('Content-Type''application/json');
  6245.         return $response
  6246.     }
  6247.     function formatSizeUnits($bytes)
  6248.     {
  6249.         if ($bytes >= 1073741824)
  6250.         {
  6251.             $bytes number_format($bytes 10737418242) . ' GB';
  6252.         }
  6253.         elseif ($bytes >= 1048576)
  6254.         {
  6255.             $bytes number_format($bytes 10485762) . ' MB';
  6256.         }
  6257.         elseif ($bytes >= 1024)
  6258.         {
  6259.             $bytes number_format($bytes 10242) . ' KB';
  6260.         }
  6261.         elseif ($bytes 1)
  6262.         {
  6263.             $bytes $bytes ' bytes';
  6264.         }
  6265.         elseif ($bytes == 1)
  6266.         {
  6267.             $bytes $bytes ' byte';
  6268.         }
  6269.         else
  6270.         {
  6271.             $bytes '0 bytes';
  6272.         }
  6273.         return $bytes;
  6274.     }
  6275.         
  6276.     public function createPatientGardian($em$newPatient$parentCategory$userLabelText$guardianHasCustody$guardianCustodySince$guardiancprNo$guardianFullname$guardianIsShowAddress$userAddress$userPostno$userCity) {
  6277.         $u $em->getRepository(User::class)->findOneBy(array('username' => $guardiancprNo));
  6278.         $guardian $em->getRepository(Family::class)->findOneBy(array("patient" => $newPatient'relative' => $u));
  6279.         if (!$guardian) {
  6280.             $guardian = new Family();
  6281.             //$u = $this->createRelative($guardianObject);
  6282.             $u $this->createGardianRelative($em$guardiancprNo$guardianFullname$guardianIsShowAddress$userAddress$userPostno$userCity);
  6283.             if (!$u->hasRole('ROLE_PARENT')) {
  6284.                 $u->addRole('ROLE_PARENT');
  6285.                 $u->setCategory($parentCategory);
  6286.                 $u->setEnabled(true);
  6287.             }
  6288.         } else {
  6289.             //$u = $this->createRelative($guardianObject);
  6290.             $u $this->createGardianRelative($em$guardiancprNo$guardianFullname$guardianIsShowAddress$userAddress$userPostno$userCity);
  6291.             $guardian->setRelation(Family::REL_GUARDIAN);
  6292.         }
  6293.         if (trim($u->getStamdataLabel()) == "-") {
  6294.             $u->setStamdataLabel(NULL);
  6295.         } else {
  6296.             $u->setStamdataLabel($userLabelText);
  6297.         }
  6298.         $guardian->setHasCustody($guardianHasCustody);
  6299.         $guardian->setCustodySince($guardianCustodySince);
  6300.         $guardian->setIsParticipant(false);
  6301.         $guardian->setRelative($u);
  6302.         return $guardian;
  6303.     }
  6304.     
  6305.     public function createGardianRelative($em$usercpr$userFullname$guardianIsShowAddress$userAddress=NULL$userPostno=NULL$userCity=NULL) {
  6306.         //$serviceResponse = $this->doSoapRequest(208, $this->getFieldValue($relativeObject, 'PNR_FOEDDATO'));
  6307.         //$parentObject = $serviceResponse->Gctp->System->Service->CprData->Rolle->Table->Row[0];
  6308.         //Check this user is already exist or not
  6309.         //$em = $this->getDoctrine()->getManager();
  6310.         //$cprNo = $this->getFieldValue($relativeObject, 'PNR_FOEDDATO');
  6311.         $user $em->getRepository(User::class)->findOneBy(array('username' => $usercpr));
  6312.         $isNew false;
  6313.         if($user) {
  6314.             $user $user $user NULL;
  6315.         } else {
  6316.             $user = new Relative();
  6317.             $isNew true;
  6318.         }
  6319.         if(strlen($userFullname) > && $user) {
  6320.             $sname explode(' 'addslashes(trim($userFullname)), 2);
  6321.             $userFirstname = ($sname[0]);
  6322.             $userLastname = (isset($sname[1]) ? $sname[1] : '-');
  6323.         
  6324.             $user->setFirstName($userFirstname);
  6325.             $user->setLastName($userLastname);
  6326.             $user->setUsername($usercpr);
  6327.             if(!$guardianIsShowAddress) { //!="00001"
  6328.                 $user->setAddress($userAddress);
  6329.                 //$user->setAddressLine2('');
  6330.                 $user->setPostNumber($userPostno);
  6331.                 $user->setCity($userCity);
  6332.             }
  6333.             if($isNew) {
  6334.                 $em->persist($user);
  6335.                 $em->flush();
  6336.             }
  6337.             return $user;
  6338.         }
  6339.     }
  6340.     //create dialougecase card details
  6341.     public function createDefaultDialougeCaseCard($user,$patient,$dialogue) {
  6342.         $em $this->getDoctrine()->getManager();
  6343.         $predefinedCaseCardObj $em->getRepository(PredefinedCaseCard::class)->findOneBy(array('caseCardType' => 'Notat'));
  6344.         $dialougeCaseCardObj $em->getRepository(DialogueCaseCard::class)->findOneBy(array('dialogue' => $dialogue,'pCaseCardId'=>$predefinedCaseCardObj->getId()));
  6345.         if($predefinedCaseCardObj && !$dialougeCaseCardObj){
  6346.             $card = new DialogueCaseCard();
  6347.             $card->setPatient($patient);
  6348.             $card->setDialogue($dialogue);
  6349.             $card->setPCaseCardId($predefinedCaseCardObj);
  6350.             $card->setCreatedBy($user);
  6351.             $em->persist($card);
  6352.             $em->flush();
  6353.             $dialogueCaseCardControllerObj = new DialogueCaseCardController();
  6354.             $history $dialogueCaseCardControllerObj->saveCaseCardHistory($em$card'N',$dialogue,null$user);
  6355.             return $card;  
  6356.         }      
  6357.         return $dialougeCaseCardObj;  
  6358.     }
  6359.     public function featchAllScalingGraphDetails($em,$dialogueAttachmentDetailObj){
  6360.         //Get scaling progression records
  6361.         $shortMonthArray = array('01' => "Jan"'02' => "Feb"'03' => "Mar"'04' => "Apr"'05' => "Maj",
  6362.             '06' => "Jun"'07' => "Jul"'08' => "Aug"'09' => "Sep"'10' => "Okt"'11' => "Nov"'12' => "Dec");
  6363.         $scalingProgressionObj $em->getRepository(ScalingProgression::class)->findBy(array('dialogueAttachmentDetail' => $dialogueAttachmentDetailObj'isDeleted' => false));
  6364.         $scalingProgressionArray = array();
  6365.         $scalingIndividualGraphArray = array();
  6366.         foreach ($scalingProgressionObj as $scalingProgression) {
  6367.             $scalingProgressionObjId $scalingProgression->getId();
  6368.             $scalingGraph $em->getRepository(ScalingGraph::class)->getAllScalingRecordByProgression($scalingProgressionObjId);
  6369.             $totalUserCount count($scalingGraph);
  6370.             $userGrade $avgUserGrade 0;
  6371.             $userNameNGrade "";
  6372.             foreach ($scalingGraph as $spRecord) {
  6373.                 $userGrade = ($userGrade $spRecord->getGrade());
  6374.                 $userCurrentGrade $spRecord->getGrade();
  6375.                 $userNameNGrade $userNameNGrade.$spRecord->getUser()->getFullName()."($userCurrentGrade)_";
  6376.                 
  6377.                 //Participants individual graph records
  6378.                 $indiStartDate $spRecord->getCreatedAt();
  6379.                 $indiYear $indiStartDate->format('Y');
  6380.                 $indiMonth $shortMonthArray[$indiStartDate->format('m')];
  6381.                 //$scalingIndividualGraphArray['userId'] = $spRecord->getUser()->getId();
  6382.                 $scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['id'] = $spRecord->getId();
  6383.                 $scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['user'] = $spRecord->getUser();
  6384.                 $scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['progression'] = $spRecord->getProgression();
  6385.                 $scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['grade'] = $spRecord->getGrade();
  6386.                 $scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['displayYear'] = $indiYear;
  6387.                 $scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['displayMonth'] = strtoupper($indiMonth);
  6388.                 $scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['createdAt'] = $spRecord->getCreatedAt();
  6389.                 $scalingIndividualGraphArray[$dialogueAttachmentDetailObj->getId()][$spRecord->getId()]['updatedAt'] = $spRecord->getUpdatedAt();
  6390.             }
  6391.             //var_dump($userNameNGrade); die;
  6392.             if ($totalUserCount 0) {
  6393.                 $avgUserGrade = ($userGrade $totalUserCount);
  6394.             }
  6395.             $startDate $scalingProgression->getStartDate();
  6396.             $year $startDate->format('Y');
  6397.             $month $shortMonthArray[$startDate->format('m')];
  6398.             $scalingProgressionArray[$scalingProgression->getId()]['id'] = $scalingProgression->getId();
  6399.             $scalingProgressionArray[$scalingProgression->getId()]['avg_cnt'] = (int) round($avgUserGrade);
  6400.             $scalingProgressionArray[$scalingProgression->getId()]['totalUserCount'] = $totalUserCount;
  6401.             $scalingProgressionArray[$scalingProgression->getId()]['start_by'] = $scalingProgression->getStartBy();
  6402.             $scalingProgressionArray[$scalingProgression->getId()]['dialogue'] = $scalingProgression->getDialogue();
  6403.             $scalingProgressionArray[$scalingProgression->getId()]['start_date'] = $scalingProgression->getStartDate();
  6404.             $scalingProgressionArray[$scalingProgression->getId()]['displayYear'] = $year;
  6405.             $scalingProgressionArray[$scalingProgression->getId()]['displayMonth'] = strtoupper($month);
  6406.             $scalingProgressionArray[$scalingProgression->getId()]['end_date'] = $scalingProgression->getEndDate();
  6407.             $scalingProgressionArray[$scalingProgression->getId()]['userParticipant'] = $scalingGraph;
  6408.             $scalingProgressionArray[$scalingProgression->getId()]['toolTipUserList'] = $userNameNGrade;
  6409.         }
  6410.         return array('scalingProgressionArray'=>$scalingProgressionArray,'scalingIndividualGraphArray'=>$scalingIndividualGraphArray);
  6411.     }
  6412.     public function createMeasureOnLoad($dialogueCaseCardObj,$user){
  6413.         $em $this->getDoctrine()->getManager();
  6414.         $ccId 38;
  6415.             $todaysDate date("Y-m-d");
  6416.             $caseCardMeasure $em->getRepository(CaseCardMeasure::class)->findBy(array('pCaseCard'=> $ccId,'referenceType' => 'F'));
  6417.             foreach($caseCardMeasure as $measure){
  6418.                 $dialogueCaseCardMeasureObj $em->getRepository(DialogueCaseCardMeasure::class)->findOneBy(array('DialogueCaseCard' => $dialogueCaseCardObj'measure' => $measure));
  6419.                 if(!$dialogueCaseCardMeasureObj){
  6420.                     $dialogueCaseCardMeasure = new DialogueCaseCardMeasure();
  6421.                     $dialogueCaseCardMeasure->setCreatedBy($user);
  6422.                     $dialogueCaseCardMeasure->setDialogueCaseCard($dialogueCaseCardObj);
  6423.                     $dialogueCaseCardMeasure->setMeasure($measure);
  6424.                     $dialogueCaseCardMeasure->setReferenceType('F');
  6425.                     $dialogueCaseCardMeasure->setFromDate(new \DateTime($todaysDate));
  6426.                     $dialogueCaseCardMeasure->setResponsiblePerson($user);
  6427.                     $em->persist($dialogueCaseCardMeasure);
  6428.                     $em->flush();
  6429.                 } 
  6430.             } 
  6431.             return true;
  6432.     }
  6433.     public function saveSkabelonDate(Request $request,$skId){
  6434.         $em $this->getDoctrine()->getManager();
  6435.         $skabelonDate $request->get('skabelonDate');
  6436.         $dialogueAttachmentDetailObj $em->getRepository(DialogueAttachmentDetails::class)->find($skId);
  6437.         //var_dump($dialogueAttachmentDetailObj);die;
  6438.         if ($skabelonDate != "") {
  6439.               $selectedDate = new \DateTime($skabelonDate);
  6440.               $time_now = new \DateTime();
  6441.               $merge = new \DateTime($selectedDate->format('Y-m-d') . ' ' $time_now->format('H:i:s'));
  6442.               $setSelectedDate $merge->format('Y-m-d H:i:s');
  6443.               $dialogueAttachmentDetailObj->setAttachmentDate(new \DateTime($setSelectedDate));
  6444.         }
  6445.         $em->persist($dialogueAttachmentDetailObj);
  6446.         $em->flush();
  6447.         $response "success";
  6448.         $response = new Response(json_encode(array('data' => $response)));
  6449.         $response->headers->set('Content-Type''application/json');
  6450.         return $response;
  6451.     }
  6452.     
  6453.     public function createSkelringCaseActivity($user,$patient,$dialogue,$dialogueCaseCardObj){
  6454.         $em $this->getDoctrine()->getManager();
  6455.         //$session = $request->getSession();
  6456.         $response "fail";
  6457.         $lastInsertedNoteId='';
  6458.         $topic 'Trivselsvurdering';
  6459.         $selectedDateAttachment '';
  6460.         $reminderDateAttachment '';
  6461.         $isDraft 1;
  6462.         $isAttachmentPrivate '';
  6463.         $attachmentText '';
  6464.         $dialogueCaseCardMeasureId '';
  6465.         $measureId '';
  6466.         $holdId '';
  6467.         $today1 = new \DateTime();
  6468.         $after14days $today1->modify('+14 day');
  6469.         $predefinedCaseCardObj $em->getRepository(PredefinedCaseCard::class)->findOneBy(array('caseCardType' => 'Notat'));
  6470.         $predefinedAttachmentTypeObj $em->getRepository(PredefinedAttachmentType::class)->findOneBy(array('attachmentType' => 'Skalering'));
  6471.         $predefinedCaseCard $predefinedCaseCardObj->getId();
  6472.         $predefinedTypeId $predefinedAttachmentTypeObj->getId();
  6473.         $selectedPatientObj $em->getRepository(Patient::class)->find($patient->getId());
  6474.         $selectedDialogueObj $em->getRepository(Dialogue::class)->find($dialogue->getId());
  6475.         if ($predefinedCaseCard != "0" && $predefinedTypeId != "0") {
  6476.             $dialogueAttachmentDetailsObj = new DialogueAttachmentDetails();
  6477.             $dialogueAttachmentDetailsObj->setPatient($selectedPatientObj);
  6478.             $dialogueAttachmentDetailsObj->setDialogue($selectedDialogueObj);
  6479.             if($dialogueCaseCardObj){
  6480.                 $dialogueAttachmentDetailsObj->setDialogueCaseCard($dialogueCaseCardObj);
  6481.             }
  6482.             $dialogueAttachmentDetailsObj->setUser($user);
  6483.             $dialogueAttachmentDetailsObj->setPCaseCardId($predefinedCaseCardObj);
  6484.             $dialogueAttachmentDetailsObj->setPAtttachmentType($predefinedAttachmentTypeObj);
  6485.             $dialogueAttachmentDetailsObj->setTypeHeading($predefinedAttachmentTypeObj->getAttachmentType());
  6486.             $dialogueAttachmentDetailsObj->setAttachmentHeading($topic);
  6487.             $dialogueAttachmentDetailsObj->setIsDraft($isDraft);
  6488.             if($isDraft == 0){
  6489.                 $today = new \DateTime();
  6490.                 $tomorrow $today->modify('+1 day');
  6491.                 $dialogueAttachmentDetailsObj->setPostJournaliseDate($tomorrow);
  6492.             }
  6493.             //if ($selectedDateAttachment != "") {
  6494.                 $selectedDate = new \DateTime($selectedDateAttachment);
  6495.                 $time_now = new \DateTime();
  6496.                 $merge = new \DateTime($selectedDate->format('Y-m-d') . ' ' $time_now->format('H:i:s'));
  6497.                 $setSelectedDate $merge->format('Y-m-d H:i:s');
  6498.                 $dialogueAttachmentDetailsObj->setAttachmentDate(new \DateTime($setSelectedDate));
  6499.             //}
  6500.             if ($reminderDateAttachment != "") {
  6501.                 $dialogueAttachmentDetailsObj->setReminderDate(new \DateTime($reminderDateAttachment));
  6502.             }
  6503.             if ($attachmentText != "") {
  6504.                 $dialogueAttachmentDetailsObj->setAttachmentText($attachmentText);
  6505.             }
  6506.             $dialogueAttachmentDetailsObj->setVisibleStatus($isAttachmentPrivate);
  6507.             
  6508.             if($dialogueCaseCardMeasureId == "0") {
  6509.                 $dialogueAttachmentDetailsObj->setDialogueCaseCardMeasureId(NULL);
  6510.                 $dialogueAttachmentDetailsObj->setMeasureId(NULL);
  6511.             } else {
  6512.                 $dialogueCaseCardMeasureObj $em->getRepository(DialogueCaseCardMeasure::class)->find($dialogueCaseCardMeasureId);
  6513.                 $dialogueAttachmentDetailsObj->setDialogueCaseCardMeasureId($dialogueCaseCardMeasureObj);
  6514.                 $caseCardMeasureObj $em->getRepository(CasecardMeasure::class)->find($measureId);
  6515.                 $dialogueAttachmentDetailsObj->setMeasureId($caseCardMeasureObj);
  6516.             }
  6517.             
  6518.             if(($holdId == "0") || $holdId == NULL ){
  6519.                 $dialogueAttachmentDetailsObj->setHold(NULL);
  6520.             } else {
  6521.                 $holdObj $em->getRepository(JoCaseCardHold::class)->find($holdId);
  6522.                 $dialogueAttachmentDetailsObj->setHold($holdObj);
  6523.             }
  6524.             
  6525.             $activityTypeVal 0;
  6526.             if($predefinedTypeId == '5' && $isDraft == "1") {
  6527.                 $activityTypeVal 6;
  6528.             } else if($predefinedTypeId == '5' && $isDraft == "0") {
  6529.                 $activityTypeVal 5;
  6530.             } else if($predefinedTypeId <> '5' && $isDraft == "1") {
  6531.                 $activityTypeVal 8;
  6532.             } else if($predefinedTypeId <> '5' && $isDraft == "0") {
  6533.                 $activityTypeVal 7;
  6534.             }
  6535.             $dialogueAttachmentDetailsObj->setActivityType($activityTypeVal);
  6536.             $dialogueAttachmentDetailsObj->setScaleGrade(0);
  6537.             $em->persist($dialogueAttachmentDetailsObj);
  6538.             $em->flush();
  6539.             /***********************************scaling progression*********************************/
  6540.             $scalingProgressionObj = new ScalingProgression();
  6541.             $scalingProgressionObj->setStartBy($user);
  6542.             $scalingProgressionObj->setPatient($selectedPatientObj);
  6543.             $scalingProgressionObj->setDialogue($selectedDialogueObj);
  6544.             $scalingProgressionObj->setDialogueAttachmentDetail($dialogueAttachmentDetailsObj);
  6545.             $scalingProgressionObj->setIsDeleted(false);
  6546.             $scalingProgressionObj->setStartDate(new \DateTime());
  6547.             $scalingProgressionObj->setEndDate($after14days);
  6548.             //$scalingProgressionObj->setCreatedAt(new \DateTime());
  6549.             //$scalingProgressionObj->setUpdatedAt(new \DateTime());
  6550.             $em->persist($scalingProgressionObj);
  6551.             $em->flush();
  6552.             /***********************************scaling Graph***************************************/
  6553.             $scalingGraphObj = new ScalingGraph();
  6554.             $scalingGraphObj->setUser($user);
  6555.             $scalingGraphObj->setPatient($selectedPatientObj);
  6556.             $scalingGraphObj->setDialogue($selectedDialogueObj);
  6557.             $scalingGraphObj->setProgression($scalingProgressionObj);
  6558.             $scalingGraphObj->setGrade(0);
  6559.             //$scalingGraphObj->setCreatedAt(new \DateTime());
  6560.             //$scalingGraphObj->setUpdatedAt(new \DateTime());
  6561.             $em->persist($scalingGraphObj);
  6562.             $em->flush();
  6563.             if($dialogueCaseCardMeasureId){
  6564.                 $this->addFlash('openDialogueCaseCardMeasureId',$dialogueCaseCardMeasureId);
  6565.             }
  6566.             //$session->set('activityDetailUpdated', $dialogueAttachmentDetailsObj->getId());
  6567.             //File upload code for new records
  6568.             $response "success";
  6569.             //$lastInsertedNoteId = $dialogueAttachmentDetailsObj->getId();
  6570.         }
  6571.         return $response;
  6572.     }
  6573.     public function getFilesSize($user,$em,$attachId,$type){
  6574.         $totalSize 0;
  6575.         $dialogueAttachments $em->getRepository(DialogueAttachments::class)->findBy(array('dialogueAttachmentDetailId' => $attachId));
  6576.         foreach ($dialogueAttachments as $dialogueAttachment) {
  6577.             $id $dialogueAttachment->getDialogueAttachmentDetailId()->getId();
  6578.             $fileIsImported false;
  6579.             $isSharedJournal false;
  6580.             if(isset($dialogueAttachment) && !empty($dialogueAttachment)) {
  6581.                 $fileIsImported $dialogueAttachment->getIsImported();
  6582.                 $isSharedJournal $dialogueAttachment->getIsSharedJournal();
  6583.             }
  6584.             if($isSharedJournal) {
  6585.                 $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/attachmentsJournal/';
  6586.             } else if($fileIsImported) {
  6587.                 $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/kingo/';
  6588.             } else {
  6589.                 $webPath $this->get('kernel')->getProjectDir() . '/public/uploads/attachments/';
  6590.             }
  6591.             if(file_exists($webPath.$dialogueAttachment->getAttachmentName())){
  6592.                 $fileSize filesize($webPath.$dialogueAttachment->getAttachmentName());
  6593.                 $totalSize += $fileSize;
  6594.             }
  6595.         }
  6596.         if($type){
  6597.             return $this->formatSizeUnits($totalSize);
  6598.         }else{
  6599.             return $totalSize;
  6600.         }
  6601.     }
  6602.     public function updateSkaleringAttachment($dialogue,$patient,$em){
  6603.       $dialogueAttachmentDetailsSkalering $em->getRepository(DialogueAttachmentDetails::class)->findOneBy(array('dialogue' => $dialogue,'patient'=>$patient,'pAtttachmentType'=>34));
  6604.       $dialogueAttachmentDetailsSkalering->setAttachmentDate(new \DateTime());
  6605.       $dialogueAttachmentDetailsSkalering->setUpdatedAt(new \DateTime());
  6606.       $em->persist($dialogueAttachmentDetailsSkalering);
  6607.       $em->flush();
  6608.     }
  6609.     public function maintaineUserLog($em,$user,$case_no,$case_card_id,$activity_id,$activity,$forslatling_id,$pccId,$dialogue_case_card_measure)
  6610.     {
  6611.         if($case_no != ''){
  6612.             $user_case_log = new UserCaseLogger();
  6613.             $user_case_log->setUser($user);
  6614.             $user_case_log->setCreatedAt(new \DateTime());
  6615.             $user_case_log->setUpdatedAt(new \DateTime());
  6616.             $user_case_log->setCaseNo($case_no);
  6617.             $em->persist($user_case_log);
  6618.             $em->flush();
  6619.         } 
  6620.         // for maitain log for UserCaseActivity when click on activity arrow
  6621.         if($activity_id != ''){
  6622.         $user_case_activity_log = new UserCaseActivityLogger();
  6623.         $user_case_activity_log->setUser($user);
  6624.         $user_case_activity_log->setCreatedAt(new \DateTime());
  6625.         $user_case_activity_log->setUpdatedAt(new \DateTime());
  6626.         if($activity->getMeasureId() != ''){
  6627.              $user_case_activity_log->setForslatlingId($activity->getMeasureId()->getId());
  6628.         }else{
  6629.         $user_case_activity_log->setForslatlingId(NULL);
  6630.         }
  6631.         $user_case_activity_log->setActivityId($activity_id);
  6632.         $user_case_activity_log->setCaseNo($activity->getDialogue()->getCaseNo());
  6633.         $user_case_activity_log->setCaseCardId($activity->getCaseCard()->getId());
  6634.            if($activity->getDialogue()->getdialogueType() == || $activity->getDialogue()->getdialogueType() == 4){
  6635.                 $user_case_activity_log->setDialogueCaseCardMeasureId($dialogue_case_card_measure $dialogue_case_card_measure NULL);
  6636.             }
  6637.         $em->persist($user_case_activity_log);
  6638.         $em->flush();
  6639.         }
  6640.          //for maitaine logger for case no and case card when click on index sagskort
  6641.          if($case_card_id !=''){
  6642.         //  $user_case_log = new UserCaseLogger();
  6643.         //  $user_case_log->setUser($user);
  6644.         //  $user_case_log->setCreatedAt(new \DateTime());
  6645.         //  $user_case_log->setUpdatedAt(new \DateTime());
  6646.         //  $user_case_log->setCaseNo($case_card_id->getDialogue()->getCaseNo());
  6647.         //  $em->persist($user_case_log);
  6648.         //  $em->flush();
  6649.  
  6650.          $user_case_card_log = new UserCaseCardLogger();
  6651.          $user_case_card_log->setUser($user);
  6652.          $user_case_card_log->setCreatedAt(new \DateTime());
  6653.          $user_case_card_log->setUpdatedAt(new \DateTime());
  6654.          $user_case_card_log->setCaseCardId($case_card_id->getPCaseCardId()->getId());
  6655.          $user_case_card_log->setCaseNo($case_card_id->getDialogue()->getCaseNo());
  6656.          $em->persist($user_case_card_log);
  6657.          $em->flush();
  6658.          }
  6659.         // for maitain log for UserCaseActivity click on count of activity on opened sagskort
  6660.         if($forslatling_id != ''){
  6661.             // var_dump($dialogue_case_card_measure);die;
  6662.            $user_case_activity_log = new UserCaseActivityLogger();
  6663.            $user_case_activity_log->setUser($user);
  6664.            $user_case_activity_log->setCreatedAt(new \DateTime());
  6665.            $user_case_activity_log->setUpdatedAt(new \DateTime());
  6666.            $user_case_activity_log->setForslatlingId($forslatling_id);
  6667.            $user_case_activity_log->setCaseNo($activity->getCaseNo());
  6668.            $user_case_activity_log->setActivityId(NULL);
  6669.            $user_case_activity_log->setCaseCardId($pccId);   
  6670.            if($activity->getdialogueType() == || $activity->getdialogueType() == 4){
  6671.                 $user_case_activity_log->setDialogueCaseCardMeasureId($dialogue_case_card_measure $dialogue_case_card_measure NULL);
  6672.            }
  6673.            $em->persist($user_case_activity_log);
  6674.            $em->flush();
  6675.         }  
  6676.     }
  6677.     public function callStamdataUpdate(Request $request) {
  6678.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  6679.         $em $this->getDoctrine()->getManager();
  6680.         $session $request->getSession();
  6681.         //$patientInfo = trim($request->get('patientInfo'));
  6682.         //$patient = $em->getRepository(Patient::class)->find($patientInfo);
  6683.         $selectedPatient $session->get("selectedPatient"false);
  6684.         $patient $em->getRepository(Patient::class)->find($selectedPatient->getId());
  6685.         
  6686.         $cprEncode $patient->getUserCprEncode();
  6687.         if($patient && !($patient->getIsDummyPatient()) && !($patient->getIsFakeCpr())) {
  6688.             $this->updateAllStamdata($patient$session);
  6689.            
  6690.         }
  6691.         
  6692.         return $this->redirectToRoute('create_case_with_existing',['cprNo' => $cprEncode]);
  6693.     }
  6694.     public function changeInstitution(Request $request){
  6695.         $session $request->getSession();
  6696.         $institutionId $request->get('institutionId');
  6697.         $institutionName $request->get('institutionName');
  6698.         $session->set('institutionName',$institutionName);
  6699.         $session->set('selectedInstitutionId',$institutionId);
  6700.         $response "success";
  6701.         $response = new Response(json_encode(array('data' => $response)));
  6702.         $response->headers->set('Content-Type''application/json');
  6703.         return $response;
  6704.     }
  6705.     public function checkCurrentCase(Request $request) {
  6706.         $user $this->get('security.token_storage')->getToken()->getUser();
  6707.         $dialogueId $patientName $patientId '';
  6708.         //if (!($user)) {
  6709.         if (!is_object($user)) {
  6710.             $patientId = -1;
  6711.         }else{
  6712.             //$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  6713.             $em $this->getDoctrine()->getManager();
  6714.             $session $request->getSession();
  6715.         
  6716.             
  6717.             $selectedPatient $session->get("selectedPatient"null);
  6718.             $selectedDialogue $session->get("selectedDialogue"null);
  6719.             if($selectedDialogue){
  6720.                 $dialogue $em->getRepository(Dialogue::class)->find($selectedDialogue->getId());
  6721.                 $patientName $dialogue->getPatient()->getFullName();
  6722.                 $patientId $dialogue->getPatient()->getId();
  6723.                 $dialogueId $dialogue->getId();
  6724.             }
  6725.         }
  6726.         
  6727.         
  6728.         $responce 'success';
  6729.         $response = new Response(json_encode(array('dialogueId' => $dialogueId'patientId' => $patientId'patientName' => $patientName)));
  6730.         $response->headers->set('Content-Type''application/json');
  6731.         return $response;
  6732.     }
  6733. }