<?php
	class mainController extends Controller {
		
		public $userGroupId = 0;
		public $helper;
		public $notification;
				
		function __construct() {
			parent::__construct();
			
			$this->helper = new Helper($this->utility);
			$this->notification = new Notification($this, 0); //2 for debug
			$this->userGroupId = $this->user->getUserField('userGroupId');
									
			$groupInfoKey = 'group:info:'.$this->userGroupId;
			$groupInfoCache = $this->memoryCache->read($groupInfoKey);
			if (is_null($groupInfoCache)) {
				$this->groupInfo = $this->db->where('id', $this->userGroupId)->getOne('users_groups');
				$this->memoryCache->write($groupInfoKey, $this->groupInfo, '+10 years');
			} else {
				$this->groupInfo = $groupInfoCache;
			}
			$this->view->groupName = $this->groupInfo['group_name'];
			$this->view->groupId = $this->groupInfo['id'];
			$this->view->currentUserId = $this->user->getUserId();
			
			define('STATUS_TECH_NAME', _('Technician'));
			
			define('AGE_MONTH_LIMIT', 18);

			if($_SERVER['REMOTE_ADDR'] != '195.181.176.98') {
				//exit();
			}
												
		}
		
		public function beforeRender($content=null) {
			
			return $content;
			
			//TODO: check to groupId (?)
			//if ((int)$this->userGroupId < 1) {
			//}
			
			if (!$this->user->disclaimerAccepted()) {
				$this->viewDir = 'Main';
				return $this->setView('indexNoPrivacy');
			} else {
				return false;
			}
		}
		
		public function convertOldUserLang($checkLang='') {
			
			if (strlen($checkLang) == 2)  return $checkLang;
			$map = ['ENGLISH'=>'en', 'ITALIANO'=>'it', 'PORTUGUES'=>'pt', 'FRANCAIS'=>'fr'];
			
			return isset($map[$checkLang]) ? $map[$checkLang] : $this->config['settings']['default-lang'];
		}
		
		public function getClinicalCenterCountries($groupByContinent=false) {
			$this->db->where('cc.group_id', $this->userGroupId)
				->join('countries c', 'c.country_iso2_code=cc.country_code', 'INNER')
				->join('continents cn', 'cn.code=cc.continent_code', 'INNER')
				->groupBy('c.country_iso2_code');
												
				if ($groupByContinent) {
					$this->db
						->orderBy('cn.name', 'asc')
						->orderBy('c.country_name', 'asc');
				} else {
					$this->db->orderBy('c.country_name', 'asc');
				}
						
				$results = $this->db->get('clinical_centers cc', null, ['c.country_iso2_code country_code', 'c.country_name country_name', 'cn.code continent_code', 'cn.name continent_name', '(SELECT COUNT(*) AS total FROM clinical_centers WHERE clinical_centers.country_code=c.country_iso2_code AND clinical_centers.group_id='.$this->userGroupId.') cc_count', '(SELECT COUNT(*) AS total FROM clinical_centers WHERE clinical_centers.continent_code=cn.code AND clinical_centers.group_id='.$this->userGroupId.') cn_count']);
									
			if ($groupByContinent) {
				$grouped = [];
				if (is_array($results)) {
					foreach($results as $result) {
						$grouped[$result['continent_code']]['name'] = $result['continent_name'];
						$grouped[$result['continent_code']]['count'] = $result['cn_count'];
						$grouped[$result['continent_code']]['list'][] = $result;
					}
				}
				return $grouped;
			}
			
			return $results;
		}
		
		public function getUserClinicalCenters($userId, $roleId=0) {
			
			$reindexedResults = [];
			$key = 'clinical:center:'.$userId.':'.$roleId;
			$value = $this->memoryCache->read($key);
			
			$value = null; //Non usare la cache
						
			if (is_null($value)) {
				$results = $this->db
							->where('ucct.user_id', $userId)
							->where('ucct.role_id', $roleId)
							//->where('cc.group_id', $this->userGroupId)
							->join('clinical_centers cc', 'cc.id=ucct.center_id', 'INNER')
							->orderBy('cc.description', 'asc')
							->get('users_clinical_centers_to ucct', null, ['cc.id', 'cc.description', 'cc.address', 'cc.anonymize', 'cc.has_remote_visit', 'cc.notes']);
				
				//Assign the Clinical Center id to the array index
				if (is_array($results)) {
					foreach($results as $result) {
						$reindexedResults[$result['id']] = $result;
					}
				}
				
				$this->memoryCache->write($key, $reindexedResults, '+10 years');
				
			} else {
				$reindexedResults = $value;
			}
						
			return $reindexedResults;
		}
		
		public function getUserMedicalSpecialties($userId=0) {
			
			$reindexedResults = [];
			$key = 'medical:specialties:'.$userId;
			$value = $this->memoryCache->read($key);
									
			if (is_null($value)) {
				$results = $this->db
							->where('umst.user_id', $userId)
							->join('users_medical_specialties ms', 'ms.id=umst.specialty_id', 'INNER')
							->orderBy('ms.description', 'asc')
							->get('users_medical_specialties_to umst', null, ['ms.id', 'ms.description']);
										
				//Assign the Medical Specialty id to the array index
				if (is_array($results)) {
					foreach($results as $result) {
						$reindexedResults[$result['id']] = $result;
					}
				}
				
				$this->memoryCache->write($key, $reindexedResults, '+10 years');
				
			} else {
				$reindexedResults = $value;
			}
			
			return $reindexedResults;
		}
		
		public function getActiveMedicalSpecialtiesIdByGroupId($groupId=0) {
			$specialties = [];
			$results = $this->db
				->where('u.group_id', $groupId)
				->where('u.status', 1)
				->join('users u', 'u.id=umst.user_id', 'INNER')
				->groupBy('umst.specialty_id')
				->get('users_medical_specialties_to umst', null, ['umst.specialty_id']);
				
			if (is_array($results)) {
				foreach($results as $result) {
					$specialties[] = $result['specialty_id'];
				}
			}
			
			return $specialties;
		}
		
		public function getGUID(){
		    if (function_exists('com_create_guid')){
		        return com_create_guid();
		    }
		    else {
		        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
		        $charid = strtoupper(md5(uniqid(rand(), true)));
		        $hyphen = chr(45);// "-"
		        $uuid = 
		        	substr($charid, 0, 8).$hyphen.
		            substr($charid, 8, 4).$hyphen.
		            substr($charid,12, 4).$hyphen.
		            substr($charid,16, 4).$hyphen.
		            substr($charid,20,12);
		        return $uuid;
		    }
		}
		
		public function setMessageQueue($subject, $body, $recipient, $survey_id=0, $delay=null) {
			$this->db->insert('survey_queue', [
				'survey_id'=>$survey_id,
				'msg_subject'=>$subject,
				'msg_body'=>$body,
				'msg_recipient'=>$recipient,
				'msg_delay_at'=>$delay
			]);
		}
		
		public function canViewRemoteVisit() {
			
			$cc = [];
			if ($this->user->is(APPLICANT_ROLE_ID)) {
				$cc = $this->getUserClinicalCenters($this->user->getUserId(), APPLICANT_ROLE_ID);
				
				if (is_array($cc) && !empty($cc)) {
					foreach($cc as $item) {
						if ($item['has_remote_visit'] == 1) {
							return true;
						}
					}
				}
			}
			
			return false;
		}
		
		public function getSetting($key=null) {
			$value = $this->db->where('title', $key, 'LIKE')->getOne('settings');
			
			return isset($value[$key]) ? $value[$key] : false;
		}
		
		//TODO
		public function deleteUserCacheKeys($userId=0) {
			
		}
		
	}


