<?php
/**
 * lt_model.php - Learning Target Model
 *
 * @author $Author: dtong $
 * @version $Id: lt_model.php,v 1.25 2011/05/09 04:48:53 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/

class Lt_model extends CI_Model {
	public $sort_read_only = FALSE;
	public $sort_type = FALSE;
	public $sort_filehash = FALSE;

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

	/*
	 * This is the learning targets section on the unit page
	 */
	/*
	function get_targets($unitid, $type) {
		if ( !is_numeric($unitid) || !is_numeric($type) ) {
			return FALSE;
		}
		$this->db->select('t.*');
		$this->db->from('target_text as t');
		$this->db->join('unit_target as u',
			"t.id=u.targetid", 'right');
		$this->db->where('u.unitid', $unitid);
		$this->db->where('t.type', $type);
		$this->db->order_by('select1,benchmarkid', 'asc');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
	}
	*/

	/*
	 * This is the learning targets section on the unit page.
	 * $use_strands - Will get strands, standards and benchmarks.
	 * config cms_lt_importid_support will force to use strands
	 */
	function get_targets($unitid, $type, $use_strands=FALSE) {
		if ( !osa_is_int_one($unitid) || !osa_is_int_one($type) ) {
			return FALSE;
		}
		$use_importid = FALSE;
		if ( $this->config->item('cms_lt_importid_support') ) {
			$use_importid = TRUE;
		}

		$table_unit_target = $this->db->dbprefix('unit_target');
		$table_target_text = $this->db->dbprefix('target_text');
		$table_course_sis = $this->db->dbprefix('course_sis');
		$table_department = $this->db->dbprefix('department');
		$table_strand = $this->db->dbprefix('strand');
		$table_standard = $this->db->dbprefix('standard');
		$table_benchamrk = $this->db->dbprefix('benchmark');

		$fields = 'd.id departmentid,d.name departmentname,c.name coursename,t.id,c.department_display,' .
					 't.benchmarkid,t.courseid,t.select1,t.data,t.type,u.unitid';
		$table = "$table_target_text as t";
		$joins = '';
		$sort_array = array('departmentname', 'departmentid');
		//Need all related strands, standards and benchmarks
		if ( $use_strands || $use_importid ) {
			$fields .= ',str.id strandid,std.id standardid,str.data strand,std.data standard,bench.data benchmark,' .
						  'str.importid strand_importid,std.importid standard_importid,bench.importid benchmark_importid';
			$table = "$table_strand as str";
			$joins = "join $table_standard as std on str.type={$type} and str.id=std.strandid " .
						"join $table_benchamrk as bench on std.id=bench.standardid " .
						"join $table_target_text as t on bench.id=t.benchmarkid ";
			if ( $use_importid ) {
				$sort_array = array('departmentname', 'departmentid', 'strand_importid','standard_importid','benchmark_importid');
			}
			else {
				$sort_array = array('departmentname', 'departmentid','strand','strandid','standard','standardid','benchmark','benchmarkid');
			}
		}
		$joins .= "join $table_unit_target as u on u.unitid={$unitid} and t.id=u.targetid " .
					 "join $table_course_sis as c on c.id=t.courseid " .
					 "join $table_department as d on d.id=c.departmentid";

		//$conditions = "u.unitid={$unitid} and t.type={$type}";
		$conditions = "t.type={$type}";
	/*
		$orderby = 'sortmaxid asc, r.sortkey asc ';
		if ( $this->config->item('cms_lt_importid_support') ) {
			$orderby = "str.importid_int,std.importid_int,bench.importid_int,{$orderby} ";
		}*/

		$query   = "select $fields from $table $joins where $conditions";
		$res = $this->db->query( $query );

		if ( $res->num_rows() <= 0 ) {
    		return FALSE;
		}
    	$rows = $res->result();
    	$tmp_sort = array_merge($sort_array, array('data'));
    	if ( !osa_array_natsort($rows, $tmp_sort) ) {
    		osa_log(__METHOD__, 'Failed to run natsort on data.', $tmp_sort);
    		return NULL;
    	}
    	if ( $rows && count($rows) > 1 && $this->sort_type ) {
			$this->load->library('cms/cms_btnsort');
			if ( !$this->cms_btnsort->reset($this->sort_filehash, $unitid, $this->sort_type, 'unitid') ) {
				osa_log(__METHOD__, 'Failed to run btnsort reset.', $unitid, $type);
				return NULL;
			}
			if ( $this->sort_read_only ) {
				$this->cms_btnsort->read_only();
			}
			if ( $use_strands ) {
				//Listing LT along with strands, standards and benchmarks so need btnsort segmentid populated
				//$this->cms_btnsort->set_segmentindex('benchmarkid', 'departmentid');
				$this->cms_btnsort->set_segmentindex('benchmarkid');
			}
			else {
				$this->cms_btnsort->set_segmentindex('departmentid');
			}
			if ( !$this->cms_btnsort->init($rows) ) {
				osa_log(__METHOD__, 'Failed to run btnsort init.', $rows);
				return NULL;
			}
			$tmp_sort = array_merge($sort_array, array(Cms_btnsort::INDEX_SORTKEY));
	    	if ( !osa_array_natsort($rows, $tmp_sort) ) {
	    		osa_log(__METHOD__, 'Failed to run natsort on data.', $tmp_sort, $rows);
	    		return NULL;
	    	}
    	}
    	return $rows;
	}

	/*
	 * Gets standards, benchmarks, target text for a course
	 * This is the standards and benchmarks and lt on the lt popup page
	 */
	/*
	function get_selections($courseid, $type) {
		if ( !is_numeric($courseid) || !is_numeric($type) ) {
			return FALSE;
		}
		$this->db->select('st.id strandid,c.name coursename ,t.*,b.data as benchmark,b.id as benchmarkid, ' .
								's.data as standard, s.id as standardid, b.mingradeid,b.maxgradeid');
		$this->db->from('target_text as t');
		$this->db->join('benchmark as b', "t.benchmarkid=b.id", 'left');
		$this->db->join('standard as s', 'b.standardid=s.id', 'left');
		$this->db->join('strand as st', 's.strandid=st.id', 'left');
		$this->db->join('course_sis  c', 'c.id=t.courseid', 'left');
		$this->db->where('t.courseid', $courseid);
		$this->db->where('t.type', $type);
		//where flag enabled=1
		$this->db->where('b.enabled', CMS_ADMIN_ENABLE);
		$this->db->where('s.enabled', CMS_ADMIN_ENABLE);
		$this->db->where('st.enabled', CMS_ADMIN_ENABLE);
		//$this->db->order_by('s.strandid,s.id,b.id', 'asc');
		$this->db->order_by('s.data,s.id,b.data,b.id,t.data', 'asc');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
	}
	*/
	function get_selections($courseid,$type,$course_items=FALSE) {
		if ( !is_numeric($courseid) || !is_numeric($type) ) {
			return FALSE;
		}
		$this->load->library('cms/cms_btnsort');

		$course_lt_link_items = array();
		$courseid_in = $courseid;

		//Add course ids for integrated and unified units to $courseid_in
		$courseid_intuni = '';
		if (is_array($course_items)){
			if(count($course_items) > 0){
				$courseid_intuni = implode(',', $course_items) ;
				$courseid_in .= ',' . $courseid_intuni;
			}
		}

		//Add course ids to $courseid_in from course_lt_link table along with course ids from int. and unitified. units
		$course_lt_link_items = $this->get_course_lt_link($courseid);
		if (is_array($course_lt_link_items)){
			if (count($course_lt_link_items) > 0 ) {
				foreach ($course_lt_link_items as $row){
					$courseid_in .= ',' . $row->lt_courseid;
				}
			}
		}

		$table_target_text = $this->db->dbprefix('target_text');
		$table_benchmark   = $this->db->dbprefix('benchmark');
		$table_standard    = $this->db->dbprefix('standard');
		$table_strand      = $this->db->dbprefix('strand');
		$table_course_sis    = $this->db->dbprefix('course_sis');
		$table_department    = $this->db->dbprefix('department');
		//$table_res_sort    = $this->db->dbprefix('res_sort');
/*
		$select  = '';
		$from    = '';
		$join    = '';
		$where   = '';
		$orderby = '';

		$select = 'case when r.sortkey is null then
					  ifnull( (select max(sortkey)+1 from res_sort where type=' . CMS_SORT_LT_COURSE .
					  			' and fk2='.$courseid.' group by type,fk2 ), 0 )
					  else r.sortkey end as sortmaxid,
					  c.name coursename ,t.*,b.data as benchmark,b.id as benchmarkid,
					  s.data as standard, s.id as standardid, b.mingradeid,b.maxgradeid,
					  st.importid as strand_importid,s.importid as standard_importid,b.importid as benchmark_importid ';
		$from 	 = "$table_target_text as t ";

		$join   .= " left join $table_benchmark as b on t.benchmarkid=b.id";
		$join   .= " left join $table_standard as s on b.standardid=s.id";
		$join   .= " left join $table_strand as st on s.strandid=st.id";
		$join   .= " left join $table_course_sis as c on c.id=t.courseid";
		$join   .= " left join $table_department as d on d.id=c.departmentid";
		$join   .= " left join $table_res_sort as r on r.fk2=t.courseid and r.fk3=t.id ";

		$where  .= " t.courseid in(".$courseid_in.")";
		$where  .= " and t.type=" .$type;
		$where  .= " and b.enabled=" .CMS_ADMIN_ENABLE ." ";
		$where  .= " and s.enabled=" .CMS_ADMIN_ENABLE;
		$where  .= " and st.enabled=" .CMS_ADMIN_ENABLE;

		if ( $this->config->item('cms_lt_importid_support') ) {
			//$orderby = ' abs(st.importid),abs(s.importid),abs(b.importid),';
			$orderby = ' st.importid_int,s.importid_int,b.importid_int,';
		}
			$orderby .= ' d.name,d.id,st.data,st.id,s.data,s.id,b.data,b.id,sortmaxid asc,r.sortkey asc,t.data';

		$query   = " select $select from $from $join where $where order by $orderby";
*/
		$sort_array = array();
		if ( $this->config->item('cms_lt_importid_support') ) {
			$sort_array = array('strand_importid','standard_importid','benchmark_importid');
		}
		$sort_array = array_merge($sort_array,
			array('deptname','deptid','strand','strandid','standard','standardid','benchmark','benchmarkid'));

		$enable = CMS_DB_BOOLEAN_TRUE;
		$query = 'select c.name coursename,t.*,b.data benchmark,b.id benchmarkid,d.name deptname,d.id deptid,' .
						's.data standard, s.id standardid, b.mingradeid,b.maxgradeid,st.id strandid,st.data strand,' .
						'st.importid strand_importid,s.importid standard_importid,b.importid benchmark_importid ' .
						//"'{$this->sort_type}' realtype " .
					"from $table_target_text as t " .
					"join $table_benchmark as b on t.benchmarkid=b.id " .
					"join $table_standard as s on b.standardid=s.id " .
					"join $table_strand as st on s.strandid=st.id " .
					"join $table_course_sis as c on c.id=t.courseid " .
					"join $table_department as d on d.id=c.departmentid " .
					"where t.courseid in ({$courseid_in}) and t.type={$type} and " .
						"b.enabled={$enable} and s.enabled={$enable} and st.enabled={$enable}";

		$res = $this->db->query( $query );
		if ( $res->num_rows() <= 0 ) {
    		return FALSE;
		}
    	$rows = $res->result();

		//Get multiple courseids (from LT link or integrated/shared) for sorting
		$sort_courseids = $courseid;
		if ( $courseid_in != $courseid ) {
			$sort_courseids = explode(',', $courseid_in);
			if ( !$sort_courseids || count($sort_courseids) <= 1 ) {
				$sort_courseids = $courseid;
			}
		}

		if ( $this->sort_type && $rows && count($rows) > 1 ) {
			if ( !$this->cms_btnsort->reset($this->sort_filehash, $sort_courseids, $this->sort_type, 'courseid') ) {
				return FALSE;
			}
	    	$this->cms_btnsort->pre_fetch_off();
			$this->cms_btnsort->set_segmentindex('benchmarkid');
			//We may have different types but we shouldn't care since this is read-only
			//override_realtype() sets read-only on
			$this->cms_btnsort->override_realtype($this->sort_type);
			if ( !$this->cms_btnsort->init($rows) ) {
				return FALSE;
			}
			$sort_array[] = Cms_btnsort::INDEX_SORTKEY;
			if ( !osa_array_natsort($rows, $sort_array) ) {
				return FALSE;
			}
		}
		else {
			$sort_array[] = 'data';
			if ( !osa_array_natsort($rows, $sort_array) ) {
				return FALSE;
			}
		}
    	return $rows;
	}

	/*
	 * Gets strands, standards, benchmarks selected for a particular unit. This involves 5 tables
	 * This is the LT select popup
	 */
	function get_strand_tree($unitid, $type) {
		if ( !is_numeric($unitid) || !is_numeric($type) ) {
			return FALSE;
		}
		$this->db->select('b.*,s.data as standard,str.id as strandid,str.data as strand');
		$this->db->from('unit_target as u');
		$this->db->join('target_text as t', 'u.targetid=t.id', 'left');
		$this->db->join('benchmark as b', 't.benchmarkid=b.id', 'left');
		$this->db->join('standard as s', 'b.standardid=s.id', 'left');
		$this->db->join('strand as str', 's.strandid=str.id', 'left');
		$this->db->where('u.unitid', $unitid);
		$this->db->where('t.type', $type);
		$this->db->group_by('s.id,b.id');
		$this->db->order_by('str.id,s.strandid,s.id,b.id', 'asc');
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
	}

	/*
	 * Gets strands, standards, benchmarks, LTs selected for a particular department. This involves 4 tables
	 * This is the LT edit page
	 */
	/*
	function get_strand_tree_lt($deptid, $courseid, $type, $lt_only_flag=FALSE) {
		if ( !is_numeric($deptid) || !is_numeric($type) ) {
			return FALSE;
		}
		if ( $lt_only_flag ) {
			$join_direction = 'right';
		}
		else {
			$join_direction = 'left';
		}
		//table target_text can have a null benchmarkid so get benchmarkid from benchmark table
		$this->db->select('c.name coursename,t.*, b.id as realbenchid,b.data as benchmark,b.mingradeid,b.maxgradeid,s.data as standard,s.id as standardid,str.id as strandid,str.data as strand');
		$this->db->from('benchmark as b');
		//$this->db->join('target_text as t', "t.benchmarkid=b.id and t.type=b.type", 'left');
		//$this->db->join("(select * from target_text where courseid=$courseid) as t", "b.id=t.benchmarkid", 'left');
		//$this->db->join('target_text as t', "t.benchmarkid=b.id", 'left');
		$this->db->join('target_text as t', "t.benchmarkid=b.id and t.courseid=$courseid", $join_direction);
		$this->db->join('standard as s', 'b.standardid=s.id', 'left');
		$this->db->join('strand as str', 's.strandid=str.id', 'left');
		$this->db->join('course_sis  c', 'c.id=t.courseid', 'left');
		//$this->db->where('t.courseid', $courseid);
		$this->db->where('str.departmentid', $deptid);
		$this->db->where('b.type', $type);
		//$this->db->group_by('s.id,b.id');
		//$this->db->order_by('str.id,s.strandid,s.id,b.id', 'asc');
		//$this->db->order_by('str.data,s.data,s.data', 'asc');
		//$this->db->order_by('t.courseid', 'asc');
		$this->db->order_by('str.data', 'asc');
		$this->db->order_by('s.data', 'asc');

		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
	}
*/

	//Get learning targets for the edit LT page.
	//TODO: $lt_only_flag not used?
	function get_strand_tree_lt($deptid, $courseid, $type, $lt_only_flag=FALSE) {
		if ( !is_numeric($deptid) || !is_numeric($type) ) {
			return FALSE;
		}
		$this->load->library('cms/cms_btnsort');

		if ( $lt_only_flag ) {
			$join_direction = 'right';
		}
		else {
			$join_direction = 'left';
		}

		$table_benchmark   = $this->db->dbprefix('benchmark');
		$table_target_text = $this->db->dbprefix('target_text');
		$table_standard    = $this->db->dbprefix('standard');
		$table_strand      = $this->db->dbprefix('strand');

		$enable = CMS_DB_BOOLEAN_TRUE;


		//$orderby = '';
		$sort_array = array();
		if ( $this->config->item('cms_lt_importid_support') ) {
			//$orderby = 'str.importid_int,sta.importid_int,b.importid_int,';
			$sort_array = array('strand_importid','standard_importid','benchmark_importid');
		}
		//$orderby = "order by $orderby str.data,sta.data,b.id,t.data";
		$sort_array = array_merge($sort_array, array('strand','strandid','standard','standardid','benchmark','benchmarkid'));

		$query = 'select b.id as realbenchid, b.data as benchmark, b.mingradeid, b.maxgradeid,' .
					 	'sta.data as standard, sta.id as standardid, str.id as strandid, str.data as strand,' .
					 	"t.id, t.benchmarkid, t.courseid, t.select1, t.data, str.type, t.courseid, '{$this->sort_type}' sorttype," .
					 	'str.importid as strand_importid,sta.importid as standard_importid,b.importid as benchmark_importid ' .
					 "from $table_strand as str " .
					 "left join $table_standard as sta on sta.type = str.type and sta.strandid=str.id " .
					 "left join $table_benchmark as b on b.type=str.type and b.standardid=sta.id " .
					 "$join_direction join $table_target_text as t on t.type=b.type and t.benchmarkid=b.id and t.courseid={$courseid} " .
					 "where str.type={$type} and str.departmentid={$deptid} and " .
							"str.enabled={$enable} and sta.enabled={$enable} and b.enabled={$enable}";

		$res = $this->db->query( $query );
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	$tmp_sort_array = $sort_array;
    	$tmp_sort_array[] = 'data';
		if ( !osa_array_natsort($rows, $tmp_sort_array) ) {
			return NULL;
		}
		if ( $this->sort_type && count($rows) > 1 ) {
			//We use sort type for realtype becuase LT data doesn't really belong to the template.
			if ( !$this->cms_btnsort->reset($this->sort_filehash, $courseid, $this->sort_type, 'courseid', 'id', 'sorttype') ) {
				return NULL;
			}
	    	$this->cms_btnsort->pre_fetch_off();
			$this->cms_btnsort->ignore_empty_linkid();
			$this->cms_btnsort->set_segmentindex('benchmarkid');
			if ( $this->sort_read_only ) {
				$this->cms_btnsort->read_only();
			}
			if ( !$this->cms_btnsort->init($rows) ) {
				return NULL;
			}
			$sort_array[] = Cms_btnsort::INDEX_SORTKEY;
			if ( !osa_array_natsort($rows, $sort_array) ) {
				return NULL;
			}
		}
    	return $rows;
	}

	/*
	 * Gets all the selected target ids in an array so we can search by array value for the ids
	 */
	/*
	function get_selectedids($unitid, $type) {
		if ( !is_numeric($unitid) || !is_numeric($type) ) {
			return FALSE;
		}
		$this->db->select('targetid');
		$this->db->where('unitid', $unitid);
		$this->db->where('target_type', $type);
		$res = $this->db->get('unit_target');
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result_array();
    	return $rows;
	}*/

	function get_unit_targets($unitid, $type) {
		if ( !is_numeric($unitid) || !is_numeric($type) ) {
			return FALSE;
		}
		$this->db->where('unitid', $unitid);
		$this->db->where('target_type', $type);
		$res = $this->db->get('unit_target');
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
	}

	/*
		Updates the target text selections by delete and inserts
		This code was written incorectly but the bug never surfaced for 2 years because
		all the IDs (benchmarkids and targetids) were not in conflict so it was always deleting all and then insert all.
		Now, it is doing smart selective delete and selective inserts.
		TODO: Need to patch this for all installations - Mar/21/2011
		$ids - array index is the targetid and value is the benchmarkid
	*/
	function update($unitid, $type, $ids) {
		$selections = $this->get_unit_targets($unitid, $type);
		$insertids = $ids;
		if ( $selections ) {
			//Don't want to insert what is already in the DB
	    	foreach ($selections as $selection) {
	    		unset($insertids[$selection->targetid]);
	    	}
    	}

    	$sql = ''; $sep='';
    	foreach ($insertids as $targetid => $benchid) {
    		$sql .= $sep . "($unitid,$targetid,$benchid,$type)";
    		$sep = ',';
    	}
    	if ( $sql != '' ) {
    		$table = $this->db->dbprefix('unit_target');
    		$sql = "insert into $table (unitid,targetid,benchmarkid,target_type) values $sql";
    	}

    	//Get all the selected targetids in an array
    	$selected_targetids = array();
    	foreach ($ids as $targetid => $benchmarkid) {
    		$selected_targetids[] = $targetid;
    	}

    	$this->db->trans_start();
    		$this->db->where('unitid', $unitid);
    		$this->db->where('target_type', $type);
    		if ( count($selected_targetids) > 0 ) {
    			//if empty array then delete all
    			//This means nothing in the DB matches the user selected targets
    			$this->db->where_not_in('targetid', $selected_targetids);
    		}
    		//Deletes any targets not matching the selected ones
    		$this->db->delete('unit_target');
    		if ( $sql != '' ) {
    			//Insert what is not in the DB yet
    			$this->db->query($sql);
    		}
    	$this->db->trans_complete();
    	return $this->db->trans_status();
	}

	function delete($unitid,$targetid) {
		if ( !is_numeric($unitid) || !is_numeric($targetid))
	    	return FALSE;
	   //delete res_sort
		$table_res_sort = $this->db->dbprefix('res_sort');
		$this->db->where('fk1', $unitid);
		$this->db->where('fk3', $targetid);
		$this->db->delete($table_res_sort);

	   $this->db->where('unitid', $unitid);
		$this->db->where('targetid', $targetid);
		return $this->db->delete('unit_target');
	}

	/*
	 * Get one benchmark with strand and standard too
	 * For display on the LT edit popup
	 */
	function get_benchmark($benchmarkid, $type) {
		if ( !is_numeric($benchmarkid) || !is_numeric($type))
	    	return FALSE;
	   //It is intended to have benchmark.importid appear twice in the select section
	   //Cleaner to get benchmark_importid instead of importid
		$this->db->select('b.*, s.data as standard, str.data as strand, s.importid as standard_importid,' .
								'str.importid as strand_importid, b.importid as benchmark_importid');
		$this->db->from('benchmark as b');
		$this->db->join('standard as s', 'b.standardid=s.id', 'right');
		$this->db->join('strand as str', 's.strandid=str.id', 'right');
		$this->db->where('b.id', $benchmarkid);
		$this->db->where('b.type', $type);
		$res = $this->db->get();
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows[0];
	}

	/*
	 * Get all the targets belonging to a benchmark
	 * For the LT edit popup
	 */
	function get_targets_bybench($courseid, $benchmarkid, $type) {
		if ( !is_numeric($courseid) || !is_numeric($benchmarkid) || !is_numeric($type))
	    	return FALSE;
		$this->db->where('courseid', $courseid);
		$this->db->where('benchmarkid', $benchmarkid);
		$this->db->where('type', $type);
		$res = $this->db->get('target_text');
/*
	   $table = $this->db->dbprefix('target_text');
	   $sql = "select *,'{$this->sort_type}' sorttype from $table " .
	   		 "where courseid={$courseid} and benchmarkid=$benchmarkid and type=$type";
	   $res = $this->db->query($sql); */
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows;
	}

	/*
	 * Get a target from target_text by id
	 */
	function get_target_byid($targetid) {
		if ( !is_numeric($targetid) )
	    	return FALSE;
		$this->db->where('id', $targetid);
		$res = $this->db->get('target_text');
		if ( $res->num_rows() <= 0 )
    		return FALSE;
    	$rows = $res->result();
    	return $rows[0];
	}

	/*
	 * Delete a target_text record by id
	 */
	function delete_targettext($targetid) {
		if ( !is_numeric($targetid) )
	    	return FALSE;
	    ///////////////////////
	    // Added for history
	   $delete_lt = $this->get_target_byid($targetid);
	   if ( !$delete_lt )
	   	return FALSE;
	   $delete_lt->hist_id = NULL;
	   $delete_lt->hist_date = osa_dbdate();
	   $delete_lt->hist_type = CMS_LT_HIST_DELETE_TYPE;
	   ///////////////////////
		$this->db->trans_start();
			$this->db->insert('target_text_hist', $delete_lt);
			$this->db->where('targetid', $targetid);
			$this->db->delete('unit_target');
			$this->db->where('id', $targetid);
			$this->db->delete('target_text');

			//delete res_sort
			$table_res_sort = $this->db->dbprefix('res_sort');
			$this->db->where('fk3', $targetid);
			$this->db->delete($table_res_sort);
		$this->db->trans_complete();
    	return $this->db->trans_status();
	}

	/*
	 * Update/Add target_text records from the LT edit popup page
	 */
	function update_targets($courseid, $benchmarkid, $type, $curlt, $ids, $newlt) {
		if (!is_numeric($courseid) || !is_numeric($benchmarkid) || !is_array($curlt) ||
			 !is_array($newlt) || !is_array($ids) || !is_numeric($type))
			return FALSE;
		//Lets check to make sure all the ids belong to the same course
		if ( count($ids) >0 ) {
			$this->db->where_in('id', $ids);
			$this->db->where_not_in('courseid', array($courseid));
			$res = $this->db->get('target_text');
			if ($res->num_rows() > 0)
				return FALSE;
		}

		$table = $this->db->dbprefix('target_text');
		$table_hist = $this->db->dbprefix('target_text_hist');
		$sqladd = '';
		$sqlupdate = '';
		if ( count($curlt) > 0 ) {
			//Build multiple updates in one single sql statement
			$idstr = osa_getarrayvalue($ids);
			$sqlupdate = "update $table set data=case id ";
			//update test set data = case id when 1 then '1A' when 2 then '2A' else data end where id in (1,2);
			foreach ($curlt as $lt) {
				$sqlupdate .= " when {$lt['id']} then '{$lt['data']}'";
			}
			$sqlupdate .= " else data end,";
			$sqlupdate .= " select1=case id ";
			foreach ($curlt as $lt) {
				$value=$lt['select'];
				if (is_null($value))
					$value='NULL';
				$sqlupdate .= " when {$lt['id']} then {$value}";
			}
			$sqlupdate .= " else select1 end where id in ({$idstr}) and benchmarkid=$benchmarkid";
		}
		if ( count($newlt) > 0 ) {
			//Build multiple inserts in one single SQL statement
			$sqladd = "insert into $table (benchmarkid,courseid,type,select1,data) values ";
			$sep='';
			foreach ($newlt as $lt) {
				$value=$lt['select'];
				if (is_null($value))
					$value='NULL';
				$sqladd .= "{$sep}($benchmarkid,$courseid,$type,{$value},'{$lt['data']}')";
				$sep=',';
			}
		}

		//Get DB date here so we have the exact same date time for all history records
		$db_date = osa_dbdate();
		$this->db->trans_start();
		//Queries in funtions are not managed in this transaction
		//Have to look at it later
			if ($sqlupdate != '') {
				//Save original data before update
				$this->lt_add_mod_hist($curlt,$ids,$db_date);
				$this->db->query($sqlupdate);
			}
			if ($sqladd != '') {
				//Get all the LTs for this benchmark so we can get the newly added LTs later
				$db_lts_b4_insert = $this->get_targets_bybench($courseid, $benchmarkid, $type);
				$this->db->query($sqladd);
				$this->lt_add_new_hist($courseid, $benchmarkid, $type, $db_lts_b4_insert, $db_date);
			}
		$this->db->trans_complete();
    	return $this->db->trans_status();
	}

	//History of adding new LTs
	function lt_add_new_hist($courseid, $benchmarkid, $type, $db_lts_b4_insert, $db_date) {
		$id_array = array();
		if ( is_array($db_lts_b4_insert) ) {
			foreach($db_lts_b4_insert as $item) {
				$id_array[] = $item->id;
			}
		}
		$this->db->where('courseid', $courseid);
		$this->db->where('benchmarkid', $benchmarkid);
		$this->db->where('type', $type);
		if ( count($id_array) > 0 )
			$this->db->where_not_in('id', $id_array);
		$res = $this->db->get('target_text');
		if ( $res->num_rows > 0 ) {
			$rows = $res->result();
			foreach ($rows as $db_rec) {
				$db_rec->hist_id = NULL;
				$db_rec->hist_date = $db_date;
				$db_rec->hist_type = CMS_LT_HIST_ADD_TYPE;
				//Not the most efficent. Can change to multi inserts later
				$this->db->insert('target_text_hist', $db_rec);
			}
		}
	}

	//Add modify history for LTs
	function lt_add_mod_hist($curlt, $db_ids, $db_date) {
		$sql = '';
		if ( count($curlt) < 1 || count($db_ids) < 1 )
			return FALSE;
		$this->db->where_in('id', $db_ids);
		$res = $this->db->get('target_text');
		if ( $res->num_rows() <= 0 )
    		return '';
    	$rows = $res->result();
		$rows = osa_array_rekey($rows, 'id');
		foreach ($curlt as $lt_item) {
			if ( !array_key_exists('id', $lt_item) || !array_key_exists($lt_item['id'], $rows) )
				continue;
			$db_rec = $rows[$lt_item['id']];
			//Compare data/LT and KS selection
			if ( (array_key_exists('data', $lt_item) && $lt_item['data'] != $db_rec->data) ||
				  (array_key_exists('select', $lt_item) && $lt_item['select'] != $db_rec->select1) ) {
				$db_rec->hist_id = NULL;
				$db_rec->hist_date = $db_date;
				$db_rec->hist_type = CMS_LT_HIST_MODIFY_TYPE;
				if ( $lt_item['data'] != $db_rec->data )
					$db_rec->hist_mod_data = $lt_item['data'];
				if ( $lt_item['select'] != $db_rec->select1 )
					$db_rec->hist_mod_select1 = $lt_item['select'];
				//Not the most efficent. Can change to multi inserts later
				$this->db->insert('target_text_hist', $db_rec);
			}
		}
	}

	// get all department
    function  get_departments_bycourse($key='id', $toArray=FALSE) {
	    $this->db->select('c.id, d.id deptid, d.name ');
		$this->db->from('course_sis c');
		$this->db->join('department as d',"d.id=c.departmentid");

		$resobj = $this->db->get();
		if ( $resobj->num_rows() < 1 )
     	 	return FALSE;

 		$result = $resobj->result();
 		if ($key != '' && $toArray)
 			return $this->toArray($result, $key);
 		else
 			return $result;
    }

	function toArray($rows, $key='id') {
    	if (!is_array($rows))
    		return FALSE;

    	$data = array();
		foreach ($rows as $row) {
			$data[$row->$key] = $row;
		}
		return $data;
    }

	function get_department($data, $key, $field='name') {
    	if (!is_array($data))
    		return FALSE;

		$value = FALSE;

    	if (array_key_exists( $key, $data ))
    		$value = $data[$key]->$field;

		return $value;
   }

	function get_course_lt_link($courseid) {
		$this->db->select('*');
		$this->db->from('course_lt_link');
		if ($courseid!=FALSE)
		$this->db->where_in('courseid',$courseid);
		$resobj = $this->db->get();
		if ( $resobj->num_rows() <= 0 )
    		return FALSE;
    	$result = $resobj->result();
		return $result;
	}
}
?>