<?php
/**
 * target.php - Learning Target controller
 *
 * @author $Author: dtong $
 * @version $Id: target.php,v 1.43 2011/05/09 11:27:45 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/

class Target extends CI_Controller{
	function __construct() {
		parent::__construct();
		if ( !osa_is_function_name('indexsess') ) {
			$this->access_model->checkaccess_any('course_learningtarget_read');
		}
		//$this->load->helper(array('form'));
		$this->load->model('course/course_model');
		$this->load->model('unit/lt_model');
		//osa_load_lang('target');
		osa_load_lang('target');
		$this->load->helper('form');
		$this->load->library('form_validation');
	}

	/*
	 * Read learning targets
	 */
	function index($courseid){
		if ( !is_numeric($courseid))
			return;

		$this->edit($courseid, CMS_ACTION_READ);
	}
	function index_hist($courseid){
		if ( !is_numeric($courseid))
			return;

		$this->edit($courseid, CMS_ACTION_READ,TRUE);
	}

	function indexsess($courseid, $phpsessionid) {
		global $g_pdf_mode;
		$g_pdf_mode = TRUE;
		osa_init_phpci_sessions($phpsessionid);
		$this->access_model->checkaccess_any('course_learningtarget_read');
		$this->edit($courseid, CMS_ACTION_READ, TRUE);
	}

	/*
	 * Initial LT edit page
	 */
	function edit($courseid, $action=CMS_ACTION_EDIT, $pdf_mode=FALSE){
		if ( !is_numeric($courseid)) {
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}
		$isedit = ($action == CMS_ACTION_EDIT);

		//Check edit access, exists if false
		if ( $isedit ) {
			$this->_checkEditAccess($courseid);
			$lt_only_flag = FALSE;
			$data->editmodebutton = lang('target_button_pdf');
		}
		else {
			$lt_only_flag = TRUE;
		}
		$data->btn_no_course_lt = $this->config->item('cms_no_multi_course_lt');
		$data->closebutton = FALSE;
		if ( $pdf_mode ) { //Special handling for PDF reports
			$data->closebutton = $pdf_mode;
			if ( $this->_checkEditAccessPopup($courseid) ) {
				$lt_only_flag = FALSE;
			}
			else {
				$lt_only_flag = TRUE;
			}
			//Not really necessary but in case some idiot adds $data->editmodebutton above
			//or use the wrong $action flag
			if ( isset($data) && isset($data->editmodebutton) ) {
				unset($data->editmodebutton);
			}
		}

		//Get department, we could pass it from the url link, but it is safer to get it here
		if ( ($course = $this->course_model->get_course($courseid)) === FALSE ) {
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}
		$deptid = $course->departmentid;

		if ( ($dbgrades = $this->course_model->get_all_grades()) === FALSE ) {
			osa_errorlog(__METHOD__ . ' - Failed to get all grades');
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}

		//The paramaters passed to unitmain are not important here becuase
		//we just want the LT template and no precessing
		$this->load->library('unit/unitmain',
			array('action'=>CMS_ACTION_EDIT,'unitid'=>0, 'courseid'=>$courseid));
		if ( ($template = $this->unitmain->get_lt_edittemplate()) === FALSE ) {
			osa_errorlog(__METHOD__ . ' - Failed to get Learning Target template');
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}

		if ( ($type = osa_value($template, '_typeid', FALSE)) === FALSE ) {
			osa_errorlog(__METHOD__ . ' - Failed to get _typeid from template', $template);
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}

		$sort_type = osa_template_sort_type($template);
		$this->lt_model->sort_type = $sort_type;
		$this->lt_model->sort_filehash = CMS_BTNSORT_FILEHASH_LT;
		$data->sort_type = $sort_type;
		if ( !$isedit ) {
			$this->lt_model->sort_read_only = TRUE;
		}

		$db_struct = FALSE;
		if ( ($db = $this->lt_model->get_strand_tree_lt($deptid, $course->id, $type, $lt_only_flag)) !== FALSE ) {
			if ( $db === NULL ) {
				echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
				exit;
			}
			$db_struct = $this->_get_dbstruct($db, $course, $dbgrades);
		}
		$data->db_struct = $db_struct;
		$data->template = $template;
		$data->isedit = $isedit;
		$data->course = $course;
		$data->course_lnk = $this->course_model->get_course_lt_link($courseid);
		$this->load->view('course/target_view', $data);
	}

	/*
	 * Popup LT edit page
	 */
	function addt($courseid, $benchid, $type) {
		if ( !is_numeric($courseid) || !is_numeric($benchid) || !is_numeric($type))
			return;
		if ( !$this->_checkEditAccess($courseid) ) {
			//$this->load->view('template/ajax_error_view',
				//array('errormsg' => lang('gen_no_permission_ajaxmsg'), 'divid' => 'edit_lt'));
			exit;
		}
		//The paramaters passed to unitmain are not important here becuase
		//we just want the LT template and no precessing
		$this->load->library('unit/unitmain',
			array('action'=>CMS_ACTION_EDIT,'unitid'=>0, 'courseid'=>$courseid));
		if ( ($template = $this->unitmain->get_lt_edittemplate()) === FALSE ) {
			osa_errorlog(__METHOD__ . ' - Failed to get Learning Target template');
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}

		if ( ($type = osa_value($template, '_typeid', FALSE)) === FALSE ) {
			osa_errorlog(__METHOD__ . ' - Failed to get _typeid from template', $template);
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}

		$data = new stdClass();
		$sort_type = osa_template_sort_type($template);
		$this->lt_model->sort_type = $sort_type;
		$data->sort_type = $sort_type;

		$course = $this->course_model->get_course($courseid);
		$benchmark = $this->lt_model->get_benchmark($benchid, $type);
		$targets = $this->lt_model->get_targets_bybench($courseid, $benchid, $type);

		//Do the button sort if we have a result set and sort_type is present
		if ( $sort_type && is_array($targets) && count($targets)>0 ) {
			$this->load->library('cms/cms_btnsort');
			if ( !$this->cms_btnsort->reset(CMS_BTNSORT_FILEHASH_LT, $courseid, $sort_type, 'courseid') ) {
				echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
				exit;
			}
			$this->cms_btnsort->override_realtype($sort_type);
			$this->cms_btnsort->get_by_segment($benchid);
			if ( !$this->cms_btnsort->init($targets) ) {
				echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
				exit;
			}
		}

		if ( $this->config->item('cms_lt_importid_support') ) {
			$benchmark->strand = "$benchmark->strand_importid $benchmark->strand";
			$benchmark->standard = "$benchmark->standard_importid $benchmark->standard";
			$benchmark->data = "$benchmark->benchmark_importid $benchmark->data";
		}
		$data->benchmark = & $benchmark;
		$data->targets = & $targets;
		$data->course = & $course;
		$data->type = $type;
		$this->load->view('course/target_edit_view', $data);
	}

	/*
	 * Deletes a learning target and returns the target edit page for refresh purpose
	 */
	function delete($targetid) {
		if ( !is_numeric($targetid))
			return;
		if ( ($target = $this->lt_model->get_target_byid($targetid)) == FALSE ) {
			echo osa_ajaxmsg(lang('target_notargetdelete'));
			exit;
		}
		$this->_checkEditAccess($target->courseid); //Exit if fails

		if ( $this->lt_model->delete_targettext($targetid) == FALSE ) {
			echo osa_ajaxmsg(lang('target_faileddelete'));
			exit;
		}

		//Done deleting and no error so get the lt edit page to refresh it
		$this->edit($target->courseid, $action=CMS_ACTION_EDIT);
	}

	function update($courseid, $benchmarkid, $type) {
		if ( !is_numeric($courseid) || !is_numeric($benchmarkid) || !is_numeric($type))
			return;
		$this->_checkEditAccess($courseid); //Exit if fails
		//$keys = array_keys($_POST);
		//htmlentities()
		//var_dump($keys);
		$curlt = array();
		$curlt_ids = array();
		$newlt = array();
		foreach($_POST as $key => $value) {
			$value = trim($value);
			if ( $value == '' ) continue;
			$value = htmlentities($value, ENT_QUOTES, 'UTF-8');
			$tok = strtok($key,'_');
			//Gather data from new LTs
			if ( $tok == 'newlt' ) {
				$index = strtok('_');
				$select = NULL;
				$selindex = "newsel_$index";
				if ( array_key_exists($selindex,$_POST)) {
					$tmp = trim($_POST[$selindex]);
					if ( is_numeric($tmp) )
						$select = $tmp;
				}
				$newlt[] = array('data'=>$value, 'select'=>$select);
			}
			elseif ($tok == 'curlt') {
				//Gather data from existing LTs
				//$array = &$curlt;
				$targetid = strtok('_');
				if (!is_numeric($targetid)) continue;
				$select = NULL;
				$selindex = "cursel_$targetid";
				if ( array_key_exists($selindex,$_POST)) {
					$tmp = trim($_POST[$selindex]);
					if ( is_numeric($tmp) )
						$select = $tmp;
				}
				$curlt[] = array('id' => $targetid, 'data'=>$value, 'select'=>$select);
				$curlt_ids[] = $targetid;
			}
			else { continue; }
		}
		//$ids = osa_getarrayvalue($curlt_ids); //puts ids in a string delimited by ','
		//var_dump($newlt);
		//var_dump($curlt);
		//var_dump($curlt_ids);
		if ( count($curlt) > 0 || count($newlt) > 0) {
			if ( $this->lt_model->update_targets($courseid, $benchmarkid, $type, $curlt, $curlt_ids, $newlt) === FALSE ) {
				echo osa_ajaxmsg(lang('target_failedupdate'));
				exit;
			}
		}

		//Done deleting and no error so get the lt edit page for refresh purpose
		$this->edit($courseid, $action=CMS_ACTION_EDIT);
	}

	private function _get_dbstruct(&$db, &$course, &$grade) {
		$grades = array();
		foreach($grade as $record) {
			//Sort can distiguish the comparison between grade levels
			//It is too complex to put it in the query so do it manually here
			$grades[$record->id] = $record->sort;
		}
		$last_strandid='';
		$last_standardid='';
		$last_benchmarkid='';
		//This is actually using sort data from grade table
		$course_mingrade = false;
		$course_maxgrade = false;
		//fix bug mingrade and maxgrade
		if (isset($course->mingradeid) && $course->mingradeid !== FALSE && array_key_exists($course->mingradeid, $grades) )
			$course_mingrade = $grades[$course->mingradeid];
		if (isset($course->maxgradeid) && $course->maxgradeid !== FALSE && array_key_exists($course->maxgradeid, $grades) )
	 	 	$course_maxgrade = $grades[$course->maxgradeid];
		//echo "$course_mingrade - $course_maxgrade<br />";
		$db_struct = array();
		foreach($db as $record) {
			if (isset($record->mingradeid) && $record->mingradeid !== FALSE && array_key_exists($record->mingradeid, $grades) )
				$mingrade = $grades[$record->mingradeid];

			if (isset($record->maxgradeid) && $record->maxgradeid !== FALSE && array_key_exists($record->maxgradeid, $grades) )
				$maxgrade = $grades[$record->maxgradeid];

			if ( $mingrade > $course_maxgrade || $maxgrade < $course_mingrade ) {
				//Benchmark is set outside of the current course grade levels
				continue;
			}

			if ( $last_strandid != $record->strandid) {
				if ( $this->config->item('cms_lt_importid_support') ) {
					$db_struct[$record->strandid][0] = "{$record->strand_importid} {$record->strand}";
				}
				else {
					$db_struct[$record->strandid][0] = $record->strand;
				}
				$last_strandid = $record->strandid;
			}
			if ($last_standardid != $record->standardid) {
				//$benchmark[$record->standardid][0][0] = $record->benchmarkid;
				if ( $this->config->item('cms_lt_importid_support') ) {
					$db_struct[$record->strandid][$record->standardid][0] = "{$record->standard_importid} {$record->standard}";
				}
				else {
					$db_struct[$record->strandid][$record->standardid][0] = $record->standard;
				}
				$last_standardid = $record->standardid;
			}
			if ($last_benchmarkid != $record->realbenchid) {
				//$benchmark[$record->standardid][0][0] = $record->benchmarkid;
				if ( $this->config->item('cms_lt_importid_support') ) {
					$db_struct[$record->strandid][$record->standardid][$record->realbenchid][0] = "{$record->benchmark_importid} {$record->benchmark}";
				}
				else {
					$db_struct[$record->strandid][$record->standardid][$record->realbenchid][0] = $record->benchmark;
				}
				$last_benchmarkid = $record->realbenchid;
				//echo "*";
			}
			//if ( !is_null($record->data) )
			$db_struct[$record->strandid][$record->standardid][$record->realbenchid][] = $record;
			//var_dump($record);
		}
		return $db_struct;
	}

	private function _checkEditAccess($courseid) {
		if ( ! $this->access_model->checkaccess_courseeditor('course_description_write', $courseid) ) {
			  return $this->access_model->checkaccess_any('admin_course_description_write'); //This will exit if fails
		}
		return TRUE;
	}

	//check and no exit
	private function _checkEditAccessPopup($courseid) {
		if ( ! $this->access_model->checkaccess_courseeditor('course_description_write', $courseid) )
			  return ($this->access_model->checkaccess_any('admin_course_description_write', FALSE, FALSE, FALSE));
		return TRUE;
	}

	function couse_lnk($desc_courseid, $remove_courseid=FALSE) {
		$this->add_couse_lnk($desc_courseid,$remove_courseid,TRUE);
	}

	function add_couse_lnk($desc_courseid, $remove_courseid=FALSE,$couse_lnk=FALSE) {
		$this->_checkEditAccess($desc_courseid);
		$notin_course = FALSE;
		$sep = '';
		$course_select = '';
		$course_result = FALSE;
		if ($couse_lnk!=FALSE){
			$course_result = $this->course_model->get_course_lt_link($desc_courseid);
			if (is_array($course_result)) {
				foreach ($course_result as $row){
					$course_select .=$sep. $row->lt_courseid ;
					$sep = ',';
				}
			}
		}
		else{
			$course_select = $desc_courseid;
			if ($remove_courseid!=FALSE)
			$course_select = '';
		}
		if ($remove_courseid==FALSE){
			if (isset($_POST['courseids'])) {
				$course_select = implode(',', $_POST['courseids']) ;
	    	}
		}

    	if ( !is_numeric($desc_courseid) )
			return FALSE;

    	if ($course_select != '')
    		$sep = ',';

		if (isset($_POST['txt_courseids']) && $_POST['txt_courseids'] != FALSE)
    		$course_select .= $sep . $_POST['txt_courseids'];

    	$notin_course = explode(',',$course_select);
		$notin_course_desc = array();
    	foreach ($notin_course as $row){
    			if ($row != $remove_courseid){
    				$notin_course_desc[]= $row;
    			}
    	}
    	$notin_course=$notin_course_desc;
	 	$course_select = implode(',',$notin_course);
		$data->course_select	= $course_select;

		//course desc
		$data->course_desc = $this->course_model->get_course_all($notin_course,$desc_courseid,TRUE,TRUE);
		if ( !$data->course_desc ) {
			//To make the selection box appear
			$data->course_desc = array(' ');
		}
		//course result
		$data->course_result = $this->course_model->get_course_all($notin_course,$desc_courseid,TRUE);

	   $coursename = $this->course_model->get_course($desc_courseid);

	  $data->coursename =$coursename->name;
	   $data->courseid =$coursename->id;

		$data->href_save 	= base_url()."course/target/insert_couse_lnk/$desc_courseid/";
		$data->href_select  = base_url()."course/target/add_couse_lnk/$desc_courseid/";
		$data->href_refresh = base_url()."course/target/edit/$desc_courseid/";
   	$this->load->view('course/course_lt_link_view',$data);
	}
	function insert_couse_lnk($courseid) {
		$this->_checkEditAccess($courseid);
		if ($courseid!=FALSE){
				$lt_courseid = $_POST['txt_courseids'];
				$this->course_model->insert_course_lt_link($courseid,$lt_courseid);
		}
	}

}
?>