src/Controller/DefaultController.php line 74

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