<?php
	class centerController extends mainController {

		function __construct() {
			parent::__construct();

			//To change for every Controllers
			$this->viewDir = 'Center';

			//$this->allow = [];

		}

		public function index(){

			if(!isset($this->user->getRoles()[ADMIN_ROLE_ID]))
				return $this->setRawJsonResponse('err', _('Access denied.'), [], ['button'=>'goto', 'destination'=>'dashboard']);

			$this->actionTitle = _("Clinical center");

			$user_id = $this->user->getUserId();
			$center_id = $this->getPost('center_id', 0);
			$this->view->centerId = $center_id;
			$this->view->isEditing = $center_id == 0 ? false : true;

			$center_data = null;
			if($this->view->isEditing){
				$center_data = $this->db->where('id', $center_id)->getOne('clinical_centers');
				if($center_data == null)
					return $this->setRawJsonResponse('err', 'Access denied.', [], ['button'=>'goto', 'destination'=>'dashboard']);
				// centerData['medical_specialties'] => [[index] => specialty_id]
				$center_data['medical_specialties'] = $this->db->where('center_id', $center_id)->getValue('clinical_center_medical_specialties_to', 'specialty_id', null);
			}

			$this->view->centerData = $center_data;

			$this->view->continents = array_merge([0=>['code'=>null, 'name'=>'...']], $this->db->get('continents'));
			if($this->view->isEditing){
				$this->view->countries = $this->db
					->orderBy('country_name', 'ASC')
					->where('continent_iso2_code', $center_data['continent_code'])
					->get('countries', null, ['country_iso2_code as code', 'country_name as name']);
			}

			$this->view->allSpecialties = $this->db
				->orderBy('description', 'ASC')
				->get('users_medical_specialties');  // [index] => [id, description, status]

			//$this->view->DEBUG = 'NULL';

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


		// Ajax function: dynamic loading of the Countries select by Continent
		public function filterCountries() {
			$continent_code = $this->getPost('continent_code', null);
			if($this->db->where('code', $continent_code)->getOne('continents') == null){
				return $this->setRawJsonResponse('err', $continent_code . ': ' . _('invalid continent code.'), [], []);
			}
			$countries = [];
			$countries_db = $this->db
				->orderBy('country_name', 'ASC')
				->where('continent_iso2_code', $continent_code)
				->get('countries', null, ['country_iso2_code as code', 'country_name as name']);
			foreach ($countries_db as $country) {
				$countries[$country['code']] = $country['name'];
			}
			return $this->setRawJsonResponse('ok', '', ['countries'=>$countries]);
		}


		// Main function for Clinical Center saving and updating
		public function centerSave(){
			// Check: only Administrator can save
			if(!isset($this->user->getRoles()[ADMIN_ROLE_ID]))
				return $this->setRawJsonResponse('err', _('Save denied.'), [], ['button'=>'goto', 'destination'=>'dashboard']);

			$now = date('Y-m-d H:i:s');
			$user_id = $this->user->getUserId();
			$data = $this->getPost('data', null);

			$center_id = $data['center_id']['value'];
			// Check: modify a clinical center only if exists
			if($center_id != 0 && $this->db->where('id', $center_id)->getOne('clinical_centers') == null)
				return $this->setRawJsonResponse('err', _('Save denied.'), [], ['button'=>'goto', 'destination'=>'dashboard']);

			$center_validate_data = [];
			$center_validate_data = $this->centerValidate($data);
			$specialties_validate_data = [];
			$devices_validate_data = [];

			$this->view->DEBUG = $center_validate_data;
			return $this->setJsonView('centerSave');

			if(isset($center_validate_data['ok'])){
				//unset($center_validate_data['ok']['center_id']);
				$specialties_validate_data = $center_validate_data['ok']['medical_specialties'];
				unset($center_validate_data['ok']['medical_specialties']);
				$center_validate_data['ok']['updated_by'] = $user_id;
				$center_validate_data['ok']['updated_at'] = $now;

				//$this->view->DEBUG = $center_validate_data;
				//return $this->setJsonView('centerSave');

				if($center_id == 0){  // INSERT
					$center_validate_data['ok']['created_by'] = $user_id;
					$center_validate_data['ok']['created_at'] = $now;
					$center_id = $this->db->insert('clinical_centers', $center_validate_data['ok']);
					if($center_id) return $this->setRawJsonResponse('ok', _('Clinical center created successfully.'), [], ['button'=>'goto', 'destination'=>'centers/'.time()]);
					else return $this->setRawJsonResponse('err', _('Clinical center insert error.'), [], ['button'=>'goto', 'destination'=>'centers/'.time()]);
				} else {  // UPDATE
					if($this->db->where('id', $center_id)->update('clinical_centers', $center_validate_data['ok']))
						return $this->setRawJsonResponse('ok', _('Clinical center updated successfully.'), [], ['button'=>'goto', 'destination'=>'centers/'.time()]);
					else return $this->setRawJsonResponse('err', _('Clinical center update error.'), [], ['button'=>'goto', 'destination'=>'centers/'.time()]);
				}
			}
			if(isset($center_validate_data['err'])){
				$err_class = isset($center_validate_data['err']['field-class']) ? ['class'=>$center_validate_data['err']['field-class']] : [];
				return $this->setRawJsonResponse('err', $center_validate_data['err']['err_msg'], $err_class);
			}

			// For debugging...
			// $this->view->DEBUG = 'DEBUG CONTENT';
			// return $this->setJsonView('centerSave');
			// return $this->setRawJsonResponse('ok', _('MESSAGGIO DI CONFERMA'), [], ['button'=>'goto', 'destination'=>'centers/'.time()]);
			// return $this->setRawJsonResponse('err', 'MESSAGGIO DI ERRORE del tipo <b>label</b>: required field', ['class'=>'field-CAMPO1']);
		}

		// Return an array
		//	[ok] => [field => value]
		//	[err] => [
		//		err_msg => error message formatted
		//		field-class => filed-FieldName to highlight the error on the page
		//	]
		private function centerValidate($form_data){
			$result = [];

			if($form_data['description']['value'] == null){
				$result['err']['err_msg'] = '<b>' . $form_data['description']['label'] . '</b>:' . _(' required field.');
				$result['err']['field-class'] = 'field-description';
				return $result;
			}
			if((int)$form_data['anonymize']['value'] != 0 && (int)$form_data['anonymize']['value'] != 1){
				$result['err']['err_msg'] = '<b>' . $form_data['anonymize']['label'] . '</b>:' . _(' invalid value.');
				$result['err']['field-class'] = 'field-anonymize';
				return $result;
			}
			if($form_data['continent_code']['value'] == null){
				$result['err']['err_msg'] = '<b>' . $form_data['continent_code']['label'] . '</b>:' . _(' required field.');
				$result['err']['field-class'] = 'field-continent_code';
				return $result;
			}
			if($this->db->where('code', $form_data['continent_code']['value'])->getOne('continents') == null){
				$result['err']['err_msg'] = _('Save denied. ') . $form_data['continent_code']['value'] . _(': invalid value.');
				$result['err']['field-class'] = 'field-continent_code';
				return $result;
			}
			if($form_data['country_code']['value'] == null){
				$result['err']['err_msg'] = '<b>' . $form_data['continent_code']['label'] . '</b>:' . _(' required field.');
				$result['err']['field-class'] = 'field-country_code';
				return $result;
			}
			if($this->db->where('country_iso2_code', $form_data['country_code']['value'])->getOne('countries') == null){
				$result['err']['err_msg'] = _('Save denied. ') . $form_data['country_code']['value'] . _(': invalid value.');
				$result['err']['field-class'] = 'field-country_code';
				return $result;
			}
			if($this->db->where('country_iso2_code', $form_data['country_code']['value'])->getOne('countries')['continent_iso2_code'] != $form_data['continent_code']['value']){
				$result['err']['err_msg'] = _('Save denied.');
				$result['err']['field-class'] = 'field-country_code';
				return $result;
			}
			if($form_data['lat']['value']!=null && !preg_match('/^[-]?[0-9]{1,2}\.[0-9]{1,8}$/', $form_data['lat']['value'])){
				$result['err']['err_msg'] = '<b>' . $form_data['lat']['label'] . '</b>:' . _(' invalid value.');
				$result['err']['field-class'] = 'field-lat';
				return $result;
			}
			if($form_data['lng']['value']!=null && !preg_match('/^[-]?[0-9]{1,2}\.[0-9]{1,8}$/', $form_data['lng']['value'])){
				$result['err']['err_msg'] = '<b>' . $form_data['lng']['label'] . '</b>:' . _(' invalid value.');
				$result['err']['field-class'] = 'field-lng';
				return $result;
			}
			if($form_data['lat']['value']!=null && $form_data['lng']['value']==null){
				$result['err']['err_msg'] = '<b>' . $form_data['lng']['label'] . '</b>:' . _(' required field.');
				$result['err']['field-class'] = 'field-lng';
				return $result;
			}
			if($form_data['lat']['value']==null && $form_data['lng']['value']!=null){
				$result['err']['err_msg'] = '<b>' . $form_data['lat']['label'] . '</b>:' . _(' required field.');
				$result['err']['field-class'] = 'field-lat';
				return $result;
			}

			// Medical specialties validation
			if(isset($form_data['medical_specialties']['value']) && is_array($form_data['medical_specialties']['value'])){
				$all_active_specialties = $this->db->where('status', 1)->getValue('users_medical_specialties', 'id', null);
				$center_specialties = $this->db->where('center_id', $form_data['center_id']['value'])->getValue('clinical_center_medical_specialties_to', 'specialty_id', null);
				foreach ($form_data['medical_specialties']['value'] as $specialty_id) {
					if(!in_array($specialty_id, $all_active_specialties)){
						$result['err']['err_msg'] = '<b>' . $form_data['medical_specialties']['label'] . '</b>:' . _(' invalid value.');
						$result['err']['field-class'] = 'field-medical_specialties';
						return $result;
					}
				}
			} else $form_data['medical_specialties']['value'] = [];

			// List of editable fields of the clinical center
			$center_writable_fields = [];
			foreach($this->db->rawQuery('describe clinical_centers') as $attribute) $center_writable_fields[] = $attribute['Field'];
			$center_writable_fields[] = 'medical_specialties';  // Field not in clinical_centers table
			// The following fields are editable only from the controller
			$center_writable_fields = array_diff($center_writable_fields, ['id', 'group_id', 'country_id', 'created_by', 'created_at', 'updated_by', 'updated_at', 'deleted_by', 'deleted_at']);

			foreach ($center_writable_fields as $field) {
				$result['ok'][$field] = $this->utility->deepTrim($form_data[$field]['value']);
			}
			// foreach ($form_data as $form_field => $values) {
			// 	if(in_array($form_field, $center_writable_fields)){
			// 		$result['ok'][$form_field] = $values['value'];
			// 	} else {
			//
			// 	}
			// }

			return $result;
		}


		//List all Clinical Centers in the Group
		function centersList() {
			if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
				return $this->redirect('login', 'permissionDenied');
			}

			$results = $this->db
				->where('cc.group_id', $this->userGroupId)
				->join('continents cnts', 'cnts.code=cc.continent_code', 'INNER')
				->join('countries cntrs', 'cntrs.country_iso2_code=cc.country_code', 'INNER')
				->orderBy('cnts.name', 'asc')
				->get('clinical_centers cc', null, ['cc.id center_id', 'cc.description', 'cnts.name continent_name', 'cntrs.country_name', 'cc.anonymize', 'cc.notes']);

			$activeSpecialties = $this->getActiveMedicalSpecialtiesIdByGroupId($this->userGroupId);

			foreach($results as $index => $item) {
				$specialties = $this->db
					->where('ccmst.center_id', $item['center_id'])
					->join('users_medical_specialties ums', 'ums.id=ccmst.specialty_id', 'INNER')
					->get('clinical_center_medical_specialties_to ccmst', null, ['ums.id', 'ums.description']);

				$translated = [];
				if (!empty($specialties)) {
					foreach($specialties as $indecSpec => $specialty) {
						$translated[$specialty['id']]['description'] = _($specialty['description']);
						$translated[$specialty['id']]['active'] = in_array($specialty['id'], $activeSpecialties) ? true : false;
					}
				}

				$results[$index]['specialties'] = $translated;
			}

			$this->view->centers = $results;


			$this->actionTitle = _('Clinical Centers');
			$this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];

			return $this->setJsonView('centersList');
		}

	}
