<?php
/**
 * survey.php - Controller for handling surveys.
 *
 * @author $Author: dtong $
 * @version $Id: survey.php,v 1.11 2011/03/03 11:08:30 dtong Exp $
 * @copyright Copyright (c) 2010, Tiller Software Co., Ltd.
*/

class Survey extends CI_Controller{
	const CMS_SURVEY_LOGIN_SESSION = 'SURVEY_LOGIN';
	private $blocks = FALSE;

	function __construct() {
		parent::__construct();
		$this->load->helper('form');
		$this->load->library('form_validation');
		osa_load_lang('survey');
		osa_load_lang('mapping');
		$this->load->library('cms/osa_chart');
		$this->load->model('survey/survey_model');
		$this->load->model('survey/survey_result_model');
		$this->load->model('survey/survey_template_model');
		$this->load->model('sort/searchsort_model');
		//Not using the actual model but needs it to reference the survey_login session object
		$this->load->model('auth/survey_login_model');
		$this->blocks = $this->config->item('cms_survey_blocks');
	}

/*
	//Function to add or edit survey data in the table template_htmldata.
	//TODO: This should be decoupled from survey so radio boxes can be supported in other modules
	function add($extid,$type,$radio_select,$question_index=FALSE,$weight=FALSE){
		$data = FALSE;
 		$data->extid = $extid;
 		$data->type = $type;
 		$data->radio_select = $radio_select;
 		$data->question_index = $question_index;
 		$data->weight = $weight;
 		$this->survey_model->add_template_htmldata($data);
	}
*/

	//Function displays the survey page.
	//survey id is parity plus hex(id)
	function index($surveyid){
		$id_array = osa_hex_id_numval($surveyid);
		if ( $id_array === FALSE ){
			echo osa_ajaxmsg(lang('login_survey_msg_surveyid'));
			exit;
		}

		//get the parity and actual db id from the survey code
		$real_surveyid = $id_array['id'];
		$real_parity = $id_array['parity'];
		$survey = $this->survey_model->get_survey($real_surveyid, $real_parity);

		if (isset($survey) && $survey !== FALSE ){
			$expired = FALSE;
			if ( $this->survey_model->survey_expired($survey) ) {
				$expired = TRUE;
			}
			if ( $survey->islogin && !$this->survey_login_model->isAuthenticated() || $expired) {
				//Survey requires login and no login so exit
				$this->_redirect_login_page($surveyid);
			}

			$user = $this->survey_login_model->getLogin();
			$data->current_user_realname = '';
			$data->current_user_realname = $this->_user_realname($user);
			$data->unitbody = '';
			//TODO: add error handling for $template and $resultid
			//Gets the survey template
			$template = $this->_get_template($user, $survey->id);
			//Get or add a record to survey_result
			$resultid = $this->_prepare_result($user, $template->id);
			//Save result id in survey login session object for access check later
			$user->resultid = $resultid;
			$this->session->set_userobject(self::CMS_SURVEY_LOGIN_SESSION, $user);

			if ( $survey->islogin ) {
				if (isset($user) && $user != FALSE){
					$data->surveyid = $surveyid;
					$data->title = $survey->title;
					$data->resultid = $resultid;
					$data->teacher = $this->_creator_realname($survey->creatorid);
					$data->courses = $this->survey_model->get_course_names($survey->id);
					$data->blocks = $this->_get_blocks($survey->id);
					$data->startdate = osa_date_format($survey->startdate);
					$data->enddate = osa_date_format($survey->enddate);
					$data->done_btn_disabled = '';
					$action = CMS_ACTION_EDIT;
					if ( $this->_is_result_completed($resultid) == FALSE ) {
						$action = CMS_ACTION_READ;
						$data->done_btn_disabled = 'disabled="disabled" style="color:grey"';
					}
					if (isset($template->template) && $template->template != FALSE) {
						$data->unitbody = $this->_render_template($action, $resultid, $template->template);
					}
				}
				else {
					//If survey requires login and we don't have a login then redirect to login page
					$this->_redirect_login_page($surveyid);
					exit;
				}
			} //($survey->islogin)
			else {
				//The nologin survey handling goes here
				/* $data->unitbody = $this->_survey_nologin($survey); */
			}
			$this->load->view('survey/survey_view',$data);
			return;
		}
		//If we get here that means a bad survey. The login page won't let this happen though
		//The following creates infinite loop. Not needed anyway
		//$this->session->set_flashdata('SURVEY_LOGIN_MSG', lang('survey_invalid_id_msg'));
		//$this->_redirect_login_page($surveyid);
		exit;
	}

	function complete($resultid, $clear_login=TRUE) {
		$user = $this->survey_login_model->getLogin();
		if ( !$user || $user->resultid != $resultid ) {
			echo 'failed';
			return;
		}
		if ( !$this->survey_result_model->update_complete($resultid) ) {
			echo 'failed';
			return;
		}
		if ( $clear_login ) {
			$this->load->model('auth/survey_login_model');
			$this->survey_login_model->destroyLogin();
		}
		echo 'success';
	}

	//This adds a new result record if it doesn't exist yet
	//Gets the related result record if exists
	private function _prepare_result($survey_login, $templateid) {
		$result = $this->survey_result_model->get_survey_result($survey_login, $templateid);
		if ( $result ){
			//$this->survey_result_model->update_survey_result($survey_login, $templateid, $update_modify, $completed);
			$resultid = $result->id;
		}
		else {
			//Result does not exist so add survey_result
			$resultid = $this->survey_result_model->add_survey_result($survey_login, $templateid);
		}
		return $resultid;
	}

	//Get the proper (student or teacher) template for this user
	//Survey template file name consists of: _1 - all users, _2 - teacher, _3 student
	private function _get_template($survey_user, $surveyid) {
		$is_teacher = $this->_is_teacher($survey_user);
		$templates = $this->survey_model->get_templates($surveyid);
		if ( !$templates )
			return FALSE;
		//Only one templates so just return it
		if ( count($templates) == 1 ) {
			return $templates[0];
		}
		foreach( $templates as $record ) {
			if ( strlen($record->template) <= 0 ) {
				continue;
			}
			//The last char is a digit tells what type the survey is, 1 - all, 2 - teacher, 3 students
			$code = substr($record->template, strlen($record->template)-1);
			if ( $code == CMS_SURVEY_TEMPLATE_SINGLE_TYPE || ($code == CMS_SURVEY_TEMPLATE_TEACHER_TYPE && $is_teacher) ||
				( $code == CMS_SURVEY_TEMPLATE_STUDENT_TYPE && !$is_teacher) ) {
				return $record;
			}
		}
		return FALSE;
	}

	//Is the survey user a teacher?
	//This assumes if the user exists in the user table then it is a teacher account
	private function _is_teacher($survey_user) {
		if ( !$survey_user ) {
			return FALSE;
		}
		if ( !empty($survey_user->userid) ) {
			return TRUE;
		}
		return FALSE;
	}

	//Get the survey login real name
	private function _user_realname($survey_login) {
		$ret = lang('survey_na');
		if ( !empty($survey_login->userid) ) {
			$cms_login = $this->login_model->getLogin();
			if ( $cms_login ) {
				$ret = osa_user_getname($cms_login);
				return $ret;
			}
		}
		if ( !empty($survey_login->ext_firstname) || !empty($survey_login->ext_lastname) ) {
			$ret = $survey_login->ext_firstname . ' ' . $survey_login->ext_lastname . " ($survey_login->ext_username)";
		}
		else {
			$ret = $survey_login->ext_username;
		}
		return $ret;
	}

	//Get the list of block names for a survey
	private function _get_blocks($surveyid) {
		$blocks = $this->survey_model->get_blocks($surveyid);
		$ret = '';
		$sep = '';
		if ( $blocks ) {
			foreach ($blocks as $record) {
				$ret .= $sep . $this->blocks[$record];
				$sep = ', ';
			}
		}
		return $ret;
	}

	//Get the name for the survey creator
	private function _creator_realname($userid) {
		$user = $this->login_model->getDbUserByid($userid);
		return osa_user_getname($user);
	}

	//Function redirect Login Page
	private function _redirect_login_page($surveyid){
		redirect( base_url() . $surveyid );
		exit;
	}

	//Function to render the survey page template.
	private function _render_template($action, $resultid, $template){
		if (!is_numeric($resultid) && $resultid == 0)
			return FALSE;
		$this->load->library('unit/unitmain',
		array('action'=>$action,'unitid'=>$resultid, 'courseid'=>0,'unit_template'=> $template));
		return $this->unitmain->render();
	}

	//Function check in the table column completed a survey_result.
	private function _is_result_completed($resultid){
		if (!is_numeric($resultid) || $resultid <= 0)
			return FALSE;
		$result = $this->survey_result_model->get_survey_completed($resultid);
		if (isset($result->completed) && $result->completed != CMS_DB_BOOLEAN_TRUE)
			return TRUE;
		return FALSE;
	}

	//Function to add or edit survey_result table and return extid
	private function _validate_survey_result($data){
		$extid = FALSE;
		$result = $this->survey_result_model->get_survey_result($data);
		if (isset($result) && $result !== FALSE){//Edit survey_result
			$this->survey_result_model->update_survey_result($data);
			$extid = $result->id;
		}
		else {
			//Add survey_result
			$extid = $this->survey_result_model->add_survey_result($data);
		}
		return $extid;
	}
}