<?php
/**
 * outcomes.php - Outcomes and Skills controller
 *
 * @author $Author: dtong $
 * @version $Id: outcomes.php,v 1.24 2011/05/09 04:48:53 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/

class Outcomes extends CI_Controller{
	//We need a unitid to store in the resource table, so we use 0 since it is not used by actual units
	const HARDCODE_UNITID = 0;

	private $outcomes_type = FALSE;
	private $os_edit_template = FALSE;
	private $is_popup = FALSE;
	private $sort_type = FALSE;

	function __construct() {
		parent::__construct();
		$this->access_model->checkaccess_any('course_learningtarget_read');
		//$this->load->helper(array('form'));
		$this->load->model('unit/os_model');
		$this->load->model('course/course_model');
		$this->load->helper('form');
		$this->load->library('form_validation');
		$this->load->library('cms/cms_template/cms_template');
		osa_load_lang('target');
	}

	/*
	 * Read Outcomes and Skills
	 */
	function index($courseid) {
		if ( !is_numeric($courseid))
			return;
		$this->edit($courseid, CMS_ACTION_READ);
	}

	function popup($courseid) {
		$this->is_popup = TRUE;
		$this->index($courseid);
	}

	/*
	 * Initial OS edit page
	 */
	function edit($courseid, $action=CMS_ACTION_EDIT){
	    if ( !is_numeric($courseid)) {
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}
		$isedit = ($action == CMS_ACTION_EDIT);
		if ( $isedit ) {
			//Edit mode so we check to make sure user has edit rights
			$this->_checkEditAccess($courseid);
		}
		$this->init_template($courseid);
		$outcomes_type = $this->outcomes_type;
		$data->template = $this->os_edit_template;

		$data->outcomes = FALSE;
		$data->courseid = $courseid;
		$data->sort_type = $this->sort_type;

		if ( $this->is_popup ) {
		    $data->show_close_btn = TRUE;
		}
		//$strandid  = $this->config->item('cms_outcomes_skills_strandid');
		//$standardid = $this->config->item('cms_outcomes_skills_standardid');
		if ( !$isedit ) {
			$this->os_model->sort_read_only = TRUE;
		}
		$this->os_model->sort_type = $this->sort_type;
		$this->os_model->sort_filehash = CMS_BTNSORT_FILEHASH_OS;
		$this->load->library('cms/cms_btnsort');
		$tempos = $this->os_model->get_outcomes_skills_all($courseid, $outcomes_type, 1, 1, TRUE);
		if ( $tempos === NULL ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}

		if ( !$tempos ) {
			//We have no data yet for any outcomes and skills
		 	if ($isedit){
		 		$this->_prepare_edit_data($data);
		    	$data->isedit = $isedit;
		    	$data->nodatamsg = lang('outcomes_nodatamsg');
		    	$data->template = '';
				$data->coursename = '';
				$data->course_lnk = $this->course_model->get_course_lt_link($courseid);
		    	if ( ($course_dbobj = $this->course_model->get_course($courseid)) != FALSE ) {
					$data->coursename = $course_dbobj->name;
		    	}
		    	$data->btn_no_course_lt = $this->config->item('cms_no_multi_course_lt');
		    	$this->load->view('course/outcomes_skills_read_view', $data);
		 	}
		   else {
		   	//Read page and no data
		   	//Use the edit one anyway
		   	$this->_prepare_edit_data($data);
		    	$data->edit_link  = '';
		    	$data->delete_link = '';
		    	$data->isedit = FALSE;
		    	$data->nodatamsg = lang('outcomes_nodatamsg');
		    	$data->coursename = '';
		    	if ( ($course_dbobj = $this->course_model->get_course($courseid)) != FALSE ) {
					$data->coursename = $course_dbobj->name;
		    	}
		    	$data->btn_no_course_lt = $this->config->item('cms_no_multi_course_lt');
		    	$this->load->view('course/outcomes_skills_read_view', $data);
		    }
		    //We load the view already so stop processing by return
		    return;
		}

		//We got data so proceed
		$lastid   = '';
		$outcomes = array();
		$skills   = array();
		$coursename = '';
		foreach ($tempos as $row) {
			if ($lastid != $row->outcomesid && $lastid != '') {
				/*
				if (count($skills)-1 != 0) {
					$skills[count($skills)-1]->last = TRUE;
				}
				else {
					$skills[count($skills)-1]->none = TRUE;
				}*/
				$temp 			   = array($skills[0]->outcomes, $skills);
				$outcomes[$lastid] = $temp;

			    $lastid            = $row->outcomesid;
			    $skills            = array();
			    $row->first	       = TRUE;
			    $skills[]		   = $row;
			}
			else {
				/*if (count($skills)== 0) {
					$row->first	   = TRUE;
				}*/
				$skills[] 		   = $row;
				$lastid  		   = $row->outcomesid;
			}
			$coursename = $row->coursename;
		}
		if ( $coursename == '' ) {
			if ( ($course_dbobj = $this->course_model->get_course($courseid)) != FALSE )
				$coursename = $course_dbobj->name;
		}
		if ( !isset($outcomes[$lastid]) ) {
			/*
			$lastindex = count($skills)-1;
			if ($lastindex != 0)
				$skills[$lastindex]->last = TRUE;
			else
				$skills[$lastindex]->none = TRUE;*/
			$temp 			   = array($skills[0]->outcomes, $skills);
			$outcomes[$lastid] = $temp;
		}

		$data->outcomes = $outcomes;
		$data->edit_link = $this->config->item('cms_menu_target_addlink'); //'course/target/add_zm';
		$data->delete_link = $this->config->item('cms_menu_target_deletelink');
		$data->max_rows = $this->config->item('cms_course_outcomes_max_rows');
		$data->isedit = $isedit;
		$data->coursename = $coursename;
		$data->course_lnk = $this->course_model->get_course_lt_link($courseid);
		$data->btn_no_course_lt = $this->config->item('cms_no_multi_course_lt');
 		$this->load->view('course/outcomes_skills_read_view', $data);
	}

	function add($courseid, $outcomesid=FALSE) {
		if ( !osa_is_int_one($courseid) ) {
			return;
		}
		if ( !$this->_checkEditAccess($courseid) ) {
			//$this->load->view('template/ajax_error_view',
				//array('errormsg' => lang('gen_no_permission_ajaxmsg'), 'divid' => 'edit_lt'));
			exit;
		}
		$this->init_template($courseid);

		//$CI =  get_instance();
		$data->textarea_cols = $this->config->item('cms_outcomes_skills_textarea_cols');
		$data->textarea_rows = $this->config->item('cms_outcomes_skills_textarea_rows');
		$data->input_width = $this->config->item('cms_outcomes_skills_input_width');
		$data->input_height = $this->config->item('cms_outcomes_skills_input_height');
		$data->skill_rows = $this->config->item('cms_outcomes_skills_input_rows');
		$data->save_link = $this->config->item('cms_menu_target_savelink');
		$data->cancel_link = $this->config->item('cms_menu_target_editlink');
		$data->remove_link = $this->config->item('cms_menu_target_removelink');
		$data->inc_rows = $this->config->item('cms_course_outcomes_inc_rows');

		$data->courseid      = $courseid;
		$data->outcomesid    = $outcomesid;
		$this->os_model->sort_read_only = TRUE;
		$this->os_model->sort_type = $this->sort_type;
		$this->os_model->sort_filehash = CMS_BTNSORT_FILEHASH_OS;
		$data->outcomes = $this->os_model->get_course_outcomes_skills($courseid, $outcomesid, $this->outcomes_type);

  		$this->load->view('course/outcomes_skills_add_view', $data);
	}


	/*
	 * Popup LT edit page
	 */
	/*
	function addt($courseid, $benchid, $type) {
		if ( !osa_is_int_one($courseid) || !osa_is_int_one($benchid) || !osa_is_int_one($type)) {
			return;
		}
		if ( !$this->_checkEditAccess($courseid) ) {
			exit;
		}
		$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);

		$data->benchmark = $benchmark;
		$data->targets = $targets;
		$data->course = $course;
		$data->type = $type;
		$this->load->view('course/target_edit_view', $data);
	}
	*/



	function update($courseid, $benchmarkid, $type) {
		if ( !osa_is_int_one($courseid) || !osa_is_int_one($benchmarkid) || !osa_is_int_one($type)) {
			return;
		}
		$this->_checkEditAccess($courseid); //Exit if fails
		$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 ','

		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);
	}

	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;
	}

	/*
	//Will do ajax popup and exit if fails;
	function _checkEditAccessPopup($courseid) {
		if ( ! $this->access_model->checkaccess_courseeditor('course_description_write', $courseid) )
			  return ($this->access_model->checkaccess_any('admin_course_description_write', FALSE, TRUE, TRUE));
		return TRUE;
	}
	*/

	//Saves the editing items to DB and return to the main outcome listin page
	function save() {
		$keys = array_keys($_POST);

		if (!is_array($keys) || count($keys) == 0 ) {
			return FALSE;
		}
		$outcomesid = FALSE;
		$courseid   = FALSE;
		$nodata	    = TRUE;
		$outcomes   = FALSE;
		$skillsids  = Array();

		$pattern_add  = 'add';
		$pattern_edit = 'edit';

		$pattern_courseid   = 'courseid';
		$pattern_outcomesid = 'outcomesid';
		$pattern_outcomes   = 'outcomes';
		$pattern_skill 	    = 'skill';

		$add_skillsids = array();
		$edit_skillsids = array();

		foreach($keys as $key) {
			$temp = $_POST[$key];
			if ($temp !='') {
				$tok  = strtok($key,'_');
				$case = strtok('_');
				$num  = strtok('_');

				if ($key == $pattern_courseid)
					$courseid = $temp;
				elseif ($key == $pattern_outcomesid)
					$outcomesid = $temp;
				elseif ($key == $pattern_outcomes ) {
					$outcomes = $temp;
					$nodata   = FALSE;
				}
				elseif ($tok == $pattern_skill) {
					if ($case == $pattern_add)
						$add_skillsids[]  	 = $temp;
					elseif ($case == $pattern_edit)
						$edit_skillsids[$num]= $temp;
				}
			}
		}

		if ($nodata == TRUE) {
			echo osa_ajaxmsg(lang('outcomes_validate_save'));
			return FALSE;
		}
		if ( !osa_is_int_one($courseid) ) {
			return;
		}
		//Exit if fails
		$this->_checkEditAccess($courseid);
		$this->init_template($courseid);
		$outcomes_type = $this->outcomes_type;
		$save = $this->os_model->course_outcomes_save($courseid, $outcomesid, $outcomes_type,
																	 $outcomes, $add_skillsids, $edit_skillsids);
 	 	if ($save !== TRUE) {
			echo osa_ajaxmsg(lang('outcomes_save_error'));
			return FALSE;
		}
		$this->edit($courseid, $action=CMS_ACTION_EDIT);

	}

	/*
	 * Deletes a outcomes and skills then returns the os edit page for refresh purpose
	 */
	function delete($courseid, $outcomesid, $skillsid) {
		if ( !osa_is_int_one($courseid) || !osa_is_int_one($outcomesid) || !osa_is_int_one($skillsid) ) {
			return;
		}
		//Exit if fails
		$this->_checkEditAccess($courseid);
		$this->init_template($courseid);
		$outcomes_type = $this->outcomes_type;

		$target = $this->os_model->course_outcomes_target($skillsid, $outcomesid, $courseid, $outcomes_type);

		if ($target !== FALSE) {
			$delete = $this->remove($courseid, $outcomesid, $skillsid);
		}
		else {
			$delete = $this->os_model->course_outcomes_delete($skillsid, $outcomesid, $courseid, $outcomes_type);
			if ($delete === FALSE) {
				echo osa_ajaxmsg(lang('outcomes_faileddelete'));
				exit;
			}
		}
		$this->edit($courseid, $action=CMS_ACTION_EDIT);
	}

	/*
	 * Remove a outcomes and skills then returns the os edit page for refresh purpose
	 */
	function remove($courseid, $outcomesid, $skillsid=FALSE) {
		if ( !osa_is_int_one($courseid) || !osa_is_int_one($outcomesid) )
			return;
		//Exit if fails
		$this->_checkEditAccess($courseid);
		$this->init_template($courseid);
		$delete = $this->os_model->course_outcomes_all_delete($outcomesid, $courseid, $this->outcomes_type, $skillsid);
		if ($delete === FALSE) {
			echo osa_ajaxmsg(lang('outcomes_faileddelete'));
			exit;
		}
		if ($skillsid == FALSE) {
			$this->edit($courseid, $action=CMS_ACTION_EDIT);
		}
		return  $delete;
	}

	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,FALSE,TRUE);
		//course result
		$data->course_result = $this->course_model->get_course_all($notin_course,$desc_courseid);

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

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

		$data->href_save 	= base_url()."course/outcomes/insert_couse_lnk/$desc_courseid/";
		$data->href_select  = base_url()."course/outcomes/add_couse_lnk/$desc_courseid/";
		$data->href_refresh = base_url()."course/outcomes/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);
		}
	}

	//TODO: Should make all the outcomes&skills config with default like this so it will work even with no config
	//Prepares the data from site/org configuration file or use defaults if configuration is not available
	private function _prepare_edit_data($data) {
		$data->edit_link = $this->config->item('cms_menu_target_addlink');
		if ( $data->edit_link == FALSE ) {
			$data->edit_link = 'course/outcomes/add/';
		}
		$data->delete_link = $this->config->item('cms_menu_target_deletelink');
		if ( $data->delete_link == FALSE ) {
			$data->delete_link = 'course/outcomes/delete/';
		}
		$data->max_rows = $this->config->item('cms_course_outcomes_max_rows');
		if ( $data->max_rows == FALSE ) {
			$data->max_rows = 6;
		}
	}

	//Gets the unitmain object and get template related info from it
	private function init_template($courseid) {
		if ( $this->os_edit_template ) {
			//init already so do nothing
			return;
		}
		$this->load->library('unit/unitmain',
				array('action'=>CMS_ACTION_EDIT,'unitid'=>self::HARDCODE_UNITID , 'courseid'=>$courseid));

		if ( ($template = $this->unitmain->get_os_edittemplate()) === FALSE ) {
			osa_errorlog(__METHOD__ . ' - Failed to get Learning Target template');
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}
		$this->os_edit_template = $template;

		if ( !isset($template['_typeid']) || !osa_is_int_one($template['_typeid'])) {
			osa_errorlog(__METHOD__ . ' - _typeid does not exist in template data.', $template);
			echo osa_ajaxmsg(lang('gen_js_ajaxservererror'));
			exit;
		}
		//$outcomes_type = CMS_OUTCOMES_SKILLS_TYPE;
		//No more hard coding of types
		$this->outcomes_type = $template['_typeid'];
		$this->sort_type = osa_template_sort_type($template);
	}
}
?>
