<?php
/**
 * maplt_model.php - Model file mapping learning targets
 *
 * @author $Author: dtong $
 * @version $Id: maplt_model.php,v 1.9 2011/02/11 09:09:24 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/

class Maplt_model extends CI_Model {

	function __construct() {
		parent::__construct();
		$this->load->Model('unit/unit_model');
	}

	function get($course_query,$template=FALSE) {
		$unittarget_table = $this->db->dbprefix('unit_target');
		$targettext_table = $this->db->dbprefix('target_text');
		$benchmark_table = $this->db->dbprefix('benchmark');
		$standard_table = $this->db->dbprefix('standard');
		$strand_table = $this->db->dbprefix('strand');
		$unit_table = $this->db->dbprefix('unit');
		$unitcache_table = osa_unit_cachetable();
		if ( $unitcache_table == FALSE )
			return FALSE;
		$unitcache_table = $this->db->dbprefix($unitcache_table);

		$CI =  get_instance();
		if ($CI->config->item('cms_outcomes_skills_mapping_type') == TRUE)
			$type = CMS_OUTCOMES_SKILLS_TYPE;
		else
			$type = CMS_LEARNING_TARGETS_TYPE;

		//where unit template
		$where = $this->where_template($template);
		//This query is fully optimized for searching and includes int. and unified units
		//Use left join for benchmark and standard tables becuase in case they are deleted but we still want to show the target_text
		//Note, this will break if unit_target data exists in non-stage 1 stages for integrated units
		//		  If this is the case then you have to modify it to look at the unit_target types for various stages
		$sql = "select t.id,t.data target,c.name coursename,b.data benchmark,sd.data standard,u.id unitid,u.title unit_title,template
					from $unit_table u
					join $unitcache_table uc on uc.id=u.id
					join $unittarget_table ut on ut.unitid=uc.compare_unifint_id
					join $targettext_table t on (ut.targetid=t.id and ut.target_type={$type})
					left join $benchmark_table b on t.benchmarkid=b.id
					left join $standard_table sd on b.standardid=sd.id
					left join $strand_table s on sd.strandid=s.id
					join ($course_query) c on u.courseid=c.id
					$where
					and s.enabled=" . CMS_DB_BOOLEAN_TRUE .
					" and sd.enabled=" . CMS_DB_BOOLEAN_TRUE .
					" and b.enabled=" . CMS_DB_BOOLEAN_TRUE .
					" order by c.name";

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

	//Function to add where clause for unit template. These are the 3 unit type selection on the mapping page
	private function where_template($template=FALSE) {
		$where = '';
		if ($template === FALSE)
			return $where;

		$sep ='';
		$_template = '';
		if ($template !== FALSE){
			foreach ($template as $value){
				if ($value != FALSE){
					$_template .= $sep."'".$value."'";
					$sep = ',';
				}
			}
			$where = " where u.template in(".$_template.")";
		}
		return $where;
	}
}