<?php
	class Helper {

		private $utility;

		function __construct($utility=null) {
			$this->utility = $utility;
		}

		public function setHash($destination='') {
			return $this->utility->setHash($destination);
		}

		public function setSortableCol($label='', $destination, $field, $dir) {

			$currentField = isset($_POST['orderField']) ? $_POST['orderField'] : null;
			$currentDir = isset($_POST['orderDir']) ? $_POST['orderDir'] : null;
			$pageNumb = isset($_POST['pageNumb']) ? $_POST['pageNumb'] : 1;
			$icon = '';

			if ($field == $currentField) {
				if ($currentDir == 'desc') $dir = 'asc'; else $dir = 'desc';

				if ($dir == 'asc')
					$icon = '<span class="icon-menu4 opacize"></span>';
				else
					$icon = '<span class="icon-menu3 opacize"></span>';
			}

			return '<a href="'.$this->setHash($destination.'/'.$field.'/'.$dir.'/'.$pageNumb).'">'.$label.'</a> '.$icon;
		}

		public function wrapVector($vector, $start, $end='', $space=' ') {
			$string = '';

			if (is_array($vector)) {
				foreach($vector as $value) {
					$string .= $start.$value.$end.$space;
				}
			}

			return $string;
		}

		public function setCommaList($vector=[], $sep=', ') {
			return is_array($vector) ? implode($sep, $vector) : '';
		}

		public function dateIntervalString($date) {
			$start  = date_create($date);
			$end 	= date_create();
			$diff  	= date_diff($start, $end);

			if ($diff->y > 0) {
				if ($diff->m > 0) {
					return vsprintf(_('%s<sup>y</sup> %s<sup>mo</sup>'), [$diff->y, $diff->m]);
				} else {
					return vsprintf(_('%s<sup>y</sup>'), [$diff->y]);
				}
			}

			if ($diff->y <= 0 && $diff->m > 0) {
				if ($diff->d > 0) {
					return vsprintf(_('%s<sup>mo</sup> %s<sup>d</sup>'), [$diff->m, $diff->d]);
				} else {
					return vsprintf(_('%s<sup>mo</sup>'), [$diff->m]);
				}
			}

			if ($diff->y <= 0 && $diff->m <= 0 && $diff->d > 0) {

				if ($diff->h > 0) {
					return vsprintf(_('%s<sup>d</sup> %s<sup>h</sup>'), [$diff->d, $diff->h]);
				} else {
					return vsprintf(_('%s<sup>d</sup>'), [$diff->d]);
				}
			}

			if ($diff->y <= 0 && $diff->m <= 0 && $diff->d <= 0) {

				if ($diff->h > 0) {
					return vsprintf(_('%s<sup>h</sup> %s<sup>mi</sup>'), [$diff->h, $diff->i]);
				} else {

					if ($diff->i > 0) {
						return vsprintf(_('%s<sup>mi</sup>'), [$diff->i]);
					}
				}
			}

			return vsprintf(_('%s<sup>s</sup>'), [$diff->s]);
		}

		public function setYesNo($number=0) {
			return $number==1 ? _('Yes') : _('No');
		}

		public function getDateString($date=null, $withTime=true) {

			if ($withTime) {
				$dateString = '%d/%b/%Y %H.%M';
			} else {
				$dateString = '%d/%b/%Y';
			}

			if (!empty($date))
				return strftime($dateString, strtotime($date));
			else
				return '';
		}

		public function getTimeString($date=null, $sep='.', $withSecs=false) {
			$secs = $withSecs ? $sep.'s' : '';
			return date('H'.$sep.'i'.$secs, strtotime($date));
		}

		public function getJsonTranslation($jsonField, $langCode=null, $default='') {
			$data = json_decode($jsonField, true);
			return is_array($data) && isset($data[$langCode]) ? $data[$langCode] : $default;
		}

		public function getRoleNameInList($string='', $roleList=[]) {
			$string = '{'.$string.'}';
			$array = json_decode($string, true);
			$list = [];

			if (is_array($array)) {
				foreach($array as $roleId => $roleName) { //Role name is in English because of the query in usersController::usersList()
					if (isset($roleList[$roleId])) {
						$list[] = $roleList[$roleId]['name'];
					}
				}
			}

			return !empty($list) && is_array($list) ? implode(', ', $list) : null;
		}

		public function requestSubject($data=[]) {
			$surname = isset($data['patientSurname']) ? $this->cleanText($data['patientSurname']) : '';
			$name = isset($data['patientName']) ? $this->cleanText($data['patientName']) : '';
			$years = isset($data['ageYears']) ? (int)$data['ageYears'] : 0;
			$months = isset($data['ageMonths']) ? (int)$data['ageMonths'] : 0;
			$days = isset($data['ageDays']) ? (int)$data['ageDays'] : 0;
			$gender = isset($data['patientGender']) ? trim($data['patientGender']) : '';
			$anonymous = isset($data['anonymous']) ? $data['anonymous'] : 0;

			$age = $months > AGE_MONTH_LIMIT ? $years : $months; //AGE_MONTH_LIMIT is in mainController

			//$ageString = $months > AGE_MONTH_LIMIT ? vsprintf(_('%s y.'), [$years]) : vsprintf(_('%s m.'), [$months]);

			if ($months > AGE_MONTH_LIMIT) {
				$ageString = vsprintf(_('%s y.'), [$years]);
			} else {
				if ($months > 0) {
					//if ($days == 0) {
						$ageString = vsprintf(_('%s m.'), [$months]);
					//} else {
						//$ageString = vsprintf(_('%s m. %s d.'), [$months, $days]);
					//}
				} else {
					$ageString = vsprintf(_('%s d.'), [$days]);
				}
			}

			$genderLabel = $gender == 'm' ? strtolower(_('Mal.'))[0] : strtolower(_('Fem.'))[0];
			if ($gender == '') $genderLabel = ''; //Overwrite the value if no gender is passed

			if ($anonymous == 0) {
				$fullName = '<span class="badge badge-secondary">'.$this->setDottedFullname($name, $surname, false).'</span>';
			} else {
				$fullName = '<span class="badge badge-light">'.$this->getObfuscateString($name.' '.$surname).'</span>';
			}

			return $fullName.' <span class="badge badge-secondary">'.$ageString.'</span> <span class="badge badge-dark">'.$genderLabel.'</span>';
		}

		public function patient_age($data=[]) {
			$years = isset($data['ageYears']) ? (int)$data['ageYears'] : 0;
			$months = isset($data['ageMonths']) ? (int)$data['ageMonths'] : 0;
			$days = isset($data['ageDays']) ? (int)$data['ageDays'] : 0;
			$anonymous = isset($data['anonymous']) ? $data['anonymous'] : 0;

			$age = $months > AGE_MONTH_LIMIT ? $years : $months; //AGE_MONTH_LIMIT is in mainController

			if ($months > AGE_MONTH_LIMIT) {
				$ageString = vsprintf(_('%s y.'), [$years]);
			} else {
				if ($months > 0) {
						$ageString = vsprintf(_('%s m.'), [$months]);
				} else {
					$ageString = vsprintf(_('%s d.'), [$days]);
				}
			}

			return $ageString;
		}

		public function getObfuscateString($string='') {
			//return str_repeat('&#9679;', strlen($string));
			return str_repeat('&#9679;', 3);
		}

		//TODO: some cleaning operations
		public function cleanText($text='') {
			//return utf8_encode($text);
			return $text;
		}

		public function hashtag($text) {
			return preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '<a class="badge badge-info" href="/requests-edit/'.time().'/$1/view/hashtag/my/hashtag/created_at/desc/1">#$1</a>', $text);

		}

		public function linkfy($label='', $href='', $class="", $target='_self', $meta='') {
			return '<a href="'.$href.'" class="'.$class.'" target="'.$target.'" '.$meta.'>'.$label.'</a>';
		}

		public function getExtension($file) {
			return pathinfo($file, PATHINFO_EXTENSION);
		}

		public function getPreviewType($fileName=null) {
			$images = ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'tif'];
			$videos = ['mp4', 'm4p', 'm4v', 'mov', 'mpg', 'mpeg', 'mp2', 'mpeg', 'mpe', 'mpv', 'webm', 'ogv', 'ogg'];
			$audio = ['mp3', 'mpa', 'aac', 'oga'];
			$files = ['pdf'];
			$dicom = ['dcm', 'DCM'];

			if (!is_null($fileName)) {
				$ext = strtolower($this->getExtension($fileName));

				if (in_array($ext, $images)) {
					return 'images';
				}

				if (in_array($ext, $videos)) {
					return 'video';
				}

				if (in_array($ext, $audio)) {
					return 'audio';
				}

				if (in_array($ext, $files)) {
					return 'iframe';
				}

				if (in_array($ext, $dicom)) {
					return 'dicom';
				}
			}

			return 'download';
		}

		public function getPreviewLink($attach=[], $showUser=true, $wrapStart=null, $wrapEnd=null, $linkClass=null) {
			$previewType = $this->getPreviewType($attach['file_name']);
			$attachId = $attach['id'];
			$attachTitle = $attach['file_title'];
			$attachExt = $attach['file_ext'];
			$attachSize = $attach['file_size'];
			$titleLength = 20;
			$wrapStart = is_null($wrapStart) ? '<div class="attach-row">' : $wrapStart;
			$wrapEnd = is_null($wrapEnd) ? '</div><div class="clearfix"><small class="text-muted float-right mr-1"><i>'.$this->byte_convert($attachSize).'</i></small><small class="text-muted float-right"><i>'.strtoupper($attachExt).'</i> -&nbsp;</small></div></div>' : $wrapEnd;

			$user = $showUser ?  '<div class="clearfix"><small class="text-muted">'.$attach['name'].' '.$attach['surname'].' <span class="float-right">'.$this->getTimeString($attach['created_at']).'</span></small></div><div class="clearfix">' : '';

			if ($previewType != 'download') {

				switch ($previewType) {
					case 'images':
						return $wrapStart.$user.'<a data-options=\'{"hash":false}\' data-toggle="tooltip" data-placement="top" title="'.$attach['file_title'].'.'.$attach['file_ext'].'" data-fancybox="images" data-caption="'.htmlspecialchars($this->setDottedFullname($attach['name'], $attach['surname'], false)).' - '.htmlspecialchars($attachTitle).' - '.$this->getDateString($attach['created_at']).'" data-src="/downlaod/?attach_id='.$attachId.'" href="#" class="'.$linkClass.'"><span class="icon-file-picture"> </span>'.$this->truncate($attachTitle, $titleLength).'</a>'.$wrapEnd;
					break;

					case 'video':
					case 'audio':
						return $wrapStart.$user.'<a data-options=\'{"hash":false}\' data-toggle="tooltip" data-placement="top" title="'.$attach['file_title'].'.'.$attach['file_ext'].'" data-fancybox data-type="iframe" data-src="/downlaod/?attach_id='.$attachId.'" href="#" class="'.$linkClass.'"><span class="icon-file-picture"></span> '.$this->truncate($attachTitle, $titleLength).'</a>'.$wrapEnd;
					break;

					case 'dicom':
						return $wrapStart.$user.'<a data-options=\'{"hash":false}\' data-fancybox data-type="iframe" data-src="/dicom/index.php?attach_id='.$attachId.'" href="#" class="'.$linkClass.'"><span class="icon-file-picture"></span> '.$attachTitle.'</a>'.$wrapEnd;
					break;

					default:
						return $wrapStart.$user.'<a data-options=\'{"hash":false}\' data-toggle="tooltip" data-placement="top" title="'.$attach['file_title'].'.'.$attach['file_ext'].'" data-fancybox data-type="iframe" data-src="/downlaod/?attach_id='.$attachId.'" href="#" class="'.$linkClass.'"><span class="icon-download3"></span> '.$this->truncate($attachTitle, $titleLength).'</a>'.$wrapEnd;
				}
			} else {
				return $wrapStart.$user.'<a class="download '.$linkClass.'" data-toggle="tooltip" data-placement="top" title="'.$attach['file_title'].'.'.$attach['file_ext'].'" data-forcedownload="1" href="/downlaod/?attach_id='.$attachId.'"><span class="icon-download3"></span> '.$this->truncate($attachTitle, $titleLength).'</a>'.$wrapEnd;
			}
		}

		public function getDocName($attach=[], $showUser=true, $wrapStart=null, $wrapEnd=null, $linkClass=null) {
			$previewType = $this->getPreviewType($attach['file_name']);
			$attachId = $attach['id'];
			$attachTitle = $attach['file_title'];
			$attachExt = $attach['file_ext'];
			$attachSize = $attach['file_size'];
			// $titleLength = 20;
			$wrapStart = is_null($wrapStart) ? '<div class="attach-row">' : $wrapStart;
			$wrapEnd = is_null($wrapEnd) ? '<small class="float-right text-muted">'.$this->byte_convert($attachSize).' - '.strtoupper($attachExt).'</small></div>' : $wrapEnd;

			$user = $showUser ?  '<div class="clearfix"><small class="text-muted">'.$attach['name'].' '.$attach['surname'].' <span class="float-right">'.$this->getTimeString($attach['created_at']).'</span></small></div>' : '';

			if ($previewType != 'download') {

				switch ($previewType) {
					case 'images':
						return $wrapStart.$user.'<a data-options=\'{"hash":false}\' data-fancybox="images" data-caption="'.htmlspecialchars($this->setDottedFullname($attach['name'], $attach['surname'], false)).' - '.htmlspecialchars($attachTitle).' - '.$this->getDateString($attach['created_at']).'" data-src="/downlaod/?attach_id='.$attachId.'" href="#" class="'.$linkClass.'"><span class="icon-file-picture"> </span>'.$attachTitle.'.'.$attachExt.'</a>'.$wrapEnd;
					break;

					case 'dicom':
						return $wrapStart.$user.'<a data-options=\'{"hash":false}\' data-fancybox data-type="iframe" data-src="/dicom/dicom.php?attach_id='.$attachId.'" href="#" class="'.$linkClass.'"><span class="icon-file-picture"></span> '.$attachTitle.'</a>'.$wrapEnd;
					break;

					case 'video':
					case 'audio':
						return $wrapStart.$user.'<a data-options=\'{"hash":false}\' data-fancybox data-type="iframe" data-src="/downlaod/?attach_id='.$attachId.'" href="#" class="'.$linkClass.'"><span class="icon-file-picture"></span> '.$attachTitle.'</a>'.$wrapEnd;
					break;

					default:
						return $wrapStart.$user.'<a data-options=\'{"hash":false}\' data-fancybox data-type="iframe" data-src="/downlaod/?attach_id='.$attachId.'" href="#" class="'.$linkClass.'"><span class="icon-download3"></span> '.$attachTitle.'</a>'.$wrapEnd;
				}
			} else {
				return $wrapStart.$user.'<a class="download '.$linkClass.'" data-forcedownload="1" href="/downlaod/?attach_id='.$attachId.'"><span class="icon-download3"></span> '.$attachTitle.'</a>'.$wrapEnd;
			}
		}

		public function truncate($string=null, $len=15, $ell='...') {
			if (strlen($string) >= $len) {
				return trim(substr($string, 0, $len)).$ell;
			} else {
				return $string;
			}
		}

		public function formatNumber($float=0, $decimals=0) {
			return $this->utility->formatNumber($float, $decimals);
		}

		public function replaceLinks($string='', $class='') {
			return preg_replace("~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~","<a href=\"\\0\" class=\"$class\">\\0</a>", $string);
		}

		public function setRequestStatus($label='') {
			switch(trim($label)) {
				case 'pending':
					return '<span class="badge badge-light text-muted"><i>'._('Sending').'...</i></span>';
				break;

				case 'draft':
					return '<span class="badge badge-light">'._('Draft').'</span>';
				break;

				case 'opened':
					return '<span class="badge badge-secondary">'._('Opened').'</span>';
				break;

				case 'referted':
					return '<span class="badge badge-success">'._('Answered').'</span>';
				break;

				case 'reopened':
					return '<span class="badge badge-danger">'._('Reopened').'</span>';
				break;

				case '! referted':
					return '<span class="badge badge-warning">'._('Partially answered').'</span>';
				break;

				default:
					return '<span class="badge badge-light">'.$label.'</span>';
			}
		}

		public function getRequestExam($exams=[], $label='', $examType='') {
			$html = '';
			$examItem = [];

			$arrayItem = isset($exams[$label]) ? $exams[$label] : [];

			if (!empty($arrayItem)) {
				foreach($arrayItem as $examId => $examInfo) {
					if ($examInfo['type'] == $examType) {
						$examItem = $examInfo;
						break;
					}
				}

				if (!empty($examItem)) {
					$examLabel = $examItem['description'];
					$examId = $examItem['id'];
					$examType = $examItem['type'];
					$children = $examItem['children'];
					$checked = $examItem['checked'] ? 'checked' : '';

					$checkbox = '<input type="checkbox" name="data[exam_'.$examType.'][value][]" class="request-exam-checkbox exam-'.$examType.'" data-label="%s" data-checkboxclass="exam-'.$examType.'" data-wizardcontainer="exam-wrapper-'.$examType.'" id="exam-%s" value="%s" %s> ';

					$html .= '<ul>';
						$html .= '<li class="list-no-type"><label>';
							$html .= empty($children) ? vsprintf($checkbox, [$examLabel, $examId, $examId, $checked]) : '';
							//$html .= vsprintf($checkbox, [$examLabel, $examId, $examId, $checked]);
							$html .= $examLabel;
						$html .= '</label>';
						if (is_array($children) && !empty($children)) {
							$html .= '<ul>';
								foreach($children as $childId => $childInfo) {
									$checked = $childInfo['checked'] ? 'checked' : '';
									$html .= '<li class="list-no-type">'.vsprintf($checkbox, [$examLabel.' / '.$childInfo['description'], $childId, $childId, $checked]).$childInfo['description'].'</li>';
								}
							$html .= '</ul>';
						}
					$html .= '</li></ul>';
				}
			}

			return $html;
		}

		public function getUserFlag($userCountryCode=null, $width=50) {
			$imageUrl = '/images/flags/svg/'.strtolower($userCountryCode).'.svg';
			$imagePath = PUBLIC_HTML.$imageUrl;

			if (file_exists($imagePath)) {
				return '<img src='.$imageUrl.' width="'.$width.'" style="vertical-align:middle;">';
			}

			return null;
		}

		public function setDottedFullname($name, $surname, $nameFirst=true) {
				$nameParts = explode(' ', trim($name));
				$chars = [];

				foreach($nameParts as $part) {
					if (isset($part[0])) $chars[] = strtoupper($part[0]);
				}

				if ($nameFirst)
					return implode('. ', $chars).'. '.ucwords(strtolower($surname));
				else
					return ucwords(strtolower($surname)).' '.implode('. ', $chars).'.';
		}


		public function setAvatarView($avatarImagePath, $params=[]) {
			global $config;
			$timestamp = isset($params['timestamp']) ? $params['timestamp'] : time();
			$strTimestamp = "?t=$timestamp";
			$cssClass = isset($params['class']) ? $params['class'] : 'list-avatar';
			$cssId = isset($params['cssId']) ? $params['cssId'] : null;
			$strCssId = !is_null($cssId) ? 'id="'.$cssId.'"' : '';
			$status = isset($params['status']) ? (int)$params['status'] : 1;

			if ($status == 0) {
				$avatarImagePath = $config['settings']['avatar-uri'].$config['settings']['avatar-default'];
				$strTimestamp = '';
			}

			return '<div class="'.$cssClass.'" '.$strCssId.' style="background-image: url('.$avatarImagePath.$strTimestamp.');"></div>';
		}


		public function byte_convert($number = 0, $precision = 1){
			if( !is_numeric($number) ){
				return false;
			}
			$unit = ''; //suffisso dell'unità di misura
			//terabyte
			if($number >= 1000000000000){
				$number = round($number / 1099511627776, $precision);
				$unit = 'TB';
			//gigabyte
			}elseif($number >= 1000000000){
				$number = round($number / 1073741824, $precision);
				$unit = 'GB';
			//megabyte
			}elseif($number >= 1000000){
				$number = round($number / 1048576, $precision);
				$unit = 'MB';
			//kilobyte
			}elseif($number >= 1000){
				$number = round($number / 1024, $precision);
				$unit = 'KB';
			//byte
			}else{
				$unit = 'byte';
				return number_format($number).' '.$unit;
			}
			return number_format($number, $precision).' '.$unit;
		}

	}
