<?php

	class surveyController extends mainController {

		function __construct() {

			parent::__construct();

			

			//To change for every Controller

			$this->viewDir = 'Survey';

		}

		

		public function beforeRender($content=null) {

			return false;

		}

		

		//Public (Servey form) 

		/*public function index() {

			$this->view->survey_code = $this->getPost('code', 0);

			$survey_type = [];

			

			$this->view->survey_title = null;

			$this->view->survey_tag = null;

			$this->view->survey_type_id = 0;

			$this->view->structure = null;

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

			$this->view->survey_answered = false;

			$this->view->survey_date = null;

			

			$survey = $this->db

				->where('sy.code', $this->view->survey_code)

				->join('survey_registry syr', 'syr.survey_id=sy.id')

				->getOne('survey sy', "sy.type_id survey_type_id, sy.aswered_recipient, sy.aswered_date, syr.surname patient_surname, syr.name patient_name, syr.birthdate partient_bday, syr.email patient_email");

			

			if (isset($survey['survey_type_id'])) {

				$survey_type = $this->db->where('id', $survey['survey_type_id'])->where('status', 1)->getOne('survey_types');

				$this->view->survey_answered = $survey['aswered_recipient'] == 1 ? true : false;

				$this->view->survey_date = $survey['aswered_date'];

				

				$this->db->where('code', $this->view->survey_code)->update('survey', ['opened_recipient'=>1, 'updated_at'=>date('Y-m-d H:i:s')]);

			}

			

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

			

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

				$this->view->survey_type_id = $survey_type['type_id'];

				$this->view->survey_title = $survey_type['survey_label'];

				$this->view->survey_tag = $survey_type['survey_tag'];

				

				$survey_lang = $survey_type['survey_lang'];

				

				//$structure = json_decode(file_get_contents(RESOURCE_DIR.'survey/'.$survey_lang.'/'.$this->view->survey_tag.'.json'), true);

				//$global_fields = json_decode(file_get_contents(RESOURCE_DIR.'survey/'.$survey_lang.'/global.json'), true);

				

				$this->setSurveyForm($survey_lang, $this->view->survey_tag, $survey);

				

				//$this->view->structure = array_merge($structure, $global_fields);

				//$this->view->survey_patient_string = strip_tags($survey['patient_surname']).' '.strip_tags($survey['patient_name']).', '.$this->helper->getDateString($survey['partient_bday'], false).', '.$survey['patient_email'];

			}

			

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

		}

		

		//Private (managers)

		public function surveyPrivateSend() {

			

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

			

			return $this->setRawJsonResponse('ok', null, ['data'=>$data]);

		}

		

		//Public (people)

		public function surveyPublicSend() {

									

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

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

			$files = $_FILES;

			$max_file_size = 1048576*5; //5 MB

						

			//Remove file information

			if (isset($data['file'])) unset($data['file']);

			

			//Remove privacy information (last item)

			array_pop($data);

			

			//Remove file group information

			array_pop($data);

			

			$insert_data = [

				'json_answers'=>json_encode($data),

				'aswered_recipient'=>1,

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

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

			];

			

			$update = $this->db->where('code', $code)->update('survey', $insert_data);

			

			if ($update) {

				if (isset($files['data'])) {

					foreach($files['data']['name']['file'] as $index => $item) {

						

						if ((int)$files['data']['error']['file'][$index] == 0) {

							

							$file_name = $this->utility->slugify($files['data']['name']['file'][$index]);

							$file_type = $files['data']['type']['file'][$index];

							$file_tmp_name = $files['data']['tmp_name']['file'][$index];

							$file_ext = strtolower(pathinfo($files['data']['name']['file'][$index], PATHINFO_EXTENSION));

							$file_size = $files['data']['size']['file'][$index];

							$file_uuid = $this->getGUID();

							

							if ($file_size <= $max_file_size) {

								

								//Unique index on survey_uuid and file_title to avoid duplicate on multiple submits (i.g. poor connection)

								$insert = $this->db->insert('survey_attachments', [

									'uuid'=>$file_uuid,

									'survey_uuid'=>$code,

									'file_title'=>$file_name,

									'file_type'=>$file_type,

									'file_ext'=>$file_ext,

									'file_size'=>$file_size,

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

								]);

								

								if ($insert) {

									$moved = move_uploaded_file($file_tmp_name, ATTACH_DIR.$file_uuid);

									

									//If not moved, try to delete the record

									if (!$moved) {

										$this->db->where('uuid', $file_uuid)->delete('survey_attachments');

									}

								}

							

							}

							

						}

						

					}

				}

			}

			

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

		}*/

		

		public function surveyList() {

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

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

			}

			

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

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

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

			$this->view->isGlobal = $this->user->is([GLOBAL_MANAGER_ID]) ? true : false;

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

			

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

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

			

			//Get all users (Manager and Global manager) in current user centers

			$cc_list = [];

			$cc_user_list = [];

			$query_user_list = [];

			$cc = $this->db

				->where('ucct.user_id', $this->user->getUserId())

				->where('ucct.role_id IN('.MANAGER_ID.', '.GLOBAL_MANAGER_ID.')')

				->get('users_clinical_centers_to ucct', null, ['ucct.center_id']);

			

			if (is_array($cc)) {

				foreach($cc as $item) {

					//Get unique array

					$cc_list[$item['center_id']] = $item['center_id'];

				}

				

				if (!empty($cc_list)) {

					$cc_user_list = $this->db

						->where('ucct.center_id IN('.implode(',', $cc_list).')')

						->where('ucct.role_id IN('.MANAGER_ID.')')

						->get('users_clinical_centers_to ucct', null, ['ucct.user_id']);

					

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

						foreach($cc_user_list as $item) {

							$query_user_list[] = $item['user_id'];

						}

					}

				}

			}

				

			$this->view->debugcc = $cc_list;

			

			$survey_types = null;

			

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

				$survey_types = $this->db

					->where('status', 1)

					->where('center_id IN('.implode(',', $cc_list).')')

					->orderBy('survey_label', 'ASC')

					->get('survey_types');

			}

				

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

				foreach($survey_types as $item) {

					$this->view->typeList[$item['id']] = '... '.str_ireplace('QUESTIONARIO ', '', $item['survey_label']);

				}

			}

			

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

				if (!empty($query_user_list)) {

					$this->db->where('sy.manager_id IN('.implode(',', $query_user_list).')');

				} else {

					$this->db->where('sy.manager_id', $this->user->getUserId());

				}

			} else {

				$this->db->where('sy.manager_id', $this->user->getUserId());

			}

			

			$survey_type = 0;

			if (isset($this->view->strOutput['searchData']['survey_type'])) {

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

				$survey_type = (int)$this->view->strOutput['searchData']['survey_type'];

				$this->session->refreshSession('search_survey_type', $survey_type);

			} else {

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

					$survey_type = $this->session->getSessionValue('search_survey_type');

				}

			}

			if ((int)$survey_type > 0) {

				$this->db->where('sy.type_id', $survey_type);

			} else {

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

			}

			

			$survey_patient = '';

			if (isset($this->view->strOutput['searchData']['survey_patient'])) {

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

				$survey_patient = $this->view->strOutput['searchData']['survey_patient'];

				$this->session->refreshSession('search_survey_patient', $survey_patient);

			} else {

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

					$survey_patient = $this->session->getSessionValue('search_survey_patient');

				}

			}

			if (trim($survey_patient) != '') {

				//$this->db->where("CONCAT(sry.name, ' ', sry.name)", $survey_patient, 'LIKE');

				$patient_words = $this->utility->splitWords($survey_patient);

				$patient_subquery = [];

				

				if (is_array($patient_words)) {

					foreach($patient_words as $word) {

						$patient_subquery[] = "CONCAT(sry.name, ' ', sry.surname) LIKE '%$word%'";

					}

					

					if (!empty($patient_subquery)) {

						$patient_subquery = implode(' AND ', $patient_subquery);

					}

				}

				

				if (!is_array($patient_subquery)) {

					$this->db->where("(".$patient_subquery.")");

				}

					

			} else {

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

			}

				

			$this->view->survey = $this->db

				->join('survey_registry sry', 'sry.survey_id=sy.id')

				->join('users u', 'u.id=sy.manager_id')

				->join('survey_types sts', 'sts.id=sy.type_id')

				->orderBy('sy.'.$this->view->orderField, $this->view->orderDir)

				->paginate('survey sy', $this->view->currentPage, ['sy.*', 'sry.*', 'sy.id survey_id', 'sy.created_at survey_created_at', 'u.name manager_name', 'u.surname manager_surname', 'sts.survey_label survey_label', "(SELECT COUNT(*) FROM survey_attachments satt WHERE satt.survey_uuid LIKE sy.code) attach_count"]);

				

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

				foreach($this->view->survey as $index => $item) {

					if (($item['manager_id'] == $this->user->getUserId()) || $this->user->is([ADMIN_ROLE_ID, GLOBAL_MANAGER_ID])) {

						$this->view->survey[$index]['extra_buttons'] = true;

					} else {

						$this->view->survey[$index]['extra_buttons'] = false;

					}

				}

			}

			

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

			

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

			

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

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

		}

		

		public function surveyEdit() {

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

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

			}

			

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

			

			$this->view->id = $id;

			$op_label = $id == 0 ? _('New') : _('Edit');

			

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

			

			//Manager clinical center

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

			$cc = $this->db

				->where('ucct.user_id', $this->user->getUserId())

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

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

				->getOne('users_clinical_centers_to ucct', 'ucct.center_id, cc.description');

				

			if (isset($cc['center_id'])) {

				$this->view->manager_cc = $cc;

			}

			

			$survey_types = $this->db->where('status', 1)->where('center_id', $cc['center_id'])->orderBy('survey_label', 'asc')->get('survey_types');

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

			if (is_array($survey_types)) {

				foreach($survey_types as $item) {

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

				}

			}

			

			$this->view->userData = $this->db

				->where('sy.id', $id)

				->join('survey_registry sry', 'sry.survey_id=sy.id', 'INNER')

				->getOne('survey sy', 'sy.*, sry.*, sy.id survey_id');

			

			$this->actionTitle = _('Survey').' : '.$op_label;

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

		}

		

		//Survey saved and sent by Manager

		public function surveySave() {

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

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

			}

			

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

			$survey_id = $data['id']['value'];

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

			

			/*$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'];*/

			

			//Clinical center documents

			$documents = $this->db->where('center_id', $center_id)->get('clinical_center_documents');

			

			if ($center_id < 1) {

				return $this->setRawJsonResponse('err', "Impossibile inviare la scheda, il centro clinico dell'utente corrente non è valido.");

			}

			

			if (empty($documents)) {

				return $this->setRawJsonResponse('err', "Impossibile inviare la scheda, il centro clinico dell'utente corrente non è provvisto di documenti validi (testo e-mail per i pazienti, informativa sulla privacy, ecc.)");

			}

			

			if (trim($data['name']['value']) == '') {

				return $this->setRawJsonResponse('err', _('Please provide the Name'), ['class'=>$data['name']['class']]);

			}

			

			if (trim($data['surname']['value']) == '') {

				return $this->setRawJsonResponse('err', _('Please provide the Surname'), ['class'=>$data['surname']['class']]);

			}

			

			if (trim($data['birthdate']['value']) == '') {

				return $this->setRawJsonResponse('err', _('Birthdate is required'), ['class'=>$data['birthdate']['class']]);

			}

			

			if (trim($data['sex']['value']) == '') {

				return $this->setRawJsonResponse('err', _('Please provide the Sex'), ['class'=>$data['sex']['class']]);

			}

			

			if (strtotime($data['birthdate']['value']) > time()) {

				return $this->setRawJsonResponse('err', _('Birthdate cannot be in the future'), ['class'=>$data['birthdate']['class']]);

			}

			

			if (!$this->utility->validateEmail($data['email']['value'])) {

				return $this->setRawJsonResponse('err', _('E-mail is required and must be a valid address'), ['class'=>$data['email']['class']]);

			}

			

			if (trim($data['phone']['value']) == '') {

				return $this->setRawJsonResponse('err', _('Phone is required'), ['class'=>$data['phone']['class']]);

			}

			

			if ((int)$data['survey_type']['value'] == 0) {

				return $this->setRawJsonResponse('err', _('Survey types is required'), ['class'=>$data['survey_type']['class']]);

			}

			

			$survey_email = null;

			$email_subject = null;

			$survey_privacy = null;

			

			foreach($documents as $document) {

				switch($document['ducument_type']) {

					case 'recipient_mail':

						$survey_email = $document['document_file'];

						$email_subject = $document['document_subject'];

					break;

					

					case 'privacy':

						$survey_privacy = $document['document_file'];

					break;

				}

			}

			

			$email_file = RESOURCE_DIR.'survey/it/documents/centers/'.$center_id.'/'.$survey_email;

			$privacy_file = RESOURCE_DIR.'survey/it/documents/centers/'.$center_id.'/'.$survey_privacy;

			

			if (!file_exists($email_file) || !file_exists($privacy_file)) {

				return $this->setRawJsonResponse('err', "Impossibile inviare la scheda, i testi associati al centro clinico corrente non sono validi.");

			}

			

			

			/*if ($bpMax > 250) {

				return $this->setRawJsonResponse('err', _("Maximum Blood Pressure is too high."), ['class'=>$data['request_bp_max']['class']]);

			}

			

			if ($bpMin > 250) {

				return $this->setRawJsonResponse('err', _("Minimum Blood Pressure is too high."), ['class'=>$data['request_bp_min']['class']]);

			}

			

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

				if ($bpMin > $bpMax) {

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

				}

			}

			

			if ($heartRate > 250) {

				return $this->setRawJsonResponse('err', _("Heart Rate cannot be higher then 250 bpm."), ['class'=>$data['request_heart_rate']['class']]);

			}

			

			if ($oxygenSaturation > 100) {

				return $this->setRawJsonResponse('err', _("Oxygen Saturation cannot be higher than 100%."), ['class'=>$data['request_oxy_sat']['class']]);

			}*/

			

			$survey_code = strtoupper($this->getGUID());

			

			if ($survey_id == 0) {

				$survey_id = $this->db->insert('survey', [

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

					'type_id'=>$data['survey_type']['value'],

					'code'=>$survey_code,

					//'bp_min'=>$bpMin,

					//'bn_max'=>$bpMax,

					//'hrate'=>$heartRate,

					//'oxsat'=>$oxygenSaturation,

					'notes'=>trim(strip_tags($data['request_medremarks']['value'])),

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

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

				]);

			} else {

				$this->db->where('id', $survey_id)->update('survey', [

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

					'type_id'=>$data['survey_type']['value'],

					'email_failure'=>0,

					'opened_recipient'=>0,

					'aswered_recipient'=>0,

					'remote_added'=>0,

					//'bp_min'=>$bpMin,

					//'bn_max'=>$bpMax,

					//'hrate'=>$heartRate,

					//'oxsat'=>$oxygenSaturation,

					'notes'=>trim(strip_tags($data['request_medremarks']['value'])),

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

				]);



				$code_result = $this->db->where('id', $survey_id)->getOne('survey', 'code');

				

				if (isset($code_result['code'])) {

					$survey_code = $code_result['code'];

				}

			}

			

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

				'survey_id'=>$survey_id,

				'name'=>trim($data['name']['value']),

				'surname'=>trim($data['surname']['value']),

				'sex'=>$data['sex']['value'],

				'birthdate'=>$data['birthdate']['value'],

				'email'=>strtolower($data['email']['value']),

				'phone'=>trim($data['phone']['value']),

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

			]);

			

			$survey_domain = $this->config['settings']['sportellocura']['domain'];

			$survey_link = $survey_domain.'#/survey/'.$survey_code;

			$string_body = file_get_contents($email_file);



			$tmp_body = vsprintf($string_body, [trim($data['name']['value']), trim($data['surname']['value']), $survey_link]);

			$html_mail_body = $this->partial('Message/Email/survey-template', ['body'=>$tmp_body, 'email_title'=>$email_subject]);

			

			$this->setMessageQueue($email_subject, $html_mail_body, $data['email']['value'], $survey_id);

			

			return $this->setRawJsonResponse('ok', "Scheda inviata correttamente.", ['log'=>[]], ['button'=>'goto', 'destination'=>'survey-list/'.time().'/created_at/desc/1']);		

		}

		

		public function getSurveyEmptyForm() {

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

			$html = '';

			

			

			if ($type_id > 0) {

				

				$type = $this->db->where('id', $type_id)->getOne('survey_types');

				

				$this->setSurveyForm($type['survey_lang'], $type['survey_tag'], []);

				

				$html = $this->partial('Survey/form');

			}

			

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

		}

		

		//Ajax for modal preview

		public function getSurveyAnswers() {

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

			$attachs = [];

			$survey_data = [];

			$html = null;

			

			$survey = $this->db

				->join('survey_registry sr', 'sr.survey_id=s.id')

				->where('s.id', $id)

				->getOne('survey s', 's.code, s.bp_min, s.bn_max, s.hrate, s.oxsat, s.notes, s.json_answers, sr.name, sr.surname, sr.birthdate, sr.email, sr.phone');

			

			if (isset($survey['code'])) {

				$survey_data = json_decode($survey['json_answers'], true);

				$attachs = $this->db->where('survey_uuid', $survey['code'], 'LIKE')->get('survey_attachments');

			}

			

			$html = $this->partial('Survey/survey-list-preview', ['survey'=>$survey, 'data'=>$survey_data, 'attachs'=>$attachs]);

			

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

		}

		

		//Ajax

		public function sendbackSurveyMessage() {

			

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

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

			}

			

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

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

			

			if (!is_null($survey_uuid)) {

			$update1 = $this->db

				->where('code', $survey_uuid)

				->update('survey', [

					'json_answers'=>NULL,

					'opened_recipient'=>0,

					'aswered_recipient'=>0,

					'aswered_date'=>NULL,

					'remote_added'=>0,

					'remote_added_date'=>NULL,

					'remote_report_created'=>0,

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

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

				]);

				

				if ($update1) {

					$update2 = $this->db

						->where('msg_body', '%'.$survey_uuid.'%', 'LIKE')

						->where('msg_sent', 1)

						->update('survey_queue', [

							'msg_sent'=>0,

							'msg_sent_date'=>NULL

						]);

						

						if ($update2) {

							

							//Log

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

								'survey_uuid'=>$survey_uuid,

								'recipient'=>$recipient,

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

							]);

							

							return $this->setRawJsonResponse('ok', 'Scheda inviata correttamente.');

						} else {

							return $this->setRawJsonResponse('err', _('Update error (Cod. 2)'));

						}

						

				} else {

					return $this->setRawJsonResponse('err', _('Update error (Cod. 1)'));

				}

				

				

			} else {

				return $this->setRawJsonResponse('err', _('Data not valid'), []);

			}

			

		}

		

		//Ajax

		public function deleteSurvey() {

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

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

			}

			

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

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

			

			$attach = $this->db->where('survey_uuid', $survey_uuid)->get('survey_attachments');

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

				foreach($attach as $item) {

					@unlink(ATTACH_DIR.$item['uuid']);

					$this->db->where('uuid', $item['uuid'])->delete('survey_attachments');

				}

			}

			

			$registry = $this->db->where('survey_id', $survey_id)->delete('survey_registry');

			$sentback_log = $this->db->where('survey_uuid', $survey_uuid)->delete('survey_sentback_log');

			

			if ($this->db->where('code', $survey_uuid)->delete('survey')) {

				return $this->setRawJsonResponse('ok', _('Survey successfully deleted'));

			} else {

				return $this->setRawJsonResponse('err', _('Unable to delete the survey'));

			}

		}

		

		private function setSurveyForm($survey_lang, $survey_tag, $survey=[]) {

				$structure = json_decode(file_get_contents(RESOURCE_DIR.'survey/'.$survey_lang.'/'.$survey_tag.'.json'), true);

				$global_fields = json_decode(file_get_contents(RESOURCE_DIR.'survey/'.$survey_lang.'/global.json'), true);

				

				$this->view->structure = array_merge($structure, $global_fields);

				

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

					$this->view->survey_patient_string = strip_tags($survey['patient_surname']).' '.strip_tags($survey['patient_name']).', '.$this->helper->getDateString($survey['partient_bday'], false).', '.$survey['patient_email'];

				} else {

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

				}

		}

	}