<?php
/**
 * survey_model.php - Survey model
 *
 * @author $Author: dtong $
 * @version $Id: survey_model.php,v 1.10 2011/03/14 12:42:00 dtong Exp $
 * @copyright Copyright (c) 2010, Tiller Software Co., Ltd.
*/

class survey_model extends CI_Model {

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

   //Gets a survey record by survey id and parity
 	function get_survey($surveyid, $parity) {
		if ( !is_numeric($surveyid) ) {
			return FALSE;
		}
		$this->db->select('*');
	   $this->db->from('survey');
	   $this->db->where('id', $surveyid);
	   if ( $parity !== FALSE ) {
	   	$this->db->where('parity', $parity);
	   }
		$res = $this->db->get();
		if ( $res->num_rows()<= 0 )
			return FALSE;
		$result = $res->result();
		return $result[0];
	}

	function get_survey_byids($surveyids) {
		if ( !is_array($surveyids) ) {
			return FALSE;
		}
		$this->db->select('*');
	   $this->db->from('survey');
	   $this->db->where_in('id', $surveyids);
		$res = $this->db->get();
		if ( $res->num_rows()<= 0 )
			return FALSE;
		return $res->result();
	}

/*
 	function get_template_htmldata($data) {
		$table_template_htmldata = 'template_htmldata';
			if ( !is_numeric($data->extid) && !is_numeric($data->type) )
			return FALSE;
		$this->db->select('*');
	   $this->db->from($table_template_htmldata);
	   $this->db->where('extid', $data->extid);
		$this->db->where('type', $data->type);
		if (isset($data->question_index) && $data->question_index !== FALSE)
			$this->db->where('question_index', $data->question_index);
		$res = $this->db->get();
		if ( $res->num_rows()<= 0 )
			return FALSE;
		return $res->result();
	}
 	function add_template_htmldata($data) {
 		if ($this->get_template_htmldata($data) !== FALSE){
 			$this->update_template_htmldata($data);
 		}
 		else{
 			$table_template_htmldata = 'template_htmldata';
			$this->db->insert($table_template_htmldata, $data);
 		}
		return TRUE;
	}
	function update_template_htmldata($data) {
		$table_template_htmldata = 'template_htmldata';

		$this->db->where('extid', $data->extid);
		$this->db->where('type', $data->type);
		if (isset($data->question_index) && $data->question_index !== FALSE)
			$this->db->where('question_index', $data->question_index);
		$this->db->update($table_template_htmldata, $data);
		return TRUE;
	}
	function del_template_htmldata($data) {
		$table_template_htmldata = 'template_htmldata';

		$this->db->where('extid', $data->extid);
		$this->db->where('type', $data->type);
		if (isset($data->question_index) && $data->question_index !== FALSE)
			$this->db->where('question_index', $data->question_index);
		$this->db->delete($table_template_htmldata, $data);
		return TRUE;
	}
 	function get_chart_template_htmldata($data) {
		$table_template_htmldata = 'template_htmldata';
			if ( !is_numeric($data->extid) && !is_numeric($data->type) )
			return FALSE;
		$this->db->select('*,count(extid) total');
	   $this->db->from($table_template_htmldata);
	   $this->db->where('extid', $data->extid);
		$this->db->where('type', $data->type);
		$this->db->where('question_index', $data->question_index);
		$this->db->groupby('extid,type,question_index,radio_select');
		$res = $this->db->get();
		if ( $res->num_rows()<= 0 )
			return FALSE;
		return $res->result();
	}
*/
/*
	function get_user() {
		$table_user = 'user';
		$this->db->select('id, displayname');
		$this->db->from($table_user);
		$this->db->where('enabled',CMS_ADMIN_ENABLE);
		$this->db->where_not_in('username', array($this->config->item('cms_admin_username'),$this->config->item('cms_guest_username')));
		$this->db->order_by('displayname');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
			return FALSE;
		$user = $res->result();
		$result = array();
		foreach($user as $value) {
			$result[$value->id] = $value->displayname;
		}
		return $result;
	}
*/
/*
	function get_department() {
		$table_department = 'department';
		$this->db->select('id, name');
		$this->db->from($table_department);
		$this->db->where('enabled',CMS_ADMIN_ENABLE);
		$this->db->order_by('name');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
			return FALSE;
		$user = $res->result();
		$result = array();
		foreach($user as $value) {
			$result[$value->id] = $value->name;
		}
		return $result;
	}
*/
	//Get all the courses except teacher's mycourses
	function get_othercourses($mycourses) {
		$this->db->select('id,name');
		$this->db->from('course_sis');
		$this->db->where('enabled', 1);
		$this->db->order_by('name');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
			return FALSE;
		$array = $res->result();
		if ( !$mycourses || !is_array($mycourses) )
			return $array;
		$newarray = array();
		//Let's loop and takeout the tacher's courses
		foreach ($array as $record) {
			$docopy = TRUE;
			foreach ($mycourses as $myrecord) {
				if ( $myrecord->id == $record->id ) {
					$docopy = FALSE;
					break;
				}
			}
			if ( $docopy ) {
				$newarray[] = $record;
			}
		}
		return $newarray;
	}

	//Get teacher's mycourses
	function get_mycourses($userid) {
		$this->db->select('c.id,c.name');
		$this->db->from('course_sis c');
		$this->db->join('user_course u', 'c.id=u.courseid');
		$this->db->where("u.userid", "$userid");
		$this->db->where("c.enabled", 1);
		$this->db->order_by('c.name');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
			return FALSE;
		return $res->result();
	}

	//Creates a new survey.
	function create_survey($userid, $extid, $startdate, $enddate, $courses, $blocks, $templates, $title) {
		$now = osa_dbdate();
		$parity = $this->random_2digit_hex();
		//Title is not used yet
		$survey_data = array('creatorid' => $userid, 'ispublic' => 0,
									'islogin' => 1, 'disabled' => 0, 'createdate' => $now,
									'modifydate' => $now, 'startdate' => $startdate, 'enddate' => $enddate,
									'parity' => $parity, 'title'=>$title
									);

		$this->db->trans_begin();
		///////////////////////////////////////////////////////////////////
		$this->db->insert('survey', $survey_data);
		$surveyid = osa_db_lastinsertid($this->db);
		//echo $surveyid;
		//Write to survey_template table
		foreach ($templates as $key=>$value) {
			$template_data = array('surveyid' => $surveyid, 'type' => $key, 'template' => $value);
			$this->db->insert('survey_template', $template_data);
		}
		//Write to survey_course table
		if ( $courses ) {
			//Loop thru the user selected courses
			foreach ($courses as $courseid) {
				if ( is_numeric($courseid) ) {
					$data = array('courseid' => $courseid, 'surveyid' => $surveyid);
					$this->db->insert('survey_course', $data);
				}
			}
		}
		//Write to survey_extra_data table. Right now, only type block is supported but the data structure can support more
		if ( $blocks ) {
			//Loop thru the user selected courses
			foreach ($blocks as $blockid) {
				if ( is_numeric($blockid) ) {
					$data = array('surveyid' => $surveyid, 'data_type' => CMS_SURVEY_EXTRA_BLOCK_TYPE, 'data' => $blockid);
					$this->db->insert('survey_extra_data', $data);
				}
			}
		}
		//Write to table survey_goal
		$data = array('goalid' => $extid, 'surveyid' => $surveyid);
		$this->db->insert('survey_goal', $data);

		if ($this->db->trans_status() === FALSE) {
		  	$this->db->trans_rollback();
		 	return FALSE;
		}
		///////////////////////////////////////////////////////////////////
		$this->db->trans_complete();
		if ($this->db->trans_status() === FALSE) {
			return FALSE;
		}

		$url_code = osa_hex_code($parity, $surveyid);
		return $url_code;
	}

	//Updates a survey
	function update_survey($surveyid, $startdate, $enddate, $courses, $blocks, $title, $survey_templates) {
		$this->db->trans_begin();
		///////////////////////////////////////////////////////////////////
		//Update survey table
		$data = array('startdate'=>$startdate, 'enddate'=>$enddate, 'modifydate'=>osa_dbdate(), 'title'=>$title);
		$this->db->where('id', $surveyid);
		$this->db->update('survey', $data);

		//Update survey_course table
		$this->db->where('surveyid', $surveyid);
		$this->db->delete('survey_course');
		if ( $courses ) {
		//Loop thru the user selected courses
			foreach ($courses as $courseid) {
				if ( is_numeric($courseid) ) {
					$data = array('courseid' => $courseid, 'surveyid' => $surveyid);
					$this->db->insert('survey_course', $data);
				}
			}
		}

		//Update blocks
		//Right now, only type block is supported but the data structure can support more
		$this->db->where('surveyid', $surveyid);
		$this->db->where('data_type', CMS_SURVEY_EXTRA_BLOCK_TYPE);
		$this->db->delete('survey_extra_data');
		if ( $blocks ) {
			//Loop thru the user selected courses
			foreach ($blocks as $blockid) {
				if ( is_numeric($blockid) ) {
					$data = array('surveyid' => $surveyid, 'data_type' => CMS_SURVEY_EXTRA_BLOCK_TYPE, 'data' => $blockid);
					$this->db->insert('survey_extra_data', $data);
				}
			}
		}

		//Update the survey templates in case the user changed the survey selection
		//This will check if the survey is dirty or not. Will not give warning message if survey is dirty and no update
		if ( $survey_templates && is_array($survey_templates) && !$this->survey_has_results($surveyid) ) {
			foreach ( $survey_templates as $key => $template ) {
				$data = array('template' => $template);
				$this->db->where('surveyid', $surveyid);
				$this->db->where('type', $key);
				$this->db->update('survey_template', $data);
			}
		}

		if ($this->db->trans_status() === FALSE) {
		  	$this->db->trans_rollback();
		 	return FALSE;
		}
		///////////////////////////////////////////////////////////////////
		$this->db->trans_complete();
		if ($this->db->trans_status() === FALSE) {
			return FALSE;
		}
		return TRUE;
	}

	//Assumes one or all surveys per goal
	function get_survey_bygoalid($extid, $return_multiple=FALSE) {
		$this->db->select('s.*');
		$this->db->from('survey s');
		$this->db->join('survey_goal g', 'g.surveyid=s.id');
		$this->db->where('g.goalid', $extid);
		$this->db->order_by('s.startdate,s.enddate');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 ) {
			return FALSE;
		}
		$array = $res->result();
		if ( $return_multiple ) {
			return $array;
		}
		return $array[0];
	}

	function get_blocks($surveyid) {
		$this->db->select('data');
		$this->db->where('surveyid', $surveyid);
		$this->db->where('data_type', CMS_SURVEY_EXTRA_BLOCK_TYPE);
		$res = $this->db->get('survey_extra_data');
		if ( $res->num_rows() <= 0 ) {
			return array();
		}
		$records = $res->result();
		$ret = array();
		foreach ($records as $record) {
			$ret[] = $record->data;
		}
		return $ret;
	}

	function get_courses($surveyid) {
		$this->db->select('courseid');
		$this->db->where('surveyid', $surveyid);
		$res = $this->db->get('survey_course');
		if ( $res->num_rows() <= 0 ) {
			return array();
		}
		$records = $res->result();
		$ret = array();
		foreach ($records as $record) {
			$ret[] = $record->courseid;
		}
		return $ret;
	}

	function get_course_names($surveyid) {
		$this->db->select('c.name');
		$this->db->from('course_sis c');
		$this->db->join('survey_course s', 's.courseid=c.id');
		$this->db->where('s.surveyid', $surveyid);
		$this->db->order_by('c.name');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 ) {
			return '';
		}
		$records = $res->result();
		$ret = '';
		$sep = '';
		foreach ($records as $record) {
			$ret .= $sep . $record->name;
			$sep = ', ';
		}
		return $ret;
	}

	//Get one or more templates beloning to the supplied survey
	function get_templates($surveyid) {
		$this->db->select('*');
		$this->db->from('survey_template');
		$this->db->where('surveyid', $surveyid);
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 ) {
			return FALSE;
		}
		return $res->result();
	}

	function get_templates_by_goalid($goalid) {
		$this->db->select('t.*');
		$this->db->from('survey_goal g');
		$this->db->join('survey s', 'g.surveyid=s.id');
		$this->db->join('survey_template t', 't.surveyid=s.id');
		$this->db->where('g.goalid', $goalid);
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 ) {
			return FALSE;
		}
		$array = $res->result();
		return $array;
	}

	function survey_expired($surveyobj) {
		if ( !is_object($surveyobj) || !isset($surveyobj->enddate) ||
				strtotime($surveyobj->enddate) < time() ) {
			return TRUE;
		}
		return FALSE;
	}

	//See has anyone taken the survey yet
	function survey_has_results($surveyid) {
		$this->db->select('count(t.id) s_total');
		$this->db->from('survey_template t');
		$this->db->join('survey_result r', 't.id=r.templateid');
		$this->db->join('template_htmldata h', 'r.id=h.extid');
		$this->db->where("t.surveyid", $surveyid);
		$res = $this->db->get();
		if ( $res->num_rows()<= 0 ) {
			//This means an error so return true telling it is dirty
			return TRUE;
		}
		$count = $res->result();
		$count = $count[0];
		if ( $count->s_total <= 0 ) {
			return FALSE;
		}
		return TRUE;
	}

	private function random_2digit_hex() {
		$num = rand(16, 255);
		return dechex($num);
	}
}