<?php

	class requestController extends mainController {



		function __construct() {

			parent::__construct();



			//To change for every Controllers

			$this->viewDir = 'Request';



			//$this->allow = [];



			define('MAX_ATTACH_TITLE_LENGTH', 30);

		}



		//List the requests

		public function index() {



			if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID, REFERRER_ROLE_ID, GUEST_ROLE_ID])) {

				return $this->redirect('login', 'permissionDenied');

			}



			$this->controllerName = 'request';

			$this->actionName = 'index';



			$hr = new HandleRequest();



			$this->view->logList = $hr->getActivityLogList();



			//Scopes: "my" | "center" | "moderations" | "reports (referral)"

			$this->view->scope = $this->getPost('scope', 'my');

			$this->view->userHasClinicalCenters = true;

			$this->view->baseUri = 'requests/'.time().'/'.$this->view->scope;



			$this->view->currentPage = $this->getPost('pageNumb', 1);

			//$this->view->orderField = $this->getPost('orderField', 'created_at');

			$this->view->orderField = $this->getPost('orderField', 'request_status_number');

			$this->view->orderDir = $this->getPost('orderDir', 'asc');

			//$this->view->orderDir = $this->getPost('orderDir', 'desc');

			$this->view->statusSelectList = $hr->requestStatusLabels;

			

			//Robot (teleconsulti automatici)

			$robot_path = null;

			$this->view->robot_id = -1;

			if (file_exists(PUBLIC_HTML.'sportellocura-aosga-api/robot-id.txt')) {

				$robot_path = PUBLIC_HTML.'sportellocura-aosga-api/robot-id.txt';

			} else {

				if (file_exists(PUBLIC_HTML.'sportellocura-api/robot-id.txt')) {

					$robot_path = PUBLIC_HTML.'sportellocura-api/robot-id.txt';

				}

			}

			

			if (!is_null($robot_path)) {

				$this->view->robot_id = (int)file_get_contents($robot_path);

			}



			$userClinicalCenters = [];

			$userCcRole = 0;

			switch ($this->view->scope) {

				case 'my':

					$userCcRole = APPLICANT_ROLE_ID;

				break;



				case 'center':

					$userCcRole = APPLICANT_ROLE_ID;

				break;



				case 'moderations':

					$userCcRole = MODERATOR_ROLE_ID;

				break;



				case 'reports':

					$userCcRole = REFERRER_ROLE_ID;

				break;



				case 'center-guest':

					$userCcRole = GUEST_ROLE_ID;

				break;

			}



			$hr->setActivityLog($this->user->getUserId(), 'REQ_LISTED', ['userId'=>$this->user->getUserId(), 'scope'=>$this->view->scope]);



			if ($userCcRole > 0) {

				$userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), $userCcRole); //In mainController()

			}



			$this->view->ccSelectList = $userClinicalCenters;



			//Populate the Medical specialties list and the requester list for the column filter

			$ccIdList = [];

			$ccIdListString = '';

			$this->view->msSelectList = [];

			$this->view->requesterSelectList = [];

			foreach($userClinicalCenters as $ccId => $ccInfo) {

				$ccIdList[] = $ccId;

			}



			if (!empty($ccIdList)) {

				$ccIdListString = implode(',', $ccIdList);

				$this->view->debug = $ccIdListString;



				$msResults = $this->db

					->where('ccmst.center_id IN('.$ccIdListString.')')

					->where('ums.status', 1)

					->join('users_medical_specialties ums', 'ums.id=ccmst.specialty_id', 'INNER')

					->groupBy('ccmst.specialty_id')

					->get('clinical_center_medical_specialties_to ccmst', null, ['ccmst.specialty_id', 'ums.description']);



				if (is_array($msResults) && !empty($msResults)) {

					foreach($msResults as $item) {

						$msSelectList[$item['specialty_id']] = _($item['description']);

					}



					//Sorting based on translated descriptions

					asort($msSelectList);



					//Medical specialties list

					$this->view->msSelectList = $msSelectList;

				}



				//Requester list

				$requestersResult = $this->db

					->where('ucct.center_id IN('.$ccIdListString.')')

					->where('ucct.role_id', APPLICANT_ROLE_ID)

					->where('u.status', 1)

					->where('u.trashed', 0)

					->join('users u', 'u.id=ucct.user_id', 'INNER')

					->groupBy('ucct.user_id')

					->orderBy('u.surname', 'ASC')

					->get('users_clinical_centers_to ucct', null, ['u.id', 'u.name', 'u.surname']);



				if (is_array($requestersResult) && !empty($requestersResult)) {

					foreach($requestersResult as $item) {

						$name = ucwords(strtolower($item['name']));

						$surname = ucwords(strtolower($item['surname']));



						$this->view->requesterSelectList[$item['id']] = $this->helper->setDottedFullname($name, $surname, false);

					}

				}



				//$this->view->debug = $this->view->requesterSelectList;

			}



			$this->view->ccStringList = '';

			$userCcList = [];

			$ccStringList = [];



			$this->view->referrals = [];

			$this->view->specialties = [];

			$searchData = $this->getPost('searchData', []);

			parse_str($searchData, $this->view->strOutput);



			//Default value

			$obscure = false;



			//Select the Clinical Center ID to anonymize

			$anonymCenters = [];

			foreach($userClinicalCenters as $uCC) {

				if (isset($uCC['anonymize']) && (int)$uCC['anonymize'] > 0) {

					$anonymCenters[$uCC['id']] = true;

				}

			}

			$this->view->anonymCenters = $anonymCenters;



			//Show user's requests

			if ($this->view->scope == 'my') {



				$this->actionTitle = _('My Requests');



				if ($this->user->is(APPLICANT_ROLE_ID)) {

					$this->db->where('user_id', $this->user->getUserId());

				}



			} else if ($this->view->scope == 'center' || $this->view->scope == 'moderations') {



				if ($this->view->scope == 'moderations' && $this->user->is(MODERATOR_ROLE_ID)) {

					$userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID);

				}



				$this->actionTitle = _('Center(s) Requests');

				if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {

					foreach($userClinicalCenters as $ccItem) {

						$userCcList[] = $ccItem['id'];

						$ccStringList[] = $ccItem['description'];

					}

				}



				$this->db->where('r.request_visibility', 'all');

				$this->db->where('r.group_id', $this->userGroupId);

				

				if ($this->user->is([MODERATOR_ROLE_ID])) {

					$this->db->where("r.request_status IN('draft', 'pending', 'opened', 'referted', 'reopened', '! referted')");

				} else {

					$this->db->where("r.request_status IN('pending', 'opened', 'referted', 'reopened', '! referted')");

				}



				if (!empty($userCcList)) {

					$userCcListString = implode(',', $userCcList);

					$this->db->where("cc.id IN($userCcListString)");



					$this->view->ccStringList = implode(', ', $ccStringList);

				} else {

					$this->db->where('cc.id', -1); //Force no results

					$this->view->userHasClinicalCenters = false;

				}



			} else if ($this->view->scope == 'reports') {

					$this->actionTitle = _('My Requests');



					if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {

						foreach($userClinicalCenters as $ccItem) {

							$ccStringList[] = $ccItem['description'];

						}

					}



					$this->view->ccStringList = implode(', ', $ccStringList);



					$this->db->where('r.request_visibility', 'all');

					$this->db->where('r.group_id', $this->userGroupId);

					$this->db->where("r.request_status IN('opened', 'referted', 'reopened', '! referted')");

					$this->db->where('rere.user_id', $this->user->getUserId());

					$this->db->join('requests_recipients rere', 'rere.request_id=r.id', 'INNER');



			} else if ($this->view->scope == 'center-guest') {

				$this->actionTitle = _('Requests');



				if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {

					foreach($userClinicalCenters as $ccItem) {

						$userCcList[] = $ccItem['id'];

						$ccStringList[] = $ccItem['description'];

					}

				}



				$this->db->where('r.request_visibility', 'all');

				$this->db->where('r.group_id', $this->userGroupId);

				$this->db->where("r.request_status IN('opened', 'referted', 'reopened', '! referted')");



				if (!empty($userCcList)) {

					$userCcListString = implode(',', $userCcList);

					$this->db->where("cc.id IN($userCcListString)");



					$this->view->ccStringList = implode(', ', $ccStringList);

				} else {

					$this->db->where('cc.id', -1); //Force no results

					$this->view->userHasClinicalCenters = false;

				}

			}



			//if (!empty($this->view->strOutput)) {



				/*$searchRequester = isset($this->view->strOutput['search']['requester']) ? (int)$this->view->strOutput['search']['requester'] : 0;

				$searchStatus = isset($this->view->strOutput['search']['status']) ? $this->view->strOutput['search']['status'] : '';

				$seachMs = isset($this->view->strOutput['search']['ms']) ? (int)$this->view->strOutput['search']['ms'] : 0;

				$seachCc = isset($this->view->strOutput['search']['cc']) ? (int)$this->view->strOutput['search']['cc'] : 0;*/



				// SET INFO MAX REQUESTS

				$this->view->getTotRequests =  $this->db->totalCount;

				$this->view->getMaxRequests = $this->db->MaxAddRequests;

				

				$has_pdf = -1;

				if (isset($this->view->strOutput['search']['has_pdf'])) {

					$this->session->deleteSession('reqHasPdf');

					$has_pdf = $this->view->strOutput['search']['has_pdf'];

					$this->session->refreshSession('reqHasPdf', (int)$has_pdf);

				} else {

					if ($this->session->getSessionValue('reqHasPdf') !== false) {

						$has_pdf = $this->session->getSessionValue('reqHasPdf');

					}

				}				

				if ($has_pdf > -1) {

					if ($has_pdf == 0) {

						$this->db->having('total_reports', 0);

					} else {

						$this->db->having('total_reports', 0, '>');

					}

				} else {

					$this->session->deleteSession('reqHasPdf');

				}



				$searchId = 0;

				if (isset($this->view->strOutput['search']['id'])) {

					$this->session->deleteSession('reqSearStorId');

					$searchId = (int)$this->view->strOutput['search']['id'];

					$this->session->refreshSession('reqSearStorId', $searchId);

				} else {

					if ($this->session->getSessionValue('reqSearStorId') !== false) {

						$searchId = $this->session->getSessionValue('reqSearStorId');

					}

				}

				if ($searchId > 0) {

					$this->db->where('r.id', $searchId);

				} else {

					$this->session->deleteSession('reqSearStorId');

				}



				$searchRequester = 0;

				if (isset($this->view->strOutput['search']['requester'])) {

					$this->session->deleteSession('reqSearStorUid');

					$searchRequester = (int)$this->view->strOutput['search']['requester'];

					$this->session->refreshSession('reqSearStorUid', $searchRequester);

				} else {

					if ($this->session->getSessionValue('reqSearStorUid') !== false) {

						$searchRequester = $this->session->getSessionValue('reqSearStorUid');

					}

				}

				if ($searchRequester > 0) {

					$this->db->where('r.user_id', $searchRequester);

				} else {

					$this->session->deleteSession('reqSearStorUid');

				}





//////////////

				//

				$searchPatient = '';

				if (isset($this->view->strOutput['search']['patient'])) {

					$this->session->deleteSession('reqSearPatient');

					$searchPatient = (string)$this->view->strOutput['search']['patient'];

					$this->session->refreshSession('reqSearPatient', $searchPatient);

				} else {

					if ($this->session->getSessionValue('reqSearPatient') !== false) {

						$searchPatient = $this->session->getSessionValue('reqSearPatient');

					}

				}



				if ($searchPatient != '') {



					$regexp = '';

					$arr_lists = explode(' ', $searchPatient);



					foreach($arr_lists as $key=>$value){

						if($key == 0){

								$regexp .= '"'.$value.'"';

						}else{

							$regexp .= '|"'.$value.'"';

						}

					}



					// $this->db->where('CONCAT(rr.surname," ",rr.name) REGEXP '.$regexp.'');



					if (is_array($arr_lists) && !empty($arr_lists)) {

						foreach($arr_lists as $list_value) {

							$this->db->where('CONCAT(rr.surname," ",rr.name)', '%'.$list_value.'%', 'LIKE');

						}

					} else {

						$this->db->where('CONCAT(rr.surname," ",rr.name)', '%'.$arr_lists.'%', 'LIKE');

					}



				} else {

					$this->session->deleteSession('reqSearPatient');

				}



//////////////





				$searchStatus = '';

				if (isset($this->view->strOutput['search']['status'])) {

					$this->session->deleteSession('reqSearStorStat');

					$searchStatus = $this->view->strOutput['search']['status'];

					$this->session->refreshSession('reqSearStorStat', $searchStatus);

				} else {

					if ($this->session->getSessionValue('reqSearStorStat') !== false) {

						$searchStatus = $this->session->getSessionValue('reqSearStorStat');

					}

				}

				if ($searchStatus != '') {

					$this->db->where('r.request_status', $searchStatus);

				} else {

					$this->session->deleteSession('reqSearStorStat');

				}





				$seachCc = 0;

				if (isset($this->view->strOutput['search']['cc'])) {

					$this->session->deleteSession('reqSearStorCc');

					$seachCc = (int)$this->view->strOutput['search']['cc'];

					$this->session->refreshSession('reqSearStorCc', $seachCc);

				} else {

					if ($this->session->getSessionValue('reqSearStorCc') !== false) {

						$seachCc = $this->session->getSessionValue('reqSearStorCc');

					}

				}

				if ($seachCc > 0) {

					$this->db->where('r.center_id', $seachCc);

				} else {

					$this->session->deleteSession('reqSearStorCc');

				}



				$seachMs = 0;

				if (isset($this->view->strOutput['search']['ms'])) {

					$this->session->deleteSession('reqSearStorMs');

					$seachMs = (int)$this->view->strOutput['search']['ms'];

					$this->session->refreshSession('reqSearStorMs', $seachMs);

				} else {

					if ($this->session->getSessionValue('reqSearStorMs') !== false) {

						$seachMs = $this->session->getSessionValue('reqSearStorMs');

					}

				}

				if ($seachMs > 0) {

					$this->db->join('requests_medical_specialties_to rmst', 'rmst.request_id=r.id', 'INNER')->where('rmst.specialty_id', $seachMs);

				} else {

					$this->session->deleteSession('reqSearStorMs');

				}



			//}



			$this->db->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')

			->join('users u', 'u.id=r.user_id', 'INNER')

			->join('requests_registry rr', 'rr.request_id=r.id', 'INNER')

			->orderBy($this->view->orderField, $this->view->orderDir);



			if ($this->view->orderField == 'request_status_number') {

				$this->db->orderBy('created_at', 'desc');

			}



			$requests = $this->db->paginate('requests r', $this->view->currentPage, ['r.*', 'u.name applicant_name', 'u.surname applicant_surname', 'rr.id patient_id', 'rr.name patient_name', 'rr.surname patient_surname', '(SELECT TIMESTAMPDIFF(YEAR, rr.birthdate, CURDATE())) patient_age_years', '(SELECT TIMESTAMPDIFF(MONTH, rr.birthdate, CURDATE())) patient_age_months', '(SELECT TIMESTAMPDIFF(DAY, rr.birthdate, CURDATE())) patient_age_days', 'rr.gender patient_gender', 'cc.description center_name', "(SELECT COUNT(*) FROM requests_attachments ra WHERE ra.request_id=r.id) AS total_attach", "(SELECT COUNT(*) FROM sportellocura_log sptc WHERE sptc.request_id=r.id) AS total_reports",



			//Remove (?)

			"(SELECT GROUP_CONCAT(ums.description SEPARATOR ', ') AS specialty_list FROM requests_medical_specialties_to rmst JOIN users_medical_specialties ums ON ums.id=rmst.specialty_id WHERE rmst.id=r.id) AS med_specialties",

			

			"(SELECT COUNT(*) FROM sportellocura sca WHERE sca.request_id=r.id) sportello_total",

			"(SELECT COUNT(*) FROM requests_comments rc WHERE rc.request_id=r.id AND rc.user_id=".$this->view->robot_id.") total_auto_tlc"]);



			$this->view->queryDebug = $this->db->getLastQuery();



			// SET INFO MAX REQUESTS

			$this->view->getTotRequests =  $this->db->totalRequests;

			$this->view->getMaxRequests = $this->db->MaxAddRequests;



			$this->setPagination($this->db, $this->db->totalCount, $this->view->currentPage, $this->view->baseUri.'/'.$this->view->orderField.'/'.$this->view->orderDir);



			if (is_array($requests)) {

				foreach($requests as $index => $request) {



					//Check whether obfuscate the Patient name or don't

					if ($this->view->scope != 'my') {



						//Check whether the request has been market ad anonymous

						if ((int)$requests[$index]['request_anonymous'] == 0) {



							//If the request isn't anonymous, check the Clinical Center

							if (isset($anonymCenters[$request['center_id']])) { //The Center is anonymous by default

								$requests[$index]['request_anonymous'] = 1; //Make this request anonymous

							}

						}



					}



					//Overwrite the anonymous value if the current user is the request author

					if ($request['user_id'] == $this->user->getUserId()) {

						$requests[$index]['request_anonymous'] = 0;

					}



					//If there are no Clinical Center for the current user, foce anonymous anyway

					if (empty($userClinicalCenters)) {

						$requests[$index]['request_anonymous'] = 0;

					}



					//Get the Referrals for each Requests

					$this->view->referrals[$request['id']] = $this->db

						->where('rc.request_id', $request['id'])

						->where('(SELECT COUNT(*) FROM users_roles_to urt WHERE urt.user_id=rc.user_id AND role_id='.REFERRER_ROLE_ID.')', 0, '>')

						->join('users u', 'u.id=rc.user_id', 'INNER')

						->orderBy('u.surname', 'asc')

						->groupBy('rc.user_id')

						->get('requests_comments rc', null, [

						'user_id',

						'u.name user_name',

						'u.surname user_surname',

						"(SELECT GROUP_CONCAT(umst.specialty_id SEPARATOR '|') FROM users_medical_specialties_to umst WHERE umst.user_id=rc.user_id) specialty_ids"

					]);



					//Get the Medical Specialties for each Requests

					$this->view->specialties[$request['id']] = $this->db

						->where('rmst.request_id', $request['id'])

						->join('users_medical_specialties ums', 'ums.id=rmst.specialty_id', 'INNER')

						->orderBy('ums.description', 'asc')

						->get('requests_medical_specialties_to rmst', null, ['rmst.specialty_id specialty_id', 'ums.description specialty_name', 'NULL AS referrals']);



					//Combine Referrals and Specialties

					foreach($this->view->specialties as $request_id => $specialties) {

						foreach($specialties as $specialty_index => $specialty) {

							foreach($this->view->referrals[$request_id] as $referral) {



								//Check if referral has this specialty id

								if (in_array($specialty['specialty_id'], explode('|', $referral['specialty_ids']))) {

									$this->view->specialties[$request_id][$specialty_index]['referrals'][$referral['user_id']] = $this->helper->setDottedFullname(ucwords($referral['user_name']), ucwords($referral['user_surname']), false);

								}

							}

						}

					}



					//Add new item in the Request list

					$requests[$index]['specialties'] = isset($this->view->specialties[$request['id']]) ? $this->view->specialties[$request['id']] : [];

				}

			}



			$this->view->ucc = $userClinicalCenters;

			$this->view->actionTitle = rawurlencode($this->actionTitle); //Pass the action title to "New Request" button

			$this->view->parentBaseUri = rawurlencode($this->view->baseUri); //Pass the base uri to "New Request" button

			$this->view->requests = $requests;

			$this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];



			return $this->setJsonView('index');

		}



		//Request editing page (View)

		public function requestEdit() {

			/*if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID])) {

				return $this->redirect('login', 'permissionDenied');

			}*/

			

			$this->view->surveyStructure['wizard-neuro-epilepsy'] = json_decode($this->db->where('tag', 'wizard-neuro-epilepsy')->where('lang', $this->user->getLanguage())->getValue('requests_wizard_survey', 'json_structure'), true);

			

			$this->view->tmpSurvey = [

				['group'=>'', 'list' => [

						[

							'question'=>"Qualcuno nella famiglia soffre di epilessia?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],

						

						[

							"type"=>"textarea", 

							"question"=>"Se sì, specifichi:",

							"rows"=>3

						],

						[

							'question'=>"Gravidanza e parto regolari?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],



						[

							"type"=>"textarea", 

							"question"=>"Se no, specifichi:",

							"rows"=>3,

						],

						[

							'question'=>"Sviluppo psicomotorio normale?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],

						[

							'question'=>"Malattie cerebrali note?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],

						[

							"type"=>"textarea", 

							"question"=>"Se si, specifichi se malaria, tumore o altro",

							"rows"=>3,

						],

						[

							'question'=>"Patologie non neurologiche da segnalare?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],

						[

							"type"=>"textarea", 

							"question"=>"Se si, specifichi:",

							"rows"=>3,

						],

						[

							'question'=>"Il paziente abusa o ha abusato di alcol o droghe?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],

						[

							"type"=>"textarea", 

							"question"=>"Se si, specifichi:",

							"rows"=>3,

						],

						[

							"type"=>"textarea", 

							"question"=>"Indicare mese e anno della prima crisi epilettica:",

							"rows"=>3,

						],

						[

							'question'=>"Che tipo di crisi presenta il paziente?", 

							'list'=>true,

							'answers'=>[

								['label'=>"Crisi convulsiva tonico-clonica",  'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>" Assenza",  'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Crisi parziale", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Crisi parziale con secondaria generalizzazione", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Altro", 'values'=>[['label'=>'Sì'], ['label'=>'No']]]

							]

						],

						[

							"type"=>"textarea", 

							"question"=>"Altre informazioni sulle eventuali crisi presentate dal paziente:",

							"rows"=>3,

						],

						[

							'question'=>"Il paziente si accorge che la crisi sta per arrivare?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],

						[

							"type"=>"textarea", 

							"question"=>"Se si, descriva come:",

							"rows"=>3,

						],

						[

							'question'=>"Dopo la crisi presenta deficit di parola / movimento / confusione / cefalea / altro?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],

						[

							"type"=>"textarea", 

							"question"=>"Se si, specifichi:",

							"rows"=>3,

						],

						[

							"type"=>"textarea", 

							"question"=>"Qual è la frequenza delle crisi prima di iniziare la terapia?",

							"rows"=>3,

						],

						[

							"type"=>"textarea", 

							"question"=>"Quante crisi negli ultimi 3 mesi?",

							"rows"=>3,

						],

						[

							"type"=>"textarea", 

							"question"=>"Quante crisi nell'ultimo mese?",

							"rows"=>3,

						],

						[

							"type"=>"textarea", 

							"question"=>"Quando ha avuto l'ultima crisi?",

							"rows"=>3,

						],

						[

							'question'=>"Terapie pregresse", 

							'list'=>true,

							'answers'=>[

								['label'=>"Valproato",  'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Levetiracetam",  'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Fenobarbital", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Carbamazepina", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Lamotrigina", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Benzodiazepine", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Altro", 'values'=>[['label'=>'Sì'], ['label'=>'No']]]

							]

						],

						[

							"type"=>"textarea", 

							"question"=>"Se altro, indichi cosa:",

							"rows"=>3,

						],

						[

							"type"=>"textarea", 

							"question"=>"Terapia attuale:",

							"rows"=>3,

						],

						[

							'question'=>"Esame Obiettivo Neurologico normale?",

							'list'=>false,

							'answers'=>[

								['label'=>NULL, 'values'=>[['label'=>'Si'], ['label'=>'No']]]

							]

						],

						[

							'question'=>"Se no, alterazione di:", 

							'list'=>true,

							'answers'=>[

								['label'=>"Forza",  'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Sensibilità",  'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Marcia", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Equilibrio", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Salivazione", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Parola", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Vista", 'values'=>[['label'=>'Sì'], ['label'=>'No']]],

								['label'=>"Altro", 'values'=>[['label'=>'Sì'], ['label'=>'No']]]

							]

						],

						[

							"type"=>"textarea", 

							"question"=>"Se altro, indichi cosa:",

							"rows"=>3,

						]

					]

				]

			];

			

			$handleRequest = new HandleRequest();



			$requestID = $this->getPost('requestID', 1);

			$this->view->parentActionTitle = $this->getPost('parentTitle', _('Requests'));

			$this->view->parentScope = $this->getPost('parentScope', 'my');

			$this->view->viewType = $this->getPost('viewType', 'view');

			$this->view->parentBaseUri = $this->getPost('parentBaseUri', '');

			$this->view->currentPage = $this->getPost('pageNumb', 1);

			$this->view->orderField = $this->getPost('orderField', 'created_at');

			$this->view->orderDir = $this->getPost('orderDir', 'desc');

			$this->view->userLang = $this->user->getUserLang();



			//Default values

			$this->view->userCanView = true;

			$this->view->requestData = [];

			$this->view->companies = [];

			$this->view->symptoms = [];

			$this->view->ICD10 = [];

			$this->view->medicalSpecialties = [];

			$this->view->requestMedicalSpecialties = [];

			$this->view->forwardMedicalSpecialties = [];

			$this->view->requestMedicalSpecialtiesIdList = [];

			$this->view->attachments = [];

			$this->view->comments = [];

			$this->view->ccReferral = []; //Clinical Centers referrals (recipients)

			$this->view->languages = $this->locale->getSupportedLanguages();

			$this->view->icd10 = [];

			$this->view->dermaPositions = [];

			$this->view->dermaPositionLabels = ['single'=>_('Single'), 'multiple-localized'=>_('Multiple localized'), 'multiple-spread'=>_('Multiple spread'), 'clusted'=>_('Cluster'), 'metameric'=>_('Metameric'), 'linear'=>_('Linear'), 'acral'=>_('Acral'), 'symmetrical'=>_('Symmetrical')];

			$this->view->otoImages = [];

			$this->view->otoPositionLabels = ['oto_myringitis'=>_('Bullous myringitis'),

			'oto_polip'=>_('Polyp of the EAC'),

			'oto_atelectasis'=>_('Tympanic membrane atelectasis'),

			'oto_perforation'=>_('Tympanic membrane perforation / non-cholesteatomatous otitis media'),

			'oto_chole'=>_('Cholesteatomatous otitis media'),

			'oto_tympanoscler'=>_('Tympanosclerosis'),

			'oto_tyjugular'=>_('Tympano-jugular paraganglioma'),

			'oto_cholesterol'=>_('Cholesterol granuloma')];

			$this->view->statuses = [];

			$this->requestOrigin = '';

			$this->view->dreamCode = '';

			$this->view->dreamData = [];

			$this->view->dreamCompleteData = '';

			$this->view->requestDreamPDF = []; //Information for Dream PDF

			$this->view->provinceList = [];

			$this->view->cgProvince = '';

			$this->view->cgCity = '';

			$this->view->dreamItalyEndPoint = $this->config['settings']['api']['endpoint'];

			$this->view->dreamItalyApiKey = $this->config['settings']['api']['key'];

			

			$this->view->sportelloCuraEndPoint = $this->config['settings']['sportellocura']['api']['key'];

			$this->view->sportelloCuraApiKey = $this->config['settings']['sportellocura']['api']['endpoint'];

			$this->view->survey = []; //Sportello Cura data

			

			$provinces = $this->db->orderBy('name', 'ASC')->get('italian_provinces');

			if (is_array($provinces) && !empty($provinces)) {

				foreach($provinces as $item) {

					$this->view->provinceList[$item['id']] = $item['name'];

				}

			}

			

			//PDF sending log

			$this->view->pdfLog = $this->db

				->where('sl.request_id', $requestID)

				->join('requests_messages_queue rmq', 'rmq.mail_id=sl.mail_code', 'LEFT')

				->orderBy('sl.created_at', 'ASC')

				->get('sportellocura_log sl', NULL, ['sl.created_at queued_date', 'rmq.request_id', 'rmq.mail_id', 'rmq.delay_at']);

				

			//Default values

			$userIsAuthor = false; //The logged user id the author of this Request

			$userIsModerator = false; //The logged user is a moderator of this Clinical Center

			$this->view->userIsAuthor = $userIsAuthor;

			$this->view->userIsModerator = $userIsModerator;

			$userIsReferrer = false; //The logged user is a referral of this Request

			$this->view->userIsReferrer = $userIsReferrer;



			$this->view->icd10Categories = $handleRequest->getICD10Categories($this->user->getUserLang());

			$this->view->wizards = [];



			$advancedFields = $this->db->where('id', $this->user->getUserId())->getOne('users', 'advanced_request');

			$this->view->advancedFields = isset($advancedFields['advanced_request']) && (int)$advancedFields['advanced_request'] == 1 ? true : false;

			

			//Viewer

			$this->view->isSimpleViewer = false;

			//$viewer = $this->db->where('id', $this->user->getUserId())->getOne('users', 'simple_viewer');

			$viewer = 0;

			if (isset($viewer['simple_viewer']) && (int)$viewer['simple_viewer'] == 1) {

				$this->view->isSimpleViewer = true;

			}



			//Select the user's language by default

			foreach($this->view->languages as $index => $language) {

				if ($language['lang_code'] == $this->user->getUserLang()) {

					$this->view->languages[$index]['selected'] = true;

				} else {

					$this->view->languages[$index]['selected'] = false;

				}

			}



			if ($this->user->is(APPLICANT_ROLE_ID)) {

				$this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), APPLICANT_ROLE_ID); //In mainController()

			} else if ($this->user->is(REFERRER_ROLE_ID)) {

				$this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), REFERRER_ROLE_ID);

			} else if ($this->user->is(MODERATOR_ROLE_ID)) {

				$this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID); //In mainController()

			}

			

			$this->view->requestId = $requestID;

			//$this->view->medicalSpecialties = $this->db->orderBy('description', 'asc')->get('users_medical_specialties');

			$this->view->ccReferral = $this->db

				->where('ucct.role_id', REFERRER_ROLE_ID)

				->join('clinical_centers cc', 'cc.id=ucct.center_id', 'INNER')

				->groupBy('cc.id')

				->orderBy('cc.description', 'asc')

				->get('users_clinical_centers_to ucct', null, ['cc.id id', 'cc.description description']);



			$this->view->referralList = $this->db

				->where('role_id', REFERRER_ROLE_ID)

				->where('u.status', 1)

				->join('users u', 'u.id=urt.user_id', 'INNER')

				->orderBy('u.surname', 'asc')

				->get('users_roles_to urt', null, [

				'u.id user_id',

				'u.name user_name',

				'u.surname user_surname',

				"(SELECT GROUP_CONCAT(ums.description SEPARATOR ', ') FROM users_medical_specialties_to umst JOIN users_medical_specialties ums ON ums.id=umst.specialty_id WHERE umst.user_id=u.id ORDER BY ums.description) medspec_list"

				]);



			if ($this->view->viewType == 'view') {

				//Get all Medical Specialties (in the list for the comment form)

				$this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId(0, $this->userGroupId);

			} else {

				//New Request: if there is just one Clinical Center, list its the Medical Specialties (else they are loaded by Ajax)

				if (count($this->view->userClinicalCenters) == 1) {

					$currentCenterId = array_values($this->view->userClinicalCenters)[0]['id'];

					$this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId($currentCenterId, $this->userGroupId);

				}

			}



			if ($requestID == 0) {

				$this->actionTitle = _('Request : New');

				$this->view->requestUniqueCode = strtoupper(uniqid());

				$this->view->requestData = []; //Default: empty array



				$this->view->exams = $handleRequest->getExams();



				$handleRequest->setActivityLog($this->user->getUserId(), 'REQ_NEW', ['userId'=>$this->user->getUserId()]);



			} else {

				$this->actionTitle = _('Request : Edit');





				if ($this->view->viewType == 'view') {

					$this->actionTitle = vsprintf(_('Request #%s'), [$requestID]);

					$this->actionTitlePDF = "#".$requestID;

					$handleRequest->setActivityLog($this->user->getUserId(), 'REQ_VIEW', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);





				}



				//TO DO: check whether the current user is authorized to access this request (i.e. changing the ID in the addess bar)



				//$this->view->testData = $handleRequest->forwardRequest($requestID);



				$requestData = $this->db

					->where('r.id', $requestID)

					->join('users u', 'u.id=r.user_id', 'INNER')

					->join('requests_registry rr', 'rr.request_id=r.id', 'INNER')

					->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')

					->join('continents cnt', 'cnt.code=cc.continent_code', 'INNER')

					->join('countries ctr', 'ctr.country_iso2_code=cc.country_code', 'INNER')

					->getOne('requests r', "r.*, cc.description center_description, cc.address center_address, cc.lat, cc.lng, cnt.name center_continent, ctr.country_name center_country, cc.notes center_notes, rr.clinical_remarks, rr.medical_history, rr.name patient_name, rr.surname patient_surname, rr.birthdate, rr.gender, (SELECT TIMESTAMPDIFF(YEAR, rr.birthdate, CURDATE())) age_years, (SELECT TIMESTAMPDIFF(MONTH, rr.birthdate, CURDATE())) age_months, (SELECT TIMESTAMPDIFF(DAY, rr.birthdate, CURDATE())) age_days, rr.min_arterial_pressure, rr.max_arterial_pressure, rr.heart_rate, rr.saturation, u.name sender_name, u.surname sender_surname, u.updated_at user_updated_at");

				

				//Sporello Cura

				$sportellocura = $this->db->where('request_id', $requestID)->getOne('sportellocura');

				if (isset($sportellocura['survey_id'])) {

					$survey_record = json_decode($sportellocura['survey_data'], true);

					if (isset($survey_record['json_answers'])) {

						$survey_record['data'] = json_decode($survey_record['json_answers'], true);

					}

					$this->view->survey = $survey_record;

				}



				$companies = $this->db->getOne('companies');



				if (!is_array($requestData)) {

					return $this->setJsonView('requestError');

				}

				

				//Check whether the moderator can access this request or can't

				if ($this->user->is(MODERATOR_ROLE_ID)) {

					if (!isset($this->view->userClinicalCenters[$requestData['center_id']])) {

						return $this->setJsonView('requestError');

					}

				}



				//Get Dream code

				$dreamResult = $this->db->where('request_id', $requestID)->getOne('requests_dream_data', 'dream_code, dream_hash');



				if (isset($dreamResult['dream_code']) && trim($dreamResult['dream_code']) != '') {

					$this->view->dreamCode = $dreamResult['dream_code'];

					$this->view->dreamData = htmlspecialchars($dreamResult['dream_hash']);

				}



				$userIsAuthor = $requestData['user_id'] == $this->user->getUserId() ? true : false;

				$this->view->userIsAuthor = $userIsAuthor;

				

				$this->view->hasMoreDetails = trim($requestData['cgnamesurname']) != '' || trim($requestData['cgrole']) != '' || trim($requestData['cgemail']) != '' || trim($requestData['cgphone']) != '';

				

				//Get Caregiver's Province and City

				

				if ((int)$requestData['cgprovince'] > 0) {

					$cg_province = $this->db->where('id', $requestData['cgprovince'])->getOne('italian_provinces');

					

					$this->view->cgProvince = isset($cg_province['name']) ? $cg_province['name'] : '';

				}

				

				if ((int)$requestData['cgcity'] > 0) {

					$cg_city = $this->db->where('id', $requestData['cgcity'])->getOne('italian_cities');

					

					$this->view->cgCity = isset($cg_city['name']) ? $cg_city['name'] : '';

				}



				$userIsModerator = $handleRequest->isUserModerator($requestData['center_id'], $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID), $this->user->getUserId());

				$this->view->userIsModerator = $userIsModerator;



				$userIsReferrer = $handleRequest->isUserReferrer($requestID, $this->user->getUserId());

				$this->view->userIsReferrer = $userIsReferrer;



				//Get the Medical Specialties for the saved Clinical Center

				$currentCenterId = $requestData['center_id'];

				$this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId($currentCenterId, $this->userGroupId);



				$ccInfo = $this->db->where('id', $currentCenterId)->getOne('clinical_centers');

				$isCcAnonymous = isset($ccInfo['anonymize']) && (int)$ccInfo['anonymize'] == 1 ? true : false;



				if ($isCcAnonymous) {

					$requestData['request_anonymous'] = 1;

				}



				//Overwrite the previouse value

				if ($userIsAuthor) {

					$isCcAnonymous = false;

				}



				$this->view->requestData = $requestData;

				$this->view->companies = $companies;



				//TOOD: check whether current user can access this request

				//O. Is the right group?

				//1. Is the Author?

				//2. Is a Moderator in this Clinical Center?

				//3. Is a Referral of this Request?

				//4. Is an Admininstrator?



				$this->view->requestUniqueCode = $requestData['unique_code'];

				//$this->actionTitle .= ' ('.ucfirst($requestData['request_origin']).')';

				$this->requestOrigin = $requestData['request_origin'];

				

				//Epilepsy Wizard

				$this->view->hasEpilepsyWizard = false;

				$this->view->epilepsyStructure = [];

				if (isset($requestData['unique_code'])) {

					$epilepsy_db_data = $this->db->where('request_code', $requestData['unique_code'])->getValue('requests_wizard_survey_answers', 'answer_structure');

					$epilepsy_structure = json_decode($epilepsy_db_data, true);

					

					if (!is_null($epilepsy_structure)) {

						$this->view->hasEpilepsyWizard = true;

						$this->view->surveyStructure['wizard-neuro-epilepsy'] = $epilepsy_structure;

					}

				}



				//Symptons (old ICD10)

				$this->view->symptoms = $this->db

					->where('rst.request_id', $requestID)

					->where('rsl.language_code', $this->user->getUserLang())

					->join('requests_symptoms_labels rsl', 'rsl.symptom_id=rst.symptom_id', 'INNER')

					->orderBy('rsl.symptom_label', 'asc')

					->get('requests_symptoms_to rst', null, ['rsl.symptom_label']);



				//ICD10 (new)

				$this->view->ICD10 = $this->db

					->where('rst.request_id', $requestID)

					->where('idl.lang_code', $this->user->getUserLang())

					->join('icd10_desease_labels idl', 'idl.desease_id=rst.symptom_id', 'INNER')

					->orderBy('idl.description', 'asc')

					->get('requests_symptoms_to rst', null, ['idl.description symptom_label']);



				//Overwrite the symptoms with the new ICD10

				if (!empty($this->view->ICD10)) {

					$this->view->symptoms = $this->view->ICD10;

				}



				//Clinical Centers

				foreach($this->view->userClinicalCenters as $centerId => $centerItem) {

					if ($centerItem['id'] == $requestData['center_id']) {

						$this->view->userClinicalCenters[$centerId]['selected'] = true;

					} else {

						$this->view->userClinicalCenters[$centerId]['selected'] = false;

					}

				}



				if (is_array($this->view->referralList)) {

					$requestRecipients = $this->db

						->where('request_id', $requestID)

						->get('requests_recipients');



					$this->view->recipients = $requestRecipients;



					if (is_array($requestRecipients)) {

						foreach($this->view->referralList as $index => $referral) {

							$this->view->referralList[$index]['selected'] = false;

							foreach($requestRecipients as $recipient) {

								if ($referral['user_id'] == $recipient['user_id']) {

									$this->view->referralList[$index]['selected'] = true;

								}

							}

						}

					}

				}



				$requestMedSpec = $this->db

					->where('request_id', $requestID)

					->get('requests_medical_specialties_to');



				//Medical specialties of the request

				$idList = [];

				$requestMedicalSpecialties = $this->db

					->where('rmst.request_id', $requestID)

					->join('users_medical_specialties ums', 'ums.id=rmst.specialty_id', 'INNER')

					->get('requests_medical_specialties_to rmst', null, ['ums.id', 'ums.description']);

				if (is_array($requestMedicalSpecialties)) {

					foreach($requestMedicalSpecialties as $item) {

						$this->view->requestMedicalSpecialties[$item['id']]['id'] = $item['id'];

						$this->view->requestMedicalSpecialties[$item['id']]['description'] = _($item['description']);

						$idList[] = $item['id'];

					}



					$this->view->requestMedicalSpecialtiesIdList = $idList;

				}



				//All possible Medical specialties

				foreach($this->view->medicalSpecialties as $index => $medSpecList) {

					$this->view->medicalSpecialties[$index]['selected'] = false;

					foreach($requestMedSpec as $reqMedSpecItem) {

						if ($reqMedSpecItem['specialty_id'] == $medSpecList['id']) {

							$this->view->medicalSpecialties[$index]['selected'] = true;

						}

					}



					//Request forward: list with mmedical specialties without the request medical specialties

					if (!isset($this->view->requestMedicalSpecialties[$medSpecList['id']])) {

						$this->view->forwardMedicalSpecialties[$medSpecList['id']]['id'] = $medSpecList['id'];

						$this->view->forwardMedicalSpecialties[$medSpecList['id']]['description'] = $medSpecList['description'];

					}



				}





				$requestLangs = $this->db

					->where('request_id', $requestID)

					->get('requests_languages_to');



				//If there are saved languages change the default value

				if (is_array($requestLangs) && !empty($requestLangs)) {

					foreach($this->view->languages as $index => $language) {

						$this->view->languages[$index]['selected'] = false;

						foreach($requestLangs as $reqLangItem) {

							if ($reqLangItem['language_code'] == $language['lang_code']) {

								$this->view->languages[$index]['selected'] = true;

							}

						}

					}

				}



				$requestCenters = $this->db

					->where('request_id', $requestID)

					->get('request_clinical_centers_to');



				foreach($this->view->ccReferral as $centerId => $referralCenter) {

					$this->view->ccReferral[$centerId]['selected'] = false;

					foreach($requestCenters as $centerItem) {

						if ($centerItem['center_id'] == $referralCenter['id']) {

							$this->view->ccReferral[$centerId]['selected'] = true;

						}

					}

				}



				$this->view->statuses = $this->db

					->where('rs.code', '! referted', '<>')

					->where('rs.code', 'draft', '<>')

					->where('rs.code', 'pending', '<>')

					->where('rs.code', 'opened', '<>')

					->orderBy('rs.default_label', 'asc')

					->get('requests_statuses rs');



				$this->view->attachments = $handleRequest->getAttachmentsByRequestId($requestID);



				//Group attachments by date

				$this->view->groupedAttachments = [];

				if (is_array($this->view->attachments) && !empty($this->view->attachments)) {

					foreach($this->view->attachments as $attachment) {

						//$ext = $this->helper->getExtension($attachment['file_name']);

						$attachment['previewType'] = $this->helper->getPreviewType($attachment['file_name']);

						$this->view->groupedAttachments[date('Y-m-d 00:00:00', strtotime($attachment['created_at']))][] = $attachment;

					}



					if (!empty($this->view->groupedAttachments)) {

						foreach($this->view->groupedAttachments as $ext => $attachList) {

							sort($attachList);

							$this->view->groupedAttachments[$ext] = $attachList;

						}

					}

				}



				//ICD-10

				$this->view->icd10 = $handleRequest->getECD10ListByRequestId($requestID, $this->user->getUserLang());



				//Wizards

				$this->view->wizardTitles = ['cardio'=>_('Wizard Cardio'), 'derma'=>_('Wizard Derma'), 'generic'=>_('Wizard Physical Examination'), 'oto'=>_('Wizard Ear')];

				$this->view->wizards = $handleRequest->getWizardsByRequestId($requestID);



				//Wizard Derma positions

				$this->view->dermaPositions = $handleRequest->getWizardsDermaPositions($requestID);



				//Wizard Ear images

				$this->view->otoImages = $handleRequest->getWizardsEarDeseases($requestID);;



				//Get all exams for the dialogs

				$this->view->exams = $handleRequest->getExams($this->view->wizards);



			}



			$pathParentUri = $this->view->parentBaseUri.'/'.$this->view->orderField.'/'.$this->view->orderDir.'/'.$this->view->currentPage;



			if ($this->view->parentBaseUri != 'hashtag') {

				$this->breadcrumbs = [['hash'=>$pathParentUri, 'label'=>$this->view->parentActionTitle], ['hash'=>null, 'label'=>$this->actionTitle]];

			} else {

				$this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];

			}



			if ($this->view->viewType == 'view') {



				if($this->checkPermissions([APPLICANT_ROLE_ID])) {

					//If not the author: $permissionDenied = true;

				}



				if($this->checkPermissions([MODERATOR_ROLE_ID])) {

					//If not moderator in this cc: $permissionDenied = true;

				}



				$this->view->comments = $handleRequest->getCommentList($requestID, $this->view->requestData['center_id'], true);



				//Add the information for the Dream PDF

				$pdfPatientString = strip_tags($this->helper->requestSubject(['anonymous'=>$this->view->requestData['request_anonymous'], 'patientSurname'=>$this->view->requestData['patient_surname'], 'patientName'=>$this->view->requestData['patient_name'], 'ageYears'=>$this->view->requestData['age_years'], 'ageMonths'=>$this->view->requestData['age_months'], 'ageDays'=>$this->view->requestData['age_days'], 'patientGender'=>$this->view->requestData['gender']]));



				$pdfComments = $this->view->comments;



				foreach($pdfComments as $index => $item) {

					$pdfComments[$index]['created_at_string'] = $this->helper->getDateString($pdfComments[$index]['created_at']);

				}



				$dreamResults = $this->db->where('request_id', $requestID)->getOne('requests_dream_data', 'dream_evt_id, dream_hash');

				$registryData = null;

				$registryEvtId = null;

				if (isset($dreamResults['dream_hash'])) {

					$registryData = json_decode($dreamResults['dream_hash'], true);

					$registryEvtId = $dreamResults['dream_evt_id'];

				}



				$hasDreamIntegration = false;



				if (isset($registryData['Anagrafica']) && !empty($registryData['Anagrafica'])) {

					$this->view->requestDreamPDF = [

						'registry'=>$registryData['Anagrafica'],

						'evtId'=>$registryEvtId,

						'request'=>['id'=>$requestID, 'requester'=>$this->helper->setDottedFullname($this->view->requestData['sender_name'], $this->view->requestData['sender_surname'], false), 'dateCreatedString'=>date('Y-m-d-H-i-s', strtotime($this->view->requestData['created_at'])), 'created'=>$this->helper->getDateString($this->view->requestData['created_at']), 'lastUpdate'=>$this->helper->getDateString($this->view->requestData['updated_at']), 'pdfLastUpdate'=>$this->helper->getDateString(date('Y-m-d H:i:s')), 'patient'=>$pdfPatientString, 'center'=>$this->view->requestData['center_description'], 'mainQuestion'=>$this->view->requestData['request_question']],

						'icd10'=>$this->view->icd10,

						'wizards'=>$this->view->wizards,

						'dermaPositions'=>$this->view->dermaPositions,

						'maxBloodPressure'=>$this->view->requestData['max_arterial_pressure'],

						'minBloodPressure'=>$this->view->requestData['min_arterial_pressure'],

						'heartRate'=>$this->view->requestData['heart_rate'],

						'saturation'=>$this->view->requestData['saturation'],

						'clinicalRemarks'=>$this->view->requestData['clinical_remarks'],

						'medicalHistory'=>$this->view->requestData['medical_history'],

						//'exams'=>$this->view->exams,

						'comments'=>$pdfComments

					];



					$hasDreamIntegration = true;

				}



				return $this->setJsonView('requestView', false, [], ['requestDreamPDF'=>$this->view->requestDreamPDF, 'userIsAuthor'=>$userIsAuthor, 'hasDreamIntegration'=>$hasDreamIntegration, 'epilepsy_db_data'=>$epilepsy_db_data]);



			} else {

				return $this->setJsonView('requestEdit');

			}

		}

		

		public function saveEpilepsyWizard() {

            if (!$this->user->isLogged()) {

                return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

            }

            

            if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {

                return $this->setRawJsonResponse('err', _('Permission denied.'));

            }

            

            $form_data = $this->getPost('form_data', null);

            $request_code = $this->getPost('request_code', null);

            

            parse_str($form_data, $form_data_parsed);

            $data = isset($form_data_parsed['epilepsy']) ? $form_data_parsed['epilepsy'] : null;

            

            $survey_structure = json_decode($this->db->where('tag', 'wizard-neuro-epilepsy')->where('lang', $this->user->getLanguage())->getValue('requests_wizard_survey', 'json_structure'), true);

            

            foreach($survey_structure as $group_index => $group_item) {



                foreach($group_item['list'] as $question_index => $question_item) {



                    /*if (!isset($question_item['answers'])) {

                        $survey_structure[$group_index][$question_index]['answers'][0]['values'] = $data[$question_index];

                    }*/





                    foreach($question_item['answers'] as $answer_index => $answer_item) {



                        if(!empty($answer_item['values'])){

							foreach($answer_item['values'] as $value_index => $value_item) {

								

								if (isset($data[$group_index][$question_index][$answer_index])) {

									

									$tmp = explode(':', $data[$group_index][$question_index][$answer_index]);

									$checked_value_index = $tmp[0];

									$checked_value_string = $tmp[1];

									

									$survey_structure[$group_index]['list'][$question_index]['answers'][$answer_index]['values'][$checked_value_index]['checked'] = true;

									

								}

							}

						} else {

							$survey_structure[$group_index]['list'][$question_index]['answers'] = $data[$group_index][$question_index][0];

						}

                    }

                }

            }

            

            if (!is_null($request_code)) {

                $this->db->replace('requests_wizard_survey_answers', [

                    'request_code'=>$request_code,

                    'answer_structure'=>json_encode($survey_structure),

                    'updated_at'=>date('Y-m-d H:i:s')

                ]);

            }

            

            return $this->setRawJsonResponse('ok', '', ['log'=>$survey_structure]);

            //return $this->setRawJsonResponse('ok', '');

        }



		//Save/Edit requests

		public function requestSave() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {

				return $this->setRawJsonResponse('err', _('Permission denied.'));

			}



			$data = isset($_POST['data']) ? $_POST['data'] : null;

			$this->view->data = $data;

			

			//$operation = $data['operation']['value'] == 'draft' ? 'draft' : 'pending';

			

			$operation = $data['operation']['value'];

			if (trim($operation) == '') $operation = 'pending';

			

			$hasFiles = (bool)$data['has_files']['value'];

			$fileCounter = (int)$data['files_counter']['value'];

			$handleRequest = new HandleRequest();



			$requestId = $data['request_id']['value'];

			$requestUniqueCode = $data['request_unique_code']['value'];

			$clinicalCenter = $data['request_cc']['value'];

			$dreamCode = isset($data['dream_code']['value']) ? $data['dream_code']['value'] : '';

			$patientName = trim($data['request_name']['value']);

			$patientSurname = trim($data['request_surname']['value']);

			$patientGender = $data['request_gender']['value'];

			$ageType = isset($data['request_birth_type']['value']) ? $data['request_birth_type']['value'] : null;



			$ageYear = $data['request_birth_year']['value'];

			$ageMonth = $data['request_birth_month']['value'];

			$ageMonthDay = $data['request_birth_month_day']['value'];



			$ageAgeInNumber = $data['request_age']['value'];

			$ageUnitOfTime = $data['request_unit_of_time']['value'];

			$triage = isset($data['triage']['value']) ? $data['triage']['value'] : null;

			$bpMin = (int)$data['request_bp_min']['value'];

			$bpMax = (int)$data['request_bp_max']['value'];

			$heartRate = (int)$data['request_heart_rate']['value'];

			$oxygenSaturation = (int)$data['request_oxy_sat']['value'];

			$medicalRemarks = strip_tags(trim($data['request_medremarks']['value']));

			$medicalHistory = strip_tags(trim($data['request_medicalhistory']['value']));

			$mainQuestion = strip_tags(trim($data['request_mainquestion']['value']));

			$visibility = $data['referral_visibility']['value'];

			$privacy = $data['privacy']['value'];

			$anonymous = $data['request_anonymisation']['value'];

			$dreamCode = trim($data['dream_code']['value']);

			$dreamData = $data['dream_data']['value'];

			$dreamEvtId = $data['dream_evt_id']['value'];



			$icd10List = isset($data['icd10_desease']['value']) ? $data['icd10_desease']['value'] : null;



			//Exams

			$supportedWizards = ['generic', 'derma', 'cardio', 'oto'];

			foreach ($supportedWizards as $wizard) {

				$this->view->wizard[$wizard] = isset($data['exam_'.$wizard]['value']) ? $data['exam_'.$wizard]['value'] : [];

			}



			//Derma positions

			$dermaPositions = isset($data['derma_position']['value']) ? $data['derma_position']['value'] : [];



			//Ear images

			$earImages = isset($data['ear_desease']['value']) ? $data['ear_desease']['value'] : [];



			//return $this->setRawJsonResponse('err', _("Test: ".json_encode($dermaPositions)));



			//Medical specialty (the only required filter)

			$medicalSpecialties = $data['referral_ms']['value'];



			//If no language is selected, assign the user's default language

			$referralLangs = is_array($data['referral_langs']['value']) && !empty($data['referral_langs']['value']) ? $data['referral_langs']['value'] : [$this->user->getUserLang()];



			//Referrals' Clinical Center (could be not set)

			$referralCc = isset($data['referral_cc']['value']) ? $data['referral_cc']['value'] : null;

			//Specific referral list (could be not set)

			$referralList = isset($data['request_referral_list']['value']) ? $data['request_referral_list']['value'] : null;



			//These numbers are used to sort the statuses and the triage colors



			//$status_numbers = ['pending'=>-1, 'draft'=>0, 'opened'=>1, '! referted'=>4, 'reopened'=>3, 'referted'=>2];

			$status_numbers = $handleRequest->statusNumbers;



			//UPDATE requests SET request_status_number = 2 WHERE request_status LIKE '! referted';

			//UPDATE requests SET request_status_number = 4 WHERE request_status LIKE 'referted';



			$triage_numbers = ['white'=>0, 'green'=>1, 'yellow'=>2, 'red'=>3];



			$referralVisibility = $data['referral_visibility']['value'];

			$dateOfBirth = '0000-00-00 00:00:00';



			//Dynamic checkboxes in Preview modal window

			$recipientsIds = isset($data['recipients_ids']['value']) ? $data['recipients_ids']['value'] : [];



			//Request Clinical Center

			if ($clinicalCenter == '') {

				return $this->setRawJsonResponse('err', _('Please provide the Clinical Center.'));

			}



			if ($patientName == '') {

				return $this->setRawJsonResponse('err', _("Please provide the Patient's Name."));

			}



			if ($patientSurname == '') {

				return $this->setRawJsonResponse('err', _("Please provide the Patient's Surname."));

			}



			if ($patientGender == '') {

				return $this->setRawJsonResponse('err', _("Please provide the Patient's Sex."));

			}



			if (is_null($ageType)) {

				return $this->setRawJsonResponse('err', _("Please provide the Patient's date of birth or the age in years or months."));

			}



			if ($ageType == 'date') {

				$dateOfBirth = "$ageYear-$ageMonth-$ageMonthDay 00:00:00";



				if (!$this->utility->isValidDate($dateOfBirth, 'Y-n-j H:i:s')) {

					return $this->setRawJsonResponse('err', _("The date of birth provided is not valid."));

				}

			}



			if ($ageType == 'number') {

				if ((int)$ageAgeInNumber > 0) {



					if ($ageUnitOfTime == 'y' && $ageAgeInNumber < 2) {

						return $this->setRawJsonResponse('err', _("Please provide the Patient's age in months."));

					}



					if ($ageUnitOfTime == 'y') {

						$diffYears = (int)date('Y')-$ageAgeInNumber;

						$dateOfBirth = "$diffYears-01-01 00:00:00";

					}



					if ($ageUnitOfTime == 'm') {

						$dateOfBirth = date('Y-m-01 00:00:00', strtotime("-$ageAgeInNumber months"));

					}



				} else {

					return $this->setRawJsonResponse('err', _("Patient's age must be a number."));

				}

			}



			//Check date of birth is in the future

			$checkBirthDate = new DateTime($dateOfBirth);

			$checkDateNow = new DateTime();

			if ($checkBirthDate > $checkDateNow) {

				return $this->setRawJsonResponse('err', _("The date of birth cannot be in the future."));

			}



			if ($bpMin > 0 && $bpMax > 0) {

				if ($bpMin > $bpMax) {

					return $this->setRawJsonResponse('err', _("Minimum Blood Pressure cannot be higher than the Maximum one."));

				}

			}



			if ($bpMax > 250) {

				return $this->setRawJsonResponse('err', _("Maximum Blood Pressure is too high."));

			}



			if ($bpMin > 250) {

				return $this->setRawJsonResponse('err', _("Minimum Blood Pressure is too high."));

			}



			if ($heartRate > 250) {

				return $this->setRawJsonResponse('err', _("Heart Rate cannot be higher then 250 bpm."));

			}



			if ($oxygenSaturation > 100) {

				return $this->setRawJsonResponse('err', _("Oxygen Saturation cannot be higher than 100%."));

			}



			if ($medicalRemarks == '') {

				return $this->setRawJsonResponse('err', _("Please provide the Medical Remarks."));

			}



			if ($mainQuestion == '') {

				return $this->setRawJsonResponse('err', _("Please provide the Main Question."));

			}



			if (!is_array($referralList)) {

				if (!is_array($medicalSpecialties)) {

					return $this->setRawJsonResponse('err', _('Please provide at least one Medical Specialty for this request.'));

				}

			}



			//Check whether is provided a referral list or isn't

			$specificReferralData = [];

			if (is_array($referralList)) {

				//Get Medical Specialties and Referral Languages

				$referralIds = implode(',', $referralList);



				$medicalSpecialties = [];

				$referralLangs = [];



				$specificReferralData = $this->db

					->where("u.id IN($referralIds)")

					->where('u.group_id', $this->userGroupId)

					->join('users_medical_specialties_to umst', 'umst.user_id=u.id', 'INNER')

					->groupBy('umst.specialty_id')

					->get('users u', null, ['umst.specialty_id referral_md', 'u.language_default referral_lang']);



				if (is_array($specificReferralData) && !empty($specificReferralData)) {

					foreach($specificReferralData as $item) {

						$medicalSpecialties[$item['referral_md']] = $item['referral_md'];

						$referralLangs[$item['referral_lang']] = $item['referral_lang'];

					}

				}



			}



			if ((int)$privacy == 0) {

				return $this->setRawJsonResponse('err', _('Please provide the Privacy Policy consent.'));

			}

			

			$cgnamesurname = $data['cgnamesurname']['value'];

			$cgrole = $data['cgrole']['value'];

			$cgphone = $data['cgphone']['value'];

			$cgemail = $data['cgemail']['value'];

			$cgmmgnamesurname = $data['cgmmgnamesurname']['value'];

			$cgmmgphone = $data['cgmmgphone']['value'];

			$cgmmgemail = $data['cgmmgemail']['value'];

			$cgprovince = $data['cgprovince']['value'];

			$cgcity = isset($data['cgcity']['value']) ? $data['cgcity']['value'] : 0;



			$dbData = [

				'group_id' => $this->userGroupId, //mainController

				'center_id' => $clinicalCenter,

				'user_id' => $this->user->getUserId(),

				'unique_code' => $requestUniqueCode,

				'request_question' => $mainQuestion,

				'request_status' => $operation,

				'request_visibility' => (int)$visibility == 1 ? 'all' : 'private',

				'request_origin' => 'web',

				'request_status_number' => isset($status_numbers[$operation]) ? $status_numbers[$operation] : 0, //Default Draft

				'request_guid' => $this->security->getGUID(),

				'triage_color' => $triage,

				'triage_number' => isset($triage_numbers[$triage]) ? $triage_numbers[$triage] : 0,

				'cgnamesurname' => $cgnamesurname,

				'cgrole' => $cgrole,

				'cgphone' => $cgphone,

				'cgemail' => $cgemail,

				'cgmmgnamesurname' => $cgmmgnamesurname,

				'cgmmgphone' => $cgmmgphone,

				'cgmmgemail' => $cgmmgemail,

				'cgprovince' => $cgprovince,

				'cgcity' => $cgcity,

				'patient_privacy' => $privacy,

				'send_status' => 'central',

				'request_anonymous' => $anonymous,

				'updated_at' => date('Y-m-d H:i:s'),

				'created_at' => date('Y-m-d H:i:s')

			];

			

			



			//First check for recipients

			if (empty($recipientsIds)) {

				/*$recipients = $handleRequest->getRecipients([

					'recipientList' => [],

					'ms' => $medicalSpecialties,

					'cc' => $referralCc,

					'langs' => $referralLangs,

					'groupId' => $this->userGroupId

				]);*/



				$recipients = $handleRequest->getRecipients([

					'recipientList' => [],

					'ms' => $medicalSpecialties,

					'cc' => [$clinicalCenter],

					'langs' => $referralLangs,

					'groupId' => $this->userGroupId

				]);



				if (is_array($recipients) && !empty($recipients)) {

					foreach($recipients as $recipient) {

						$recipientsIds[] = $recipient['user_id'];

					}

				}



			}



			if ($requestId == 0) { //Add



				//Add the request record if there are recipients

				if (is_array($recipientsIds) && !empty($recipientsIds)) {

					//$dbData['created_at'] = date('Y-m-d H:i:s');

					$lastInsert = $this->db->insert('requests', $dbData);

					$requestId = $lastInsert;



				} else {

					return $this->setRawJsonResponse('err', _('Unable to save the Request: the Recipient List is empty.'), ['log'=>[]]);

				}





			} else { //Update

				$handleRequest->setActivityLog($this->user->getUserId(), 'REQ_SAVED_DRAFT', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);

				$this->db->where('id', $requestId)->update('requests', $dbData);

			}



			if ($requestId > 0) {

				

				//Sportello cura

				

				$sportellocura_code = (int)$data['sportellocura_code']['value'];

				$sportellocura_json_data = trim($data['sportellocura']['value']);

				

				if ($sportellocura_code > 0 && $sportellocura_json_data != '') {

					

					//Check wheather already added

					//$check = $this->db->where('survey_id', $sportellocura_code)->getOne('sportellocura', 'survey_id');

					

					//if (!isset($check['survey_id'])) {

						

						$this->db->replace('sportellocura', [

							'survey_id'=>$sportellocura_code,

							'request_id'=>$requestId,

							'survey_data'=>$sportellocura_json_data,

							'created_at'=>date('Y-m-d H:i:s')

						]);

						

						$endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];

						$apikey = $this->config['settings']['sportellocura']['api']['key'];

						$vars = ['survey_id'=>$sportellocura_code, 'cmd'=>'set-added'];

						

						$ch = curl_init();

						curl_setopt($ch, CURLOPT_URL, $endpoint);

						curl_setopt($ch, CURLOPT_POST, 1);

						curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);  //Post Fields

						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

						curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 

						curl_setopt($ch, CURLOPT_TIMEOUT, 10); //timeout in seconds

						

						$headers = [

						    'Api-Key: '.$apikey,

						];

						

						curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

						

						$curldata = curl_exec($ch);

						curl_close($ch);

					//}

				}

				

				//DREAM Italy and Sportello Cura files

				if (isset($data['cg']) && is_array($data['cg'])) {

					foreach($data['cg'] as $cg_index => $cg_data) {

						

						$cg_filename = $cg_data['filename'];

						$cg_filesystem_name = md5(uniqid());

						

						$cg_filedata_base64 = $cg_data['filedata'];

						$cg_file_data = base64_decode($cg_filedata_base64);

												

						$cg_file_path = ATTACH_DIR.$cg_filesystem_name;

						file_put_contents($cg_file_path, $cg_file_data);

						

						if (file_exists($cg_file_path)) {

							

							$cg_file_size = filesize($cg_file_path);

							$cg_filetype = mime_content_type($cg_file_path);

							$cg_file_ext = $this->utility->mime2ext($cg_filetype);

							

							if ($cg_file_ext !== false) {

								

								$cg_filesystem_name = $cg_filesystem_name.'.'.$cg_file_ext;

								

								rename($cg_file_path, ATTACH_DIR.$cg_filesystem_name);

								

								$cg_filename = str_ireplace('.'.$cg_file_ext, '', $cg_filename);

								$cg_filename = $cg_filename.'.'.$cg_file_ext;

								

								$cg_file_title = $this->utility->slugify($cg_filename);							

									

								$this->db->insert('requests_attachments', [

									'request_id'=>$requestId,

									'user_id'=>$this->user->getUserId(),

									'file_name'=>$cg_filesystem_name,

									'file_title'=>$cg_file_title,

									'file_ext'=>$cg_file_ext,

									'file_size'=>$cg_file_size,

									'file_mime'=>$cg_filetype,

									'type'=>'others',

									'created_at'=>date('Y-m-d H:i:s')

								]);

							}

							

						}

						

					}

				} else {

					file_put_contents(ATTACH_DIR.'nodata.log', '');

				}



				//Update the Patient's Registry

				$registryData = [

					'request_id' => $requestId,

					'center_id' => $clinicalCenter,

					'name' => $patientName,

					'surname' => $patientSurname,

					'birthdate' => $dateOfBirth,

					'gender' => $patientGender,

					'min_arterial_pressure' => $bpMin,

					'max_arterial_pressure' => $bpMax,

					'heart_rate' => $heartRate,

					'saturation' => $oxygenSaturation,

					'clinical_remarks' => $medicalRemarks,

					'medical_history' => $medicalHistory,

					'updated_at' => date('Y-m-d H:i:s'),

					'created_at' => date('Y-m-d H:i:s')

				];



				$this->db->replace('requests_registry', $registryData);



				//Check Specific Referrals

				$this->db->where('request_id', $requestId)->delete('requests_recipients');

				if (is_array($referralList)) {

					foreach($referralList as $referralId) {

						$this->db->insert('requests_recipients', [

							'request_id' => $requestId,

							'user_id' => $referralId

						]);

					}

				}



				//Add/Update the Medical Specialties

				$this->db->where('request_id', $requestId)->delete('requests_medical_specialties_to');

				foreach($medicalSpecialties as $specialtyId) {

					$this->db->insert('requests_medical_specialties_to', [

						'request_id' => $requestId,

						'specialty_id' => $specialtyId

					]);

				}



				//Add/Update Clinical Centers

				$this->db->where('request_id', $requestId)->delete('request_clinical_centers_to');

				if (is_array($referralCc) && !empty($referralCc)) {

					foreach($referralCc as $ccId) {

						$this->db->insert('request_clinical_centers_to', [

							'request_id' => $requestId,

							'center_id' => $ccId

						]);

					}

				}



				//Add/Update recipients' languages

				$this->db->where('request_id', $requestId)->delete('requests_languages_to');

				foreach($referralLangs as $language) {

					$this->db->insert('requests_languages_to', [

						'request_id' => $requestId,

						'language_code' => $language

					]);

				}



				//ICD-10

				$this->db->where('request_id', $requestId)->delete('requests_symptoms_to');

				if (is_array($icd10List) && !empty($icd10List)) {

					foreach($icd10List as $symptomId) {

						$this->db->insert('requests_symptoms_to', [

							'request_id' => $requestId,

							'symptom_id' => $symptomId

						]);

					}

				}



				//Wizards

				$this->db->where('request_id', $requestId)->delete('requests_wizards_to');

				if (is_array($this->view->wizard)) {

					foreach($this->view->wizard as $wizardType => $wizardIds) {

						if (is_array($wizardIds) && !empty($wizardIds)) {

							foreach($wizardIds as $examId) {

								$this->db->insert('requests_wizards_to', [

									'request_id' => $requestId,

									'exam_id' => $examId,

									'exam_type' => $wizardType

								]);

							}

						}

					}

				}



				//Wizard Derma positions

				$this->db->where('request_id', $requestId)->delete('requests_wizard_derma_position_to');

				if (is_array($dermaPositions) && !empty($dermaPositions)) {

					foreach($dermaPositions as $positionType) {

						$this->db->insert('requests_wizard_derma_position_to', [

							'request_id' => $requestId,

							'position_type' => $positionType

						]);

					}

				}



				//Wizard Ear images

				$this->db->where('request_id', $requestId)->delete('requests_wizard_ear_deseases_to');

				if (is_array($earImages) && !empty($earImages)) {

					foreach($earImages as $earImagesType) {

						$this->db->insert('requests_wizard_ear_deseases_to', [

							'request_id' => $requestId,

							'desease_type' => $earImagesType

						]);

					}

				}



				//Dream

				if ($dreamCode != '') {

					$this->db->replace('requests_dream_data', [

						'request_id' => $requestId,

						'dream_code' => trim(strtoupper($dreamCode)),

						'dream_evt_id' => $dreamEvtId,

						'dream_hash' => $dreamData,

						'created_at' => date('Y-m-d H:i:s')

					]);

				}

			}



			$this->view->dbData = $dbData; //Debug



			//return $this->setJsonView('requestSave');

			//$debug = $handleRequest->checkPartialUploads();



			if ($operation == 'draft') {

				return $this->setRawJsonResponse('ok', _('Request information successfully saved as draft.'), ['log'=>$dermaPositions], ['button'=>'refresh-hash', 'recordId'=>$requestId, 'idPosition'=>3]);

			} else {



				//Update the recipient list for this request and change the status to pending|opened

				if (is_array($recipientsIds) && !empty($recipientsIds)) {

					$this->db->where('request_id', $requestId)->delete('requests_recipients');

					foreach($recipientsIds as $recipientId) {

						$this->db->insert('requests_recipients', [

							'request_id' => $requestId,

							'user_id' => $recipientId

						]);

					}

					

					if ($operation != 'referted') {

						$requestStatus = $hasFiles ? $handleRequest::REQUEST_STATUS_PENDING : $handleRequest::REQUEST_STATUS_OPENED;

						$handleRequest->setRequestStatus($requestId, $requestStatus, $this->user->getUserId());

					}

										

					if ($operation == 'referted' && $clinicalCenter == 124) {

						$this->db->insert('requests_comments', [

							'request_id' => $requestId,

							'user_id' => $this->user->getUserId(),

							'comment' => 'Teleconsulto chiuso.',

							'comment_guid' => $this->security->getGUID(),

							'updated_at' => date('Y-m-d H:i:s'),

							'created_at' => date('Y-m-d H:i:s')

						]);

					}



					$handleRequest->setActivityLog($this->user->getUserId(), 'REQ_SENT', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);



					//return $this->setRawJsonResponse('ok', _('Test'), ['log'=>$requestStatus]);



					return $this->setRawJsonResponse('ok', _('Request information successfully opened.'), ['log'=>[]], ['button'=>'goto', 'destination'=>'requests/'.time().'/my/created_at/desc/1']);



				}

			}

		}



		public function getDreamInformation() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			$requestId = $this->getPost('requestId', 0);

			$dreamResult = $this->db->where('request_id', $requestId)->getOne('requests_dream_data', 'dream_code, dream_hash');

			$html = _('No DREAM information available.');



			if (isset($dreamResult['dream_code'])) {

				$dreamData = json_decode($dreamResult['dream_hash'], true);

				$registry = [];

				$exams = [];

				$examStats = [];

				$daily = [];

				$symptoms = [];

				$diagnosis = [];

				$HivStages = [];

				$HivTestHistory = [];

				$TarvHistory = [];

				$ListaFarmaci = [];

				/*$examsAcr = ['Leuco','Eritro','Hemo','Hema','VGM','HGM','CHGM','Plaq','LYM','MXD','NEUT','LYM2','MXD2','NEUT2','CD4','CD4%','CViral','Creat','Glic','Blt','Urea','N2','Bild','GTP','GOT','Albu','Ferro','BK','Plasmodium','Ferritina','AlfaAmilasi','ColTot','ColHDL','Trig','Ca','Na','K','Cl','rdwcv','rdwsd','pdw','mpv','plrc','PT','ALP','Uric','PCR','PCRq','MON','EOS','BAS','MON2','EOS2','BAS2','ProtUR','PCT'];*/

				

				$examsAcr = ['Leuco', 'Eritro', 'Hemo', 'Hema', 'VGM', 'HGM', 'CHGM', 'Plaq', 'LYM', 'MXD', 'NEUT', 'LYM2', 'MXD2', 'NEUT2', 'CD4', 'CD4%', 'CViral', 'Creat', 'Glic', 'Blt', 'Urea', 'N2', 'Bild', 'GTP', 'GOT', 'Albu', 'Ferro', 'BK', 'Plasmodium', 'Ferritina', 'AlfaAmilasi', 'ColTot', 'ColHDL', 'Trig', 'Ca', 'Na', 'K', 'Cl', 'rdwcv', 'rdwsd', 'pdw', 'mpv', 'plrc', 'PT', 'ALP', 'Uric', 'PCR', 'PCRq', 'MON', 'EOS', 'BAS', 'MON2', 'EOS2', 'BAS2', 'ProtUR', 'PCT'];



				if (isset($dreamData['Anagrafica'])) {

					$registry = $dreamData['Anagrafica'];

					$registry['age'] = $this->utility->getAge($registry['dataNascita']);

				}



				if (isset($dreamData['Esami'])) {

					//$exams = $this->utility->orderArray($dreamData['Esami'], 'Data', 'desc');

					$exams = $dreamData['Esami'];

					$filter = ['1'=>'<40', '-3000'=>'<20', '-50'=>'<50', '-150'=>'<150', '-550'=>'<550', '-839'=>'<839', '-1000'=>'<1000', '500001'=>'>ULQ', '10000001'=>'>ULQ', '-2'=>'<LDL', '0'=>'ND', '-2000'=>'A', '-2001'=>'B', '-2002'=>'C', '-2003'=>'D'];



					if (is_array($exams)) {

						foreach($exams as $index => $exam) {

							foreach ($exam as $key => $value) {

								if ($key == 'CViral') {

									$code = (int)$value;



									//Default

									//$exams[$index][$key] = 'ND';



									if (isset($filter[$code])) {

										$exams[$index][$key] = $filter[$code];

									}

								}

							}

						}

					}

				}



				/*if (isset($dreamData['Diaria'])) {

					//$daily = $this->utility->orderArray($dreamData['Diaria'], 'Data', 'desc');

					$daily = $dreamData['Diaria'];



					$years = [];

					$yearList = [];

					$examList = [];

					$chartYears = [];

					$dataValues = [];



					if (is_array($daily)) {

						foreach($daily as $exam) {

							if (strlen($exam['Data']) > 4) {

								$y = substr($exam['Data'], 0, 4);

								$years[$y] = $y;

							}

						}



						if (count($years) > 1) rsort($years);



						if (count($years) > 3) {

							$yearList = array_slice($years, 0, 3);

						} else {

							$yearList = $years;

						}



						foreach($daily as $exam) {

							$y = substr($exam['Data'], 0, 4);

							$m = substr($exam['Data'], 5, 2);

							if (in_array($y, $yearList)) {

								$examList[$y][$m]['TAmin'][] = (float)$exam['TA_min'];

								$examList[$y][$m]['TAmax'][] = (float)$exam['TA_max'];

								$examList[$y][$m]['FC'][] = (float)$exam['FC'];

							}

						}



						ksort($examList);

						$chartYears = array_keys($examList);



						$monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];

						foreach($examList as $year => $month) {

							foreach($monthList as $monthNumb) {

								if (isset($examList[$year][$monthNumb])) {

									$tamin = $examList[$year][$monthNumb]['TAmin'];

									$v = array_sum($tamin)/count($tamin);

									$examList[$year][$monthNumb]['TAmin'] = $v > 0 ? $v : null;



									$tamax = $examList[$year][$monthNumb]['TAmax'];

									$v = array_sum($tamax)/count($tamax);

									$examList[$year][$monthNumb]['TAmax'] = $v > 0 ? $v : null;



									$fc = $examList[$year][$monthNumb]['FC'];

									$v = array_sum($fc)/count($fc);

									$examList[$year][$monthNumb]['FC'] = $v > 0 ? $v : null;

								} else {

									$examList[$year][$monthNumb] = ['TAmin'=>null, 'TAmax'=>null, 'FC'=>null];

								}

							}

						}



						foreach($examList as $year => $month) {

							$yearMonthList = $examList[$year];

							ksort($yearMonthList);

							$examList[$year] = $yearMonthList;

						}



						foreach($examList as $year => $month) {



							foreach($month as $monthNumb => $montValue) {

								$dataValues[$year]['TAmin'][] = $montValue['TAmin'];

								$dataValues[$year]['TAmax'][] = $montValue['TAmax'];

								$dataValues[$year]['FC'][] = $montValue['FC'];

							}

						}





						$examStats = $examList;



					}

				}*/

				

				if (isset($dreamData['Diaria'])) {

					//$daily = $this->utility->orderArray($dreamData['Diaria'], 'date_event', 'desc');

					$daily = $dreamData['Diaria'];

					

					$years = [];

					$yearList = [];

					$examList = [];

					$chartYears = [];

					$dataValues = [];



					if (is_array($daily)) {

						foreach($daily as $exam) {

							if (strlen($exam['date_event']) > 4) {

								$y = substr($exam['date_event'], 0, 4);

								$years[$y] = $y;

							}

						}



						if (count($years) > 1) rsort($years);



						if (count($years) > 3) {

							$yearList = array_slice($years, 0, 3);

						} else {

							$yearList = $years;

						}



						foreach($daily as $exam) {

							$y = substr($exam['date_event'], 0, 4);

							$m = substr($exam['date_event'], 5, 2);

							if (in_array($y, $yearList)) {

								$examList[$y][$m]['TAmin'][] = (float)$exam['vn26']; //TA_min

								$examList[$y][$m]['TAmax'][] = (float)$exam['vn25']; //TA_max

								$examList[$y][$m]['FC'][] = (float)$exam['vn10']; //FC

							}

						}



						ksort($examList);

						$chartYears = array_keys($examList);



						$monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];

						foreach($examList as $year => $month) {

							foreach($monthList as $monthNumb) {

								if (isset($examList[$year][$monthNumb])) {

									$tamin = $examList[$year][$monthNumb]['TAmin'];

									$v = array_sum($tamin)/count($tamin);

									$examList[$year][$monthNumb]['TAmin'] = $v > 0 ? $v : null;



									$tamax = $examList[$year][$monthNumb]['TAmax'];

									$v = array_sum($tamax)/count($tamax);

									$examList[$year][$monthNumb]['TAmax'] = $v > 0 ? $v : null;



									$fc = $examList[$year][$monthNumb]['FC'];

									$v = array_sum($fc)/count($fc);

									$examList[$year][$monthNumb]['FC'] = $v > 0 ? $v : null;

								} else {

									$examList[$year][$monthNumb] = ['TAmin'=>null, 'TAmax'=>null, 'FC'=>null];

								}

							}

						}



						foreach($examList as $year => $month) {

							$yearMonthList = $examList[$year];

							ksort($yearMonthList);

							$examList[$year] = $yearMonthList;

						}



						foreach($examList as $year => $month) {



							foreach($month as $monthNumb => $montValue) {

								$dataValues[$year]['TAmin'][] = $montValue['TAmin'];

								$dataValues[$year]['TAmax'][] = $montValue['TAmax'];

								$dataValues[$year]['FC'][] = $montValue['FC'];

							}

						}





						$examStats = $examList;



					}

				}



				if (isset($dreamData['Sintomi'])) {

					$symptoms = $dreamData['Sintomi'];

				}



				if (isset($dreamData['Diagnosi'])) {

					$diagnosis = $dreamData['Diagnosi'];

				}



				if (isset($dreamData['HivStages'])) {

					$HivStages = $dreamData['HivStages'][0] ?? [];

				}



				if (isset($dreamData['HivTestHistory'])) {

					$HivTestHistory = $dreamData['HivTestHistory'][0] ?? [];

				}



				if (isset($dreamData['TarvHistory'])) {

					$TarvHistory = $this->utility->orderArray($dreamData['TarvHistory'], 'DataInizio', 'desc') ?? [];

					//$TarvHistory = $dreamData['TarvHistory'][0] ?? [];

				}



				if (isset($dreamData['ListaFarmaci'])) {

					$ListaFarmaci = $dreamData['ListaFarmaci'];

				}



				$dailyData = [];

				if (is_array($daily) && !empty($daily)) {

					foreach($daily as $item) {

						$dailyData[$item['id_event']]['Diaria'] = $item;



						foreach($symptoms as $symptom) {

							if ($symptom['id_event'] == $item['id_event']) {

								$dailyData[$item['id_event']]['Sintomi'][] = $symptom;

							}

						}



						foreach($diagnosis as $diagnosi) {

							if ($diagnosi['id_event'] == $item['id_event']) {

								$dailyData[$item['id_event']]['Diagnosi'][] = $diagnosi;

							}

						}

					}

				}



				$html = $this->partial('Request/dream-dialog-content', ['dreamData'=>$dreamData, 'registry'=>$registry, 'exams'=>$exams, 'examStats'=>$examStats, 'examsAcr'=>$examsAcr, 'dailyData'=>$dailyData, 'dataValues'=>$dataValues, 'daily'=>$daily, 'symptoms'=>$symptoms, 'diagnosis'=>$diagnosis, 'HivStages'=>$HivStages, 'HivTestHistory'=>$HivTestHistory, 'TarvHistory'=>$TarvHistory, 'ListaFarmaci'=>$ListaFarmaci]);

			}



			return $this->setRawJsonResponse('ok', '', ['html'=>$html, 'chartYears'=>$chartYears, 'dataValues'=>$dataValues]);

		}



		//Ajax function to update the Medical Specialties per Clinical Center

		public function getSpecialtiesPerCenter() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			$medicalSpecialties = [];



			$centerId = $this->getPost('centerId', 0);

			$handleRequest = new HandleRequest();

			$results = $handleRequest->getSpecialtyByClinicalCenterId($centerId, $this->userGroupId);



			if (is_array($results)) {

				$c=0;

				foreach($results as $item) {

					$medicalSpecialties[$c]['value'] = $item['id'];

					$medicalSpecialties[$c]['text'] = _($item['description']);

					$c++;

				}

			}



			return $this->setRawJsonResponse('ok', '', ['specialties'=>$medicalSpecialties]);

		}



		//Ajax function to send message (comment) from Request page

		public function requestSendMessage() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			$handleRequest = new HandleRequest();

			$requestID = $this->getPost('requestID', 0);

			$centerID = $this->getPost('centerID', 0);

			$newStatus = $this->getPost('newStatus', '');

			$message = trim($this->getPost('message', null));

			$specialties = rawurldecode($this->getPost('specialtyList', ''));

			$specialtyList = strpos($specialties, ',') !== false || (int)$specialties > 0 ? explode(',', $specialties) : null;

			$hasAttachments = $this->getPost('hasAttachments', false);



			$return = [];



			//$buffer = $handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $this->user->getUserId(), 15);

			//return $this->setRawJsonResponse('err', $buffer, ['log'=>$buffer]);



			if ($message == '') {

				return $this->setRawJsonResponse('err', _('The Comment text field cannot be empty.'), ['log'=>[]]);

			}



			$id = $this->db->insert('requests_comments', [

				'request_id' => $requestID,

				'user_id' => $this->user->getUserId(),

				'comment' => $message,

				'comment_guid' => $this->security->getGUID(),

				'updated_at' => date('Y-m-d H:i:s'),

				'created_at' => date('Y-m-d H:i:s')

			]);



			if ($id) {

				$comments = $handleRequest->getCommentList($requestID, $centerID, true);

				$request = $this->db->where('id', $requestID)->getOne('requests');



				$html = $this->partial('Request/comment-list', ['comments'=>$comments]);



				$return['commentID'] = $id;

				$return['html'] = $html;



				$handleRequest->setActivityLog($this->user->getUserId(), 'REQ_MSG', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);



				//If the user is a referral, increment the comment counter (request_reports_counter table)

				if ($handleRequest->isReferralInRequest($requestID, $this->user->getUserId())) {



					//$handleRequest->setLog('position', 'dentro is referral in request');



					//Check whether moderator or referral has added new medical specialty and notify new referrals

					if ($handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $request['user_id'], $request['center_id'])) {



						$handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_PART_REPORTED, $this->user->getUserId());



						//$handleRequest->setLog('position', 'dentro forward');



					} else {



						//If previusly reported, just change the status to reported (closed)

						/*if ($handleRequest->isRequestPreviouslyReopened($requestID)) {



							$handleRequest->setLog('position', 'dentro is previuosly reopened');



							$handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REPORTED, $this->user->getUserId());

							//Notify the applicant (queue the message)

							$msgStructure = $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'PARTIALLY_REPORTED');

						} else {*/



							//$handleRequest->setLog('position', 'dentro il commento normale, incrementa il contatore');



							//If a referral comments again, doesn't add a new record in the table (see the table indexes)

							$handleRequest->incrementReferralCounter($requestID, $this->user->getUserId());



							//Change the request status

							if ($handleRequest->isRequestFullyReported($requestID) === true) {

								$handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REPORTED, $this->user->getUserId());

								$handleRequest->setActivityLog($this->user->getUserId(), 'REQ_CLOSED_AUTO', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);

							} else {

								$handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_PART_REPORTED, $this->user->getUserId());

							}



							//Notify the applicant (queue the message)

							$msgStructure = $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'PARTIALLY_REPORTED');



						//}



					}



				}



				//TODO: check whether the comment has attachments (visible / not visible)



				//Applicant's comment: change the status to REOPENED

				if ($handleRequest->isApplicantInRequest($requestID, $this->user->getUserId())) {

					$handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REOPENED, $this->user->getUserId());

					$handleRequest->notifyAllReferrals($requestID, 'REQUEST_UPDATE');

				}



				//Force the new request status (Moderator)

				if ($newStatus != '') {

					$handleRequest->setRequestStatus($requestID, $newStatus, $this->user->getUserId());



					$isFwd = $handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $request['user_id'], $request['center_id']);



					if ($newStatus == 'reopened') {

						//Notifiy all referrals

						$handleRequest->notifyAllReferrals($requestID, 'REQUEST_UPDATE');

						//Notify the applicant

						$handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'REQUEST_UPDATE_APPLICANT');

					}



					if ($newStatus == 'referted') {

						//Notify the applicant

						$handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'CLOSED_BY_MODERATOR');

					}



					$handleRequest->setActivityLog($this->user->getUserId(), 'REQ_STATUS_CNG_MODERATOR', ['userId'=>$this->user->getUserId(), 'newStatus'=>$newStatus]);

				}



				//Update last update request field

				$handleRequest->updateDate($requestID);



				$return['action'] = 'refresh';



				return $this->setRawJsonResponse('ok', '', $return);



			} else {

				return $this->setRawJsonResponse('err', _('Unable to send the message right now. Please try again in a few minutes.'), ['log'=>[]]);

			}



		}



		//Ajax function to load all request comments

		public function requestLoadAllComments() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			$requestID = $this->getPost('requestID', 0);

			$centerID = $this->getPost('centerID', 0);



			$comments = $handleRequest->getCommentList($requestID, $centerID, true);



			$html = $this->partial('Request/comment-list', ['comments'=>$comments]);



			return $this->setRawJsonResponse('ok', '', ['html'=>$html]);

		}



		//Ajax function to get the deaseses under a provided ICD10 category

		public function requestGetDeseases() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {

				return $this->setRawJsonResponse('err', _('Permission denied.'));

			}



			$icd10Id = $this->getPost('icd10Id', null); //Parent category ID



			//If Draft mode some deseases could be selected

			$selectedDeseases = $this->getPost('selectedDeseases', []);



			$handleRequest = new HandleRequest();



			$deseases = $handleRequest->getDeseasesByICD10Category($icd10Id, $this->user->getUserLang(), $selectedDeseases);



			$html = $this->partial('Request/icd10-deseases-list', ['deseases'=>$deseases]);



			return $this->setRawJsonResponse('ok', '', ['html'=>$html]);

		}



		public function requestSearchDesease() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('ok', '', ['html'=>'']);

			}



			if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {

				return $this->setRawJsonResponse('ok', '', ['html'=>'']);

			}



			$handleRequest = new HandleRequest();

			$keyword = addslashes($this->getPost('keyword', null));

			$langCode = $this->getPost('lang', 'en');

			$selectedDeseases = $this->getPost('selectedDeseases', []);



			$deseases = $handleRequest->getDeseaseByKeyword($keyword, $langCode, $selectedDeseases);



			$html = $this->partial('Request/icd10-search-deseases-list', ['deseases'=>$deseases, 'langCode'=>$langCode]);



			return $this->setRawJsonResponse('ok', '', ['html'=>$html]);

		}



		//Ajax function to get all attachs by post code (used to render the attachs list after an Ajax call)

		public function requestAttachs() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID])) {

				return $this->setRawJsonResponse('err', _('Permission denied.'));

			}



			$postCode = $this->getPost('postCode', null);

			$attachs = [];

			$request = null;



			if(!is_null($postCode)) {

				$request = $this->db

					->where('r.unique_code', $postCode)

					->join('requests_attachments ra', 'ra.request_id=r.id', 'INNER')

					->get('requests r', null, ['ra.id attach_id', 'ra.file_name attach_name', 'ra.file_title attach_title', 'ra.file_ext attach_ext']);



				if (is_array($request)) {



					foreach($request as $index => $item) {

						$ext = trim($item['attach_ext']) != '' ? $item['attach_ext'] : pathinfo($item['attach_name'], PATHINFO_EXTENSION);



						$attachs[$index]['forceDownload'] = !in_array($ext, $this->config['settings']['preview-ext']) ? 1 : 0;

						$attachs[$index]['ext'] = $ext;

						$attachs[$index]['id'] = $item['attach_id'];

						$attachs[$index]['name'] = $item['attach_name'];

						$attachs[$index]['title'] = $this->helper->truncate($item['attach_title'], MAX_ATTACH_TITLE_LENGTH, '...'.$item['attach_ext']);					}

				}

			}



			return $this->setRawJsonResponse('ok', '', ['attachData'=>$attachs]);

		}



		//Ajax function to delete the passed attachment id

		public function requestDeleteAttach() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {

				return $this->setRawJsonResponse('err', _('Permission denied.'));

			}



			$attachId = $this->getPost('attachId', null);

			$attachName = $this->getPost('attachName', null);

			$delete = false;



			if (!is_null($attachId) && !is_null($attachName)) {

				$delete = $this->db->where('id', $attachId)->delete('requests_attachments');

				@unlink(ATTACH_DIR.$attachName);

			}



			if ($delete) {

				return $this->setRawJsonResponse('ok', '', ['attachId'=>$attachId]);

			} else {

				return $this->setRawJsonResponse('ok', '', ['attachId'=>0]);

			}

		}



		//Ajax function to delete the request by id

		public function requestDelete() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			if(!$this->checkPermissions([APPLICANT_ROLE_ID, MODERATOR_ROLE_ID])) {

				return $this->setRawJsonResponse('err', _('Permission denied.'));

			}

			

			$scope = $this->user->is(APPLICANT_ROLE_ID) ? 'my' : 'moderations';



			$requestId = $this->getPost('requestId', 0);



			$handleRequest = new HandleRequest();



			$return = $handleRequest->deleteRequest($requestId);



			if ($return) {

				$handleRequest->setActivityLog($this->user->getUserId(), 'REQ_DELETED', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);

				return $this->setRawJsonResponse('ok', '', ['redirect'=>'requests/'.time().'/'.$scope.'/created_at/desc/1']);

			} else {

				return $this->setRawJsonResponse('err', _('Unable to delete the request right now, please try again in a few minutes.'));

			}

		}



		public function getRequestResponders() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			if(!$this->checkPermissions([MODERATOR_ROLE_ID])) {

				return $this->setRawJsonResponse('err', _('Permission denied.'));

			}



			$handleRequest = new HandleRequest();



			$requestId = $this->getPost('requestId', 0);



			$recipients = $handleRequest->getRecipientsByRequestId($requestId);



			$html = $this->partial('Request/show-responders-list', ['recipients'=>$recipients]);



			return $this->setRawJsonResponse('ok', '', ['html'=>$html]);

		}



		//Activity log page

		public function logs() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			if(!$this->checkPermissions([ADMIN_ROLE_ID])) {

				return $this->setRawJsonResponse('err', _('Permission denied.'));

			}



			$this->view->users = $this->db

				->where('status', 1)

				->where('group_id', $this->userGroupId)

				->orderBy('surname', 'asc')

				->get('users', null, ['id', 'username', 'name', 'surname']);



			$this->view->requests = $this->db

				->where('u.status', 1)

				->where('u.group_id', $this->userGroupId)

				->join('users u', 'u.id=r.user_id', 'INNER')

				->orderBy('r.created_at', 'desc')

				->get('requests r', 100, ['r.id', 'r.created_at']);



			$this->actionTitle = _('Activity logs');

			return $this->setJsonView('logs');

		}



		//Sending Referral list preview (in a modal)

		public function requestPreview() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {

				return $this->setRawJsonResponse('err', _('Permission denied.'));

			}



			$data = isset($_POST['data']) ? $_POST['data'] : null;



			$this->view->data = $data;

			$this->view->error = '';

			$userCount = 0;

			$request = new HandleRequest();



			$recipientList = $data['request_referral_list']['value'];



			if (!is_array($recipientList)) {

				if (!is_array($data['referral_ms']['value'])) {

					$this->view->error = _('Please provide at least one Responder Medical for this request.');

					return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);

				}



				/*if (!is_array($data['referral_cc']['value'])) {

					$this->view->error = _('Please provide at least one Responder Clinical Center.');

					return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);

				}

				*/



				if (!is_array($data['referral_langs']['value'])) {

					$this->view->error = _('Please provide at least one Default Language for this request.');

					return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);

				}

			}



			$referralMs = $data['referral_ms']['value'];

			$referralCc = isset($data['referral_cc']['value']) && !empty($data['referral_cc']['value']) ? $data['referral_cc']['value'] : null;

			$referralLangs = $data['referral_langs']['value'];

			$referralVisibility = $data['referral_ms']['referral_visibility'];



			//Recipients preview

			$this->view->referrals = $request->getRecipients([

				'recipientList' => $recipientList,

				'ms' => $referralMs,

				'cc' => $referralCc,

				'langs' => $referralLangs

			]);



			$userCount = count($this->view->referrals);



			return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);

		}



		public function generatePDF() {

			if (!$this->user->isLogged()) {

				return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);

			}



			$context = $this->getPost('context');

			$operation = $this->getPost('operation');

			$htmlContent = '';

			$outputFilePath = '';

			$fileTitle = 'print_preview';

			$pdf = new PdfPrinter();

			$layout = new Layout();

			$destinationDir = DATA_TMP_DIR;



			$printFileURI = $this->config['settings']['http-protocol'].$this->config['settings']['site-domain'].'/print/';



			switch($context) {

				

				case 'requestview':

					$_POST['requestID'] = $this->getPost('requestId');

					$_POST['viewType'] = 'view';

					$this->requestEdit();



					// footer dinamico

					$headerURI = $printFileURI.'header-default.php?center_description='.rawurlencode($this->view->requestData['center_description'])

												.'&center_continent='.rawurlencode($this->view->requestData['center_continent']).'&center_country='.rawurlencode($this->view->requestData['center_country']).'&center_address='.rawurlencode($this->view->requestData['center_address'])

												.'&companies_title='.rawurlencode($this->view->companies['title'])

												.'&head_title='._('Multidisciplinary teleconsultation service')

												.'&app_report_header='.$this->config['settings']['app-report-header'].'';

					$footerURI = $printFileURI.'footer-default.php?teleconsulto='.rawurlencode($this->actionTitle).'&paziente='.$this->view->requestData['patient_surname'].' '.$this->view->requestData['patient_name']

												.'&request_date='.$this->view->requestData['created_at'].'&patient='._('Patient_pdf').'&request_date_txt='._('Request date').'&print_date_txt='._('Print date')

												.'&request_date='.$this->view->requestData['created_at'].'';

												

					$htmlContent = $this->partial('Print/request-view', ['publicUri'=>$layout->getPublicUri()]);

					$outputFilePath = $destinationDir.'request_'.$this->user->getUserId().'.pdf';

					$fileTitle = 'request_'.$this->view->requestData['id'];

				break;



			}



			//Pass the HTML to $pdf object

			$pdfContent = $pdf->convertHtmlToPdf($htmlContent, $headerURI, $footerURI);



			//file_put_contents($destinationDir.'html.html', $htmlContent);

			file_put_contents($outputFilePath, $pdfContent);



			if ($operation == 'print') {

				return $this->setRawJsonResponse('ok', '', ['outputFilePath'=>$outputFilePath, 'fileTitle'=>$fileTitle,'debug'=>$this->view->companies]);

			} else {

				

				$hr = new HandleRequest();

				$request_id = $this->getPost('requestId');

				$attach_ids = $this->getPost('attach_ids');

				$delay = $this->getPost('delay', null);

				$delay_date = $this->utility->setDateToIsoFormat($delay);

				$attachs = [];

				

				//return $this->setRawJsonResponse('err', '-'.strlen($delay).'-');

				

				if (strlen($delay) > 0 && is_null($delay_date)) {

					return $this->setRawJsonResponse('err', "Impossibile concludere l'operazione, la data di spedizione deve essere indicata nel formato gg/mm/aaaa.");

				}

				

				if (!is_null($delay_date) && $this->utility->isDateInThePast($delay_date)) {

					return $this->setRawJsonResponse('err', "La data di spedizione non può essere corrente o nel passato.");

				}

				

				$survey = $this->db->where('request_id', $request_id)->getOne('sportellocura');

				

				if (isset($survey['survey_id']) || trim($this->view->requestData['cgemail']) != '') {

					

					$survey_data = json_decode($survey['survey_data'], true);

					$attachs_data = [];

					

					if (isset($survey['survey_id'])) {

						$recipient_email = $survey_data['email'];

						$recipient_name = $survey_data['name'];

						$recipient_surname = $survey_data['surname'];

						$mailcode = 'SURVEY_'.uniqid();

						$survey_id = $survey['survey_id'];

					} else {

						$recipient_email = trim($this->view->requestData['cgemail']);

						$recipient_name = '';

						$recipient_surname = trim($this->view->requestData['cgnamesurname']) != '' ? trim($this->view->requestData['cgnamesurname']) : 'Paziente';

						$mailcode = 'REPORT_'.uniqid();

						$survey_id = 0;

					}

					

					//$recipient_email = 'agodegi@gmail.com';



					

					if ($this->utility->validateEmail($recipient_email)) {

				

						if (is_array($attach_ids) && !empty($attach_ids)) {

							$attach_id_list = implode(',', $attach_ids);

							$attachs = $this->db->where("id IN($attach_id_list)")->get('requests_attachments');

							

							if (is_array($attachs) && !empty($attachs)) {

								foreach($attachs as $index => $attach) {

									$attachs_data[$index]['path'] = ATTACH_DIR.$attach['file_name'];

									$attachs_data[$index]['name'] = $attach['file_title'].'.'.$attach['file_ext'];

								}

							}

						}

						

						$pdf_path = ATTACH_DIR.$request_id.'.pdf';

						rename($outputFilePath, $pdf_path);

						

						//////

						$attachs_data[] = ['path'=>$pdf_path, 'name'=>'Risposta-Specialista.pdf'];

						

						$subject = 'Risposta del TeleAmbulatorio';

						$body = "Gentile $recipient_name $recipient_surname,<br>dopo aver ricevuto le varie notizie cliniche, le inoltriamo, in allegato, la risposta dello specialista alla sua visita ambulatoriale eseguita in modalità di telemedicina.<br><br>N.B.: questo messaggio è inviato automaticamente, eventuali risposte non saranno monitorate.<br><br>

Cordiali Saluti,<br>Servizio di TeleAmbulatorio";

						

						//$nf = new Notification();

						//$mailcode = 'SURVEY_'.uniqid();

						//$nf->sendEmail($recipient_email, $subject, $body, $mailcode, [], $attachs_data);*/

						//////

						

						$hr->insertMsgInQueue([

							'senderId' => $this->user->getUserId(),

							'recipientId' => $this->user->getUserId(), //L'utente corrente deve avere l'invio delle email attivato

							'requestId' => $request_id,

							'mailId' => $mailcode,

							'subject' => $subject,

							'content' => $body,

							'type' => 'email',

							'recipient' => $recipient_email,

							'senderStatus' => 1,

							'attachments' => json_encode($attachs_data),

							'delay' => $delay_date

						]);

						

						//Log

						$this->db->insert('sportellocura_log', [

							'request_id'=>$request_id,

							'survey_id'=>$survey_id,

							'mail_code'=>$mailcode,

							'created_at'=>date('Y-m-d H:i:s')

						]);

						

						$this->notifySendPdf($survey['survey_id']);

						

						return $this->setRawJsonResponse('ok', 'PDF inviato correttamente', ['log'=>null], ['button'=>'refresh-hash']);

						

					} else {

						return $this->setRawJsonResponse('err', _('Not valid recipient e-mail address'));

					}

				

				}

				

				//Send PDF

				return $this->setRawJsonResponse('err', _('Not valid request'));

			}

		}

		

		public function deleteSurveyMailQueue() {

			$mail_id = $this->getPost('mail_id', null);

			$request_id = $this->getPost('request_id', 0);

			

			$this->db

				->where('request_id', $request_id)

				->where('mail_id', $mail_id)

				->delete('requests_messages_queue');

				

			return $this->setRawJsonResponse('ok', 'Il tentativo di cancellazione della ricezione programmata è stato eseguito con successo.');

		}

		

		public function getCitiesByProvince() {

			$province_id = $this->getPost('province_id', 0);

			$selected_city_id = $this->getPost('selected_city_id', 0);

			$options = ['<option value="0">...</option>'];

			$html = '';

			

			$cities = $this->db->where('province_id', $province_id)->orderBy('name', 'ASC')->get('italian_cities');

			if (is_array($cities) && !empty($cities)) {

				foreach($cities as $city) {

					$selected = $city['id'] == $selected_city_id ? 'selected' : '';

					$options[] = '<option value="'.$city['id'].'" '.$selected.'>'.$city['name'].'</option>';

				}

				

				$html = implode("\n", $options);

			}

			

			

			return $this->setRawJsonResponse('ok', '', ['html'=>$html]);

		}

		

		private function notifySendPdf($survey_id=0) {

			$endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];

			$apikey = $this->config['settings']['sportellocura']['api']['key'];

			$vars = ['survey_id'=>$survey_id, 'cmd'=>'notify-pdf'];

			

			if ($survey_id < 1) return;

			

			$ch = curl_init();

			curl_setopt($ch, CURLOPT_URL, $endpoint);

			curl_setopt($ch, CURLOPT_POST, 1);

			curl_setopt($ch, CURLOPT_USERPWD, "dev:demo");

			curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);  //Post Fields

			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 

			curl_setopt($ch, CURLOPT_TIMEOUT, 30);

			

			$headers = [

			    'Api-Key: '.$apikey,

			];

			

			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

			

			$data = curl_exec($ch);

			//$output = json_decode($data, true);

			

			curl_close($ch);

			

			return $data;

		}

		

		public function getSportelloCura() {

			$endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];

			$apikey = $this->config['settings']['sportellocura']['api']['key'];

			$survey_id = $this->getPost('survey_id', 0);

			$vars = ['survey_id'=>$survey_id, 'cmd'=>'get-survey'];

			

			$ch = curl_init();

			curl_setopt($ch, CURLOPT_URL, $endpoint);

			curl_setopt($ch, CURLOPT_POST, 1);

			curl_setopt($ch, CURLOPT_USERPWD, "dev:demo");

			curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);  //Post Fields

			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

			

			$headers = [

			    'Api-Key: '.$apikey,

			];

			

			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

			

			$data = curl_exec($ch);

			$output = json_decode($data, true);

			

			curl_close($ch);

			

			$type_id = isset($output['survey']['type_id']) ? (int)$output['survey']['type_id'] : 0;

			

			$output['survey']['ms'] = 0;

			

			if ($type_id > 0) {

				$ms = $this->db->where('sportello_type_id', $type_id)->getOne('users_medical_specialties');

				if (isset($ms['id']) && (int)$ms['id']>0) {

					$output['survey']['ms'] = $ms['id'];

				}

			}

			

			return $this->setRawJsonResponse('ok', '', ['output'=>$output]);

		}

		

		public function getDreamItaly() {

			

			$endpoint = $this->config['settings']['api']['endpoint'];

			$apikey = $this->config['settings']['api']['key'];

			$code = $this->getPost('code', 0);

			$vars = ['request_id'=>$code];

			

			$ch = curl_init();

			curl_setopt($ch, CURLOPT_URL, $endpoint);

			curl_setopt($ch, CURLOPT_POST, 1);

			curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);  //Post Fields

			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

			

			$headers = [

			    'Api-Key: '.$apikey,

			];

			

			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

			

			$data = curl_exec($ch);

			

			$output = json_decode($data, true);

			

			$output['r_citta_lcl_id'] = 0;

			

			$output['r_provincia_lcl_id'] = 0;

			

			curl_close ($ch);

			

			return $this->setRawJsonResponse('ok', '', ['output'=>$output]);

			

		}

		

		public function setViewerType() {

			$checked_value = $this->getPost('checked_value', -1);

			$user_id = $this->user->getUserId();

			

			if ((int)$checked_value > -1) {

				//$updt = $this->db->where('id', $user_id)->update('users', ['simple_viewer'=>$checked_value]);

				$updt = 0;

			}

			

			return $this->setRawJsonResponse('ok', '', ['output'=>$updt]);

		}



		public function allowAccess() {

			if (!$this->user->isLogged()) {

				return $this->redirect('login', 'index');

			}



			return false;

		}

	}

