<?php
/**
 * course.php - Controller for handling input pages.
 *
 * @author $Author: dtong $
 * @version $Id: course.php,v 1.44 2011/05/09 11:27:45 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/
require_once(APPPATH . 'libraries/mapping/display_list.php');

class Course extends CI_Controller{
	//This is used as the session variable name. All admin features use this name
   private $divid = 'adminss'; //Used to be 'course'
	//To start a new display session or not
   private $new_display_session = FALSE;

	function __construct() {
		 parent::__construct();
 		 $this->access_model->checkaccess_any('admin_system_management');
	    $this->load->model('admin/admin_course_model');
	    osa_load_lang('admin');
	    $this->load->library('admin/admin_base');
	    $this->load->helper('form');
	    $this->load->library('form_validation');
	    $this->load->model('sort/searchsort_model');
	    osa_php_session_start();
	}

	function index() {
		$this->new_display_session = TRUE;
		$this->refresh(CMS_ADMIN_ENABLE);
	}

	function refresh($enableflag,$filter=FALSE,$page_con=FALSE) {
		if ( $enableflag != CMS_ADMIN_DISABLE && $enableflag != CMS_ADMIN_ENABLE && $enableflag != CMS_ADMIN_ALL ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}

	    //Add Config
		$url_add	 = 'admin/course/add/'.$enableflag;
		$div		 = 'course_input';
		$width		 = 600;
		$height		 = 520;
		$title_add	 = lang('admin_course_add_title');
		$imgaddname	 = osa_imagepath() . 'add_24.gif';
		$imgaddtitle = lang('admin_course_title_add');
	    $imgeadd     = $this->admin_base->newDhtmlWindow($url_add, $title_add, $width, $height, $div , $imgaddname,$imgaddtitle );

	 	//$divid    = 'course' ;
   		//$display  = $this->admin_base->init_display(CMS_ADMIN_COURSE_TYPE, $enableflag,$this->divid);
		if ( $this->new_display_session ) {
			$display = & $this->admin_base->init_display(CMS_ADMIN_COURSE_TYPE, $enableflag, $this->divid);
			$display->column_use_striptag[0] = TRUE;
			$display->column_use_striptag[2] = TRUE;
			//$display->column_data_align[2] = 'center';
		}
		else {
			$this->load->library('search/searchutil');
			$display = & $this->searchutil->get_session($this->divid);
			$display->selectlistitem = $enableflag;
			$display->reset_data();
		}
   	$display->type = '';
   	$display->menu  	 = lang('admin_menu_course');
   	$display->search  	 = lang('admin_course_search');
   	$display->pagetitle  = lang('admin_course_title');
   	$display->titles     = array(lang('admin_course_display_name'),
   				                 lang('admin_course_display_department'),
   				                 lang('admin_course_display_teachers'),
   				                 lang('admin_course_display_mingrade'),
   				                 lang('admin_course_display_maxgrad'),
   				                 lang('admin_course_display_enabled'),
   				                 "<span>$imgeadd</span>",
   				                 );
		$display->widths     = array('25%', '15%', '30%', '10%', '10%', '5%', '5%');
		$page			= 'page_content';
		$display->refresh = $page;
		$display->strand=array();
		$display->data_dep_sch =array();
		$display->standard =array();
		$display->filter=FALSE;
   	if ($filter != FALSE) {
			$display->filter = $filter;
   	}
		else {
			if (isset($_POST['filter']))
			$display->filter = $_POST['filter'];
		}
		//Fix (issue: 130) (issue:131)
		if ( !empty($display->filter) ) {
			$display->filter = rawurldecode($display->filter);
		}

	 	$data     = $this->admin_course_model->get_allcourse($enableflag,$display->filter);
		$splits = $this->admin_base->split($display->filter);
		if ($data != FALSE) {
			$course_recs = array();
			$user_recs = array();
			foreach ($data as $record) {
				$course_recs[$record->id] = $record;
				if ( !empty($record->userid) ) {
					if ( $record->iseditor == CMS_DB_BOOLEAN_TRUE ) {
						$user_name = osa_user_getname($record);
					}
					else {
						$user_name = '<span style="color:grey">' . osa_user_getname($record) . '</span>';
					}
					if ( array_key_exists($record->id, $user_recs) ) {
						$user_recs[$record->id] .= ', ' . $user_name;
					}
					else {
						$user_recs[$record->id] = $user_name;
					}
				}
			}
			foreach ($course_recs as $rows) {
				$usernames = '';
				if ( array_key_exists($rows->id, $user_recs)) {
					$usernames = $user_recs[$rows->id];
				}
				$enabled = $rows->enabled;
				if ($rows->enabled == CMS_ADMIN_DISABLE){
					$rows->enabled  = '<div class="hide">'.lang('admin_list_convert_disabled').'</div>';
				    $imgdelname		= osa_imagepath() . 'enabled_16.gif';
				    $imgdeltitle	= lang('admin_course_title_enable');
				    $massage		= lang('admin_course_message_enable');
				}elseif ($rows->enabled == CMS_ADMIN_ENABLE){
					$rows->enabled  = '<div class="show">'.lang('admin_list_convert_enabled').'</div>';
				    $imgdelname		= osa_imagepath() . 'disable_16.gif';
				    $imgdeltitle	= lang('admin_course_title_disable');
				    $massage		= lang('admin_course_message_disable');
				}

				//Edit Config
				$url_edit		= 'admin/course/edit/'.$rows->id.'/'.$enableflag;
				$div			= 'course_input';
				$title_edit		= lang('admin_course_edit_title');
				$imgeditname	= osa_imagepath() . 'edit_16.gif';
				$imgedittitle	= lang('admin_course_title_edit');
				$linktitle		= lang('admin_course_link_title');

				//Delete Config
				$url_del		= 'admin/course/delete/'.$rows->id.'/'.$enabled.'/'.$enableflag;
			    //Usercourse Config
				//$url_uc	        = 'admin/course/select/'.$rows->id.'/'.$enableflag;
				$url_uc = "admin/course/select/{$rows->id}/0/{$enableflag}";
				$url_uc_editor = "admin/course/select/{$rows->id}/1/{$enableflag}";
				$div			= 'course_input';
				$title_uc       = lang('admin_course_usercourse');
				$imgucename	    = osa_imagepath() . 'usercourse_16.gif';
				$imageuc_editor = osa_imagepath() . 'usercourse_editor.gif';
				$imguctitle	    = lang('admin_course_title_usercourse');

				//Coursegrade Config
				$url_cg		    = 'admin/course/coursegrade/'.$rows->id.'/'.$enableflag;
				$div			= 'course_input';
				$title_cg		= lang('admin_course_coursegrade');
				$imgcgname	    = osa_imagepath() . 'coursegrade_16.gif';
				$imgcgtitle	    = lang('admin_course_title_coursegrade');
			   $highlight_name = $this->admin_base->highlight($splits, $rows->name);

			   $linkname = $this->admin_base->linkDhtmlWindow($url_edit,
			    	$title_edit, $width, $height, $div ,$highlight_name, $linktitle );
			   $imgedit = $this->admin_base->newDhtmlWindow($url_edit,
			    	$title_edit, $width, $height, $div , $imgeditname, $imgedittitle );
			   $imgdel = $this->admin_base->delTarget($url_del, $page ,$massage, $imgdelname, $imgdeltitle);
			   $img_uc = $this->admin_base->newDhtmlWindow($url_uc,
			    	$title_uc, $width, $height, $div , $imgucename, $imguctitle );
			   $img_uc_editor = $this->admin_base->newDhtmlWindow($url_uc_editor,
			    	$title_uc, $width, $height, $div , $imageuc_editor, lang('admin_course_title_usercourse_editor') );
		      $img_cg = $this->admin_base->newDhtmlWindow($url_cg,
		       	$title_cg, $width, $height, $div , $imgcgname, $imgcgtitle );

			    //$imgedit  = '<span class="course_col_body_center_edit">' .$imgedit. '</span>';
			    //$imgdel   = '<span class="course_col_body_center_del">'  .$imgdel. '</span>';

				$department_name = $rows->department;
				if ( !$rows->department_enabled ) {
					$department_name = "<font color=\"grey\">$department_name</font>";
				}
				$tmp_buttons = "<nobr>$imgdel $imgedit $img_uc $img_uc_editor $img_cg</nobr>";
		 		$temp = array($linkname, $department_name, $usernames, $rows->mingrade,
		 		              $rows->maxgrade, $rows->enabled, $tmp_buttons);
				$display->add($temp);
			} //foreach
		}//if $data
		$this->admin_base->load_view($display);
	}

	//function select($courseid, $list=CMS_ADMIN_ENABLE, $descid=FALSE) {
	function select($courseid, $iseditor=FALSE, $enable_flag=FALSE, $refresh_urlpart='course') {
		if ( !osa_is_int($courseid) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		$assigned_users = $this->admin_course_model->get_user_course($courseid);
		$mod_assigned_users = array();
		$notin_ids = FALSE;
	   if ( $assigned_users !=FALSE ) {
	    	$notin_ids = array();
	     	foreach ($assigned_users as $key => $value) {
	     		if ( ($iseditor && !empty($value->iseditor)) || (!$iseditor && empty($value->iseditor)) ) {
	     			//This shows the list of read-only teachers or editors.
		    		$mod_assigned_users[$key] = & $assigned_users[$key];
	     		}
	     		if ( !empty($value->iseditor) || (!$iseditor && empty($value->iseditor) ) ) {
	     			//Editors are always excluded, read-only teachers are listed as available users in the assign editor window
	     			$notin_ids[] = $value->id;
	     		}
	     	}
	    }

	   $course = $this->admin_course_model->get_course($courseid);
		if ($course==FALSE || count($course)==0) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}

	   $row= $course[0];
	   $data->coursename = $row->name;
		$data->courseid = $courseid;
		$data->usercourse = $mod_assigned_users;
		$data->user = $this->admin_course_model->get_user($notin_ids);
		//$data->selectlistitem = $list;
		$data->iseditor = $iseditor;
		if ( $iseditor == FALSE ) {
			$data->iseditor = '0';
		}
		$data->enable_flag = $enable_flag;
		$data->refresh_urlpart = $refresh_urlpart;
		$this->load->view('admin/user_course_view',$data);
	}

	function coursegrade($courseid, $list=CMS_ADMIN_ENABLE) {
		$course_grade = $this->admin_course_model->get_course_grade($courseid);
	   //$notin_ids  = array();
	    /*
	    if ( $course_grade !=FALSE ) {
	     	foreach ($course_grade as $value) {
		    	$notin_ids[] = $value->id;
	     	}
	    }*/
	    $course = $this->admin_course_model->get_course($courseid);
			if ($course==FALSE || count($course)==0) {
				// show error message
				echo 'show error message: no data';
				return FALSE;
			}

	    $row= $course[0];
	    $g1 =$row->gmin;
	    $g2 =$row->gmax;
	    $gmin=$g1;
	    $gmax=$g2;
	    if ($g1 > $g2){
	    	$gmin=$g2;
	    	$gmax=$g1;
	    }


	    $data->coursename   	= $row->name;
		$data->courseid   		= $courseid;
		$data->course_gradeall  = $this->admin_course_model->get_gradebyin($gmin,$gmax,FALSE);
		$data->course_grade 	= $course_grade;


		//$data->template 	= $this->admin_base->getconfig(CMS_ADMIN_COURSEGRADE_TYPE);
		$data->selectlistitem = $list;

		$this->load->view('admin/course_grade_view',$data);
	}

   function insert_usercourse($courseid, $iseditor=FALSE) {
        if (is_numeric($courseid) == FALSE)
            return FALSE;
        if (isset($_POST['data'])==FALSE || is_array($_POST['data']) ==FALSE)
            return FALSE;
        $data = $_POST['data'];
        if ($data == FALSE || is_array($_POST['data']==FALSE)) {
            return FALSE;
        }
        if ($this->admin_course_model->insert_user_course($courseid , $data, $iseditor)) {
            echo 'success';
        }
	}

 function insert_coursegrade($courseid) {
 	if (is_numeric($courseid) != FALSE)
		$data = FALSE;

	 	foreach ($_POST as $key => $value) {
	 		if ($key != 'bustcache') {
	 			$data = $value ;
	 		}
	    }
	    $grade=array();
 		$en = count($data);
		for ($i=0;$i< $en;$i++) {
			$gradeid   = $data[$i]['gradeid'];
			if($gradeid!=FALSE || $gradeid!=''){
			$grade[]=$gradeid;
			}
		}

	$result=$this->admin_course_model->insert_course_grade($courseid , $grade);
	if ($result==1)
		$result = 'success';
	echo $result;
	}

	function insert() {
		$data = array();
	 	$courseid = FALSE;
	    $keys = array_keys($_POST);

		$this->form_validation->set_rules('name', 'Name', 'required') ;
		if ( ! $this->form_validation->run()) {
			echo osa_ajaxmsg(validation_errors());
		    exit();
		}

		if ($_POST['departmentid'] == 0){
	 		echo osa_ajaxmsg(lang('admin_course_error_department') );
		    exit();
	 	}
		if ($_POST['mingradeid'] == 0){
	 		echo osa_ajaxmsg(lang('admin_course_error_mingrade') );
		    exit();
	 	}
		if ($_POST['maxgradeid'] == 0){
	 		echo osa_ajaxmsg(lang('admin_course_error_maxgrade') );
		    exit();
	 	}
	 	$this->grade_validation();

	    foreach ($keys as $key) {
	    	$key = strtolower($key);
			if ($key != 'bustcache' && $key != 'id') {
	    	 	 $value = trim($_POST[$key]);
	    	 	 if ($key == 'enabled' || $key == 'autogen') {
		    	  	 if ($_POST[$key] == 'on')
		    		 	 $value = 1;
		    		 else
		    			 $value = 0;
	    	 	 }
	    		 $data[$key] = $value;
			}
			elseif ($key == 'id') {
				$courseid = $_POST[$key];
			}
	    }
	   $data['createdate'] = osa_dbdate();
	  $result= $this->admin_course_model->add_course($data);
	  if ($result==1)
			$result = 'success';
		echo $result;
	}

	function update() {
		$data = array();
	    $courseid = FALSE;
	    $keys = array_keys($_POST);

	   $this->form_validation->set_rules('name', lang('admin_course_col_name'), 'trim|required');
	   $this->form_validation->set_rules('tree_sort', lang('admin_course_col_tree_sort'), 'trim|required') ;
		if ( ! $this->form_validation->run()) {
			echo osa_ajaxmsg(validation_errors());
		   exit();
		}
		if ($_POST['departmentid'] == 0){
	 		echo osa_ajaxmsg(lang('admin_course_error_department') );
		    exit();
	 	}
		if ($_POST['mingradeid'] == 0){
	 		echo osa_ajaxmsg(lang('admin_course_error_mingrade') );
		    exit();
	 	}
		if ($_POST['maxgradeid'] == 0){
	 		echo osa_ajaxmsg(lang('admin_course_error_maxgrade') );
		    exit();
	 	}
	 	$this->grade_validation();

	    foreach ($keys as $key) {
	    	$key = strtolower($key);
			if ($key != 'bustcache' && $key != 'id') {
	    	 	 $value = trim($_POST[$key]);
	    	 	 if ($key == 'enabled' || $key == 'autogen' ) {
		    	  	 if ($_POST[$key] == 'on')
		    		 	 $value = 1;
		    		 else
		    			 $value = 0;
	    	 	 }
	    		 $data[$key] = $value;
			}
			elseif ($key == 'id') {
				$courseid = $_POST[$key];
			}
	    }
		$data['modifydate'] = osa_dbdate();

 		if ( $courseid == FALSE || is_numeric($courseid)== FALSE ) {
				echo osa_ajaxmsg('error' . $courseid);
				exit;
 		}
		$result=$this->admin_course_model->update_course($courseid , $data);
		if ($result==1)
			$result = 'success';
		echo $result;
	}

    function add($enableflag=FALSE) {
     	$this->edit(FALSE, $enableflag, CMS_ADMIN_ADD);
	}

	function edit($courseid,$list, $action=CMS_ADMIN_EDIT) {
		if ( is_numeric($list) == FALSE || $list < CMS_ADMIN_DISABLE || $list > CMS_ADMIN_ALL ) {
			// show error message
			echo 'error list';
			return FALSE;
		}

	    $data = FALSE;
	    $data->page     = $this->admin_base->getpage(CMS_ADMIN_COURSE_TYPE);
        $data->selectlistitem = $list;
	   	$data->department = $this->admin_course_model->get_department();
		$data->grade = $this->admin_course_model->get_grade();
	   	$data->action = $action;

	    if ($action == CMS_ADMIN_EDIT ) {
			$course = $this->admin_course_model->get_course($courseid);
			if ($course==FALSE || count($course)==0) {
				// show error message
				echo 'show error message: no data';
				return FALSE;
			}

	   		$data->data   = $course;
	   		$row= $course[0];
	   		$selected_dep = $row->departmentid;
	   		$selected_grade_min = $row->mingradeid;
	   		$selected_grade_max = $row->maxgradeid;
	   		$selected_display 	= $row->name;
	    }
	    elseif ($action == CMS_ADMIN_ADD ) {
	    	$selected_dep      = $data->department[0];
	   		$selected_grade_min = $data->grade[0];
	   		$selected_grade_max = $data->grade[0];
	   		$selected_display=lang('admin_course_add_head');
	    }

	    $data->selected_dep       = $selected_dep;
	   	$data->selected_grade_min = $selected_grade_min;
	   	$data->selected_grade_max = $selected_grade_max;
	   	$data->selected_display   = $selected_display;

	   	$this->CI =  get_instance();
		//$divid = 'course' ;
		$temp  = $this->CI->searchsort_model->getSort($this->divid);
		$data->filter=$temp->filter;
    	if ($temp->filter==FALSE && $temp->filter=='')
    		$data->filter = FALSE;

	  $this->load->view('admin/course_input_view',$data);
	}

	function delete($courseid,$enabled,$list) {
	if ( is_numeric($courseid)==FALSE ||  is_numeric($enabled)==FALSE ||  is_numeric($list)==FALSE ) {
			// show error message
			echo 'error list';
			return FALSE;
		}

		if ( $enabled < CMS_ADMIN_DISABLE && $enabled > CMS_ADMIN_ENABLE ) {
			// show error message
			echo 'error list';
			return FALSE;
		}

		if ($enabled==CMS_ADMIN_DISABLE)
			$enabled= CMS_ADMIN_ENABLE;
		else
		    $enabled= CMS_ADMIN_DISABLE;

		$this->CI =  get_instance();
		//$divid = 'course' ;
		$course  = $this->CI->searchsort_model->getSort($this->divid);

	    $filter= FALSE;
	    if ($course->filter!=FALSE && $course->filter!='')
	    $filter=$course->filter;
	   $this->admin_course_model->del_course($courseid,$enabled);
	   $this->refresh($list,$filter);
	}

    function delete_usercourse($courseid, $userid, $iseditor=FALSE) {
		 if ($this->admin_course_model->del_user_course($courseid,$userid))
       	echo 'success';
	 }

	function delete_usercourse_all($courseid, $iseditor=CMS_DB_BOOLEAN_FALSE) {
		 if ($this->admin_course_model->del_user_courseall($courseid,FALSE, $iseditor))
       	echo 'success';
	 }

   function delete_coursegrade($courseid,$gradeid) {
	    $this->admin_course_model->del_course_grade($courseid, $gradeid);
		 $this->coursegrade($courseid);
	}
/*
	function search() {
	 $keys = array_keys($_POST);
	    foreach ($keys as $key) {
	    	if ($key != 'bustcache') {
	    		$value = trim($_POST[$key]);
				if ($key == 'filter'){
					$filter = $value;
				}
				elseif ($key == 'filters'){
					$enableflag = $value;
				}

			}
	    }

    	echo $enableflag.'/'.$filter;
	}
*/

	function search() {
		$this->access_model->checkaccess_any('admin_system_management');
		$this->load->library('search/searchutil');
		$display = & $this->searchutil->get_session($this->divid);
		//$display->selectlistitem = $enableflag;
		$filter = FALSE;
		if ( array_key_exists('filter', $_REQUEST) ) {
			$filter = $_REQUEST['filter'];
		}
		$this->refresh($display->selectlistitem, $filter);
	}

	private function grade_validation() {
		$grade = $this->admin_course_model->get_gradebysort();
	 	if (isset($grade)){
	 		$mingrade = $grade[$_POST['mingradeid']];
	 		$maxgrade = $grade[$_POST['maxgradeid']];
	 	}

	 	if ($maxgrade < $mingrade){
	 		echo osa_ajaxmsg(lang('admin_grade_massage_error'));
		    exit();
	 	}
	}

}
?>