<?php
/**
 * desc.php - Course description page
 *
 * @author $Author: wichai $
 * @version $Id: desc.php,v 1.51 2011/06/03 11:46:42 wichai Exp $
 * @copyright Copyright (c) 2011, Tiller Software Co., Ltd.
*/
class Desc extends CI_Controller{
	private $is_pdf = FALSE;

	function __construct() {
		parent::__construct();
        //Everyone should have at least desc read rights
        if ( !osa_is_function_name(array('indexsess','coursesumsess')) ) {
        	  $this->access_model->checkaccess_any('course_description_read');
        }
        $this->load->model('course/course_model'); // model course
        $this->load->helper('form');
        osa_load_lang('desc');
        $this->load->library('form_validation'); //set validatre
    }

	function index($courseid){
		//var_dump($this->course_model->testing());
		if ( !is_numeric($courseid))
			return;
		$data = $this->_get_viewdata($courseid);
		if ( $data['canedit'] ) {
			if ( $data['descobj'] ) {
				$this->_load_roview($data);
			}
			else {
				$this->_load_addview($data);
			}
		}
		else {
			$this->_load_roview($data);
		}
	}

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

	function coursesum($courseid) {
		if ( !is_numeric($courseid))
			return;
		$html = '';
		$data['courseid'] = $courseid;
		$data['course'] = $this->_get_viewdata($courseid);
		//Don't show the resources on the description page for the summary
		$data['course']['show_upload'] = FALSE;
		$data['course_sum'] = $this->course_model->get_course_summary($courseid);
	  	$html .= $this->load->view('course/course_summary_view', $data,true);
	  	echo $html;
	}

	function coursesumsess($courseid, $phpsessionid) {
		global $g_pdf_mode;
		$g_pdf_mode = TRUE;
		osa_init_phpci_sessions($phpsessionid);
		$this->access_model->checkaccess_any('course_description_read');
		$this->is_pdf = TRUE;
		$this->coursesum($courseid);
	}

	//Constructor checks read access already
	function read($descid) {
		if ( !is_numeric($descid) ) {
			echo osa_ajaxmsg(lang('desc_invaliddesc'));
			exit;
		}
		$descobj = $this->course_model->get_descbyid($descid);
		if ( !$descobj ) {
			echo osa_ajaxmsg(lang('desc_invaliddesc'));
			exit;
		}
		$data = $this->_get_viewdata($descobj->courseid);
		$this->_load_roview($data);
	}

	function edit($descid) {
		if ( !is_numeric($descid) ) {
			echo osa_ajaxmsg(lang('desc_invaliddesc'));
			exit;
		}
		$descobj = $this->course_model->get_descbyid($descid);
		if ( !$descobj ) {
			echo osa_ajaxmsg(lang('desc_invaliddesc'));
			exit;
		}
		$this->_checkEditAccess($descobj->courseid);
		$data = $this->_get_viewdata($descobj->courseid);
		$this->_load_editview($data);
	}

	private function _get_viewdata($courseid) {
		$coursename = '';
		$department = '';
		$descobj = $this->course_model->get_desc($courseid);
		$user = $this->login_model->getLogin();
		$canedit = $this->_iseditor($courseid, $user);
		$grades = $this->course_model->get_grades($courseid);
		$display_grades = $this->course_model->get_displaygrades($courseid);
		$editors = $this->course_model->getEditorUsers($courseid);
		$courseobj = $this->course_model->get_course($courseid);
		if ( $courseobj ) {
			$coursename = $courseobj->name;
			if (isset($courseobj->department_display) && $courseobj->department_display != '')
				$department = $courseobj->department_display;
			else
				$department = $courseobj->dept_name;
		}
		$editornames = osa_user_getname($editors, ', ', 4);
		$editorids = osa_getfield($editors, 'id');
		if ( $editorids == '' )
			$editorids = 'null';
		$canchangeeditor = $this->_can_change_editor();
		$data = array();
		$data['descobj'] = $descobj;
		$data['canedit'] = $canedit;
		$data['gradesobj'] = $grades;
		$data['display_grades'] = $display_grades;
		//$data['courseid'] = $courseid;
		$data['editornames'] = $editornames;
		$data['editorids'] = $editorids;
		$data['canchangeeditor'] = $canchangeeditor;
		$data['coursename'] = $coursename;
		$data['department'] = $department;
		$data['courseid'] = $courseid;
		$data['hidden'] = $courseobj->hidden;
		$data['is_pdf'] = $this->is_pdf;
		//Check admin and courseediter
		$data['coursehide']='display:none;';
		if ( $canedit && !$this->config->item('cms_not_show_hide_course_button')){
			$data['coursehide']='display:block;';
		}

		if ( $canchangeeditor ) {
			if ( $editors )
				$data['editorbutton'] = lang('desc_button_chageeditor');
			else
				$data['editorbutton'] = lang('desc_button_addeditor');
		}
		if ( $canedit ) {
			if ( $data['descobj'] ) {
				$data['editmodebutton'] = lang('desc_button_editmode');
				$data['cancelaction'] = 'read';
				$data['cancel_id'] = $descobj->id;
			}
			else {
				$data['cancelaction'] = 'index';
				$data['cancel_id'] = $courseid;
			}
		}
		$data['url'] = base_url()."course/desc/showhide/".$courseid.'/';
		if (isset($courseobj->hidden) && $courseobj->hidden == CMS_HIDDEN_YES) {
			$data['label']  = lang('desc_label_hide');
			$data['button'] = lang('desc_button_show');
			$data['url']   .= CMS_HIDDEN_NO;
			$data['imgeurl']= osa_imagepath() . 'folder_course.gif';
		} else {
			$data['label']  = lang('desc_label_show');
			$data['button'] = lang('desc_button_hide');
			$data['url']   .= CMS_HIDDEN_YES;
			$data['imgeurl']= osa_imagepath() . 'folder_course_hide.gif';
		}

		$data['show_resourcelist'] = $this->config->item('cms_desc_show_resourcelist');
		$data['show_readings'] = $this->config->item('cms_desc_show_readings');
		$data['show_upload'] = !$this->config->item('cms_desc_notshow_upload');
		return $data;
	}

	private function _can_change_editor() {
		return $this->access_model->checkaccess_any('admin_course_description_write', FALSE, FALSE, FALSE);
	}

	private function _load_roview($data) {
		global $g_pdf_mode;
		// hide on pdf mode
		if ( (!isset($g_pdf_mode) || $g_pdf_mode === FALSE) && ( (isset($data['courseid']) && osa_is_mycourse($data['courseid'])) ||
			  (isset($data['canedit']) && $data['canedit']) ) ) {
			if ( $this->config->item('cms_pdf_private_resource_select') ) {
				$data['show_pdf_private_resource_select'] = TRUE;
				$user = & osa_login_object();
				// if login hide private resource object = 1, no check
				if ( $user->hide_unit_private_resource ) {
					$data['checked_privateres'] = '';
				}
				else {
					$data['checked_privateres'] = 'checked="checked"';
				}
			}
		}
		$data['resources'] = $this->_load_resource(CMS_ACTION_READ, $data);
		$this->load->view('course/desc_ro_view',$data);
	}

	private function _load_editview($data) {
		$data['savebutton'] = lang('desc_button_save');
		$data['action'] = 'update';
		$data['resources'] = $this->_load_resource(CMS_ACTION_EDIT, $data);
		$this->load->view('course/desc_edit_view',$data);
	}

	private function _load_addview($data) {
		$data['savebutton'] = lang('desc_button_add');
		$data['action'] = 'add';
		//Can't add resource before we have a desc record
		$data['resources'] = $this->_load_resource(CMS_ACTION_READ, $data);
		$this->load->view('course/desc_edit_view',$data);
	}

	private function _iseditor($courseid, $user) {
		$canedit = $this->access_model->checkaccess_courseeditor('course_description_write', $courseid, $user);
		if ( !$canedit )
			$canedit = $this->access_model->checkaccess_any('admin_course_description_write', $user, FALSE, FALSE);
		return $canedit;
	}

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

	function seleditor($cur_editorid, $courseid) {
		$data = array();
		$userarray = array();
		$users = $this->course_model->get_users($courseid);
		foreach ($users as $user) {
			$userarray["{$user->id}"] = osa_user_getname($user);
		}
		$data['userarray']=$userarray;
		$data['cur_editorid'] = $cur_editorid;
		$data['is_allusers'] = false;
		$data['courseid'] = $courseid;
		$this->load->view('course/listuser_view',$data);
	}

	function seleditorall($cur_editorid, $courseid) {
		$data = array();
		$userarray = array();
		$users = $this->course_model->get_users_all();
		foreach ($users as $user) {
			$userarray["{$user->id}"] = osa_user_getname($user);
		}
		$data['userarray']=$userarray;
		$data['cur_editorid'] = $cur_editorid;
		$data['is_allusers'] = true;
		$data['courseid'] = $courseid;
		$this->load->view('course/listuser_view',$data);
	}


	function add($courseid) {
		$this->_checkEditAccess($courseid);
		$selected_grades = osa_chkbox_array('gradeid_');
		if ( count($selected_grades) <= 0 ) {
			echo osa_ajaxmsg(lang('desc_pleasecorrecterror') . lang('desc_displaygrademissing'));
			exit;
		}
		$this->form_validation->set_message('required',lang('desc_internalsystemerror'));
	   $this->form_validation->set_message('is_numeric',lang('desc_internalsystemerror'));
	   $this->form_validation->set_rules('editorid', 'Editor name','trim|required');
	   $this->form_validation->set_rules('courseid', 'Course ID','trim|required|is_numeric');
	   //$this->form_validation->set_rules('descid', 'Internal Description ID','trim|required|is_numeric');
	   $this->form_validation->set_rules('prerequisites', 'Prerequisites','trim');
	   $this->form_validation->set_rules('coursedescription', 'Coursedescription','trim');
	   $this->form_validation->set_rules('resourcelist', 'Resourcelist','trim');
	   $this->form_validation->set_rules('summerreadings', 'Summerreadings','trim') ;

	   if ( ! $this->form_validation->run()) {
			echo osa_ajaxmsg(lang('desc_pleasecorrecterror') . validation_errors());
			exit();
	   }
		$this->CI = get_instance();
	   $single_editor= $this->CI->config->item('cms_single_unit_editor');
	  	if ($single_editor !== FALSE){
		   if ( !is_numeric(set_value('editorid')) ) { //this can be "null" on the web form
		   	echo osa_ajaxmsg(lang('desc_pleasecorrecterror') . lang('desc_missingeditor') );
				exit();
		   }
	 	}
	   $user = $this->login_model->getLogin();
	   $data['courseid'] = set_value('courseid');
	   $data['lasteditorid'] = $user->id;
	   $data['creatorid'] = $user->id;
	   $data['modifydate']=osa_dbdate();
	   $data['createdate']=osa_dbdate();
	   $data['prerequisites'] = set_value('prerequisites');
	   $data['coursedescription'] = set_value('coursedescription');
	   $data['resourcelist'] = set_value('resourcelist');
	   $data['summerreadings'] = set_value('summerreadings');
		$editorid = set_value('editorid');
		if ( $this->course_model->add_des($data) ) {
			//load read only view
			if ( !$this->course_model->update_displaygrade($courseid, $selected_grades)) {
				//Not using transactions, it is not critical data
				echo osa_ajaxmsg(lang('desc_faileddisplaygradeupdate'));
				exit;
			}
			if ( $this->_can_change_editor() ) {
				$this->course_model->update_editor($data['courseid'], $editorid);
			 }
			$viewdata = $this->_get_viewdata($courseid);
			$this->load->view('course/desc_ro_view', $viewdata);
			return;
		 }
		 else {
			echo osa_ajaxmsg(lang('desc_faileddescupdate'));
			exit;
		 }
	}

	function update($courseid) {
		$this->_checkEditAccess($courseid);

		//Get grade ids and do checking
		$selected_grades = osa_chkbox_array('gradeid_');
		if ( count($selected_grades) <= 0 ) {
			echo osa_ajaxmsg(lang('desc_pleasecorrecterror') . lang('desc_displaygrademissing'));
			exit;
		}

		//The 2 required fields are hidden fields so just print internal error
	   $this->form_validation->set_message('required',lang('desc_internalsystemerror'));
	   $this->form_validation->set_message('is_numeric',lang('desc_internalsystemerror'));
	   //Editor id is no longer needed because the popup now writes to the user_course table
	   //$this->form_validation->set_rules('editorid', 'Internal Editor ID','trim|required|is_numeric');
	   //$this->form_validation->set_rules('courseid', 'Course ID','trim|required');
	   $this->form_validation->set_rules('descid', 'Internal Description ID','trim|required|is_numeric');
	   $this->form_validation->set_rules('prerequisites', 'Prerequisites','trim');
	   $this->form_validation->set_rules('coursedescription', 'Coursedescription','trim');
	   $this->form_validation->set_rules('resourcelist', 'Resourcelist','trim');
	   $this->form_validation->set_rules('summerreadings', 'Summerreadings','trim') ;

	   if ( ! $this->form_validation->run()) {
			echo osa_ajaxmsg(lang('desc_pleasecorrecterror') . validation_errors());
			exit();
	   }

	    $user = $this->login_model->getLogin();
	    $data['lasteditorid'] = $user->id;
	    $data['modifydate']=osa_dbdate();
	    $data['prerequisites'] = set_value('prerequisites');
	    $data['coursedescription'] = set_value('coursedescription');
	    $data['resourcelist'] = set_value('resourcelist');
	    $data['summerreadings'] = set_value('summerreadings');
		 //$editorid = set_value('editorid');
		 $descid = set_value('descid');

		 if ( $this->course_model->update_des($data, $courseid, $descid) ) {
			//load read only view
			if ( !$this->course_model->update_displaygrade($courseid, $selected_grades)) {
				//Not using transactions, it is not critical data
				echo osa_ajaxmsg(lang('desc_faileddisplaygradeupdate'));
				exit;
			}
			/*
			 * Popup handles the editor id update so no need the following code
			 if ( $this->_can_change_editor() ) {
				$this->course_model->update_editor($courseid, $editorid);
			 }
			 */
			$viewdata = $this->_get_viewdata($courseid);
			//(issue: 114) Resource not loaded after clicking save
			//$this->load->view('course/desc_ro_view', $viewdata);
			$this->_load_roview($viewdata);
			return;
		 }
		 else {
			echo osa_ajaxmsg(lang('desc_faileddescupdate'));
			exit;
		 }
	}
	function showhide($courseid, $showhide) {
	if ( !is_numeric($courseid) && !is_numeric($showhide))
			return FALSE;

		$result=$this->course_model->edit_showhide($courseid,$showhide);

		if ($result == 1)
			$result = 'success';

		echo $result;
		$this->load->library('cms/memory_table/unit_cache_table');
		$this->unit_cache_table->update();
	}

	function course_editor($courseid,$descid=FALSE) {
		$this->access_model->checkaccess_any('admin_assign_editor');
		$course_editer = $this->course_model->getEditorUsers($courseid);

	    $course = $this->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];
	   $this->CI = get_instance();
	   $data->single_editor = $this->CI->config->item('cms_single_unit_editor');
	   $data->coursename = $course->name;
		$data->courseid = $courseid;
		$data->usercourse = $course_editer;
		$data->descid = $descid;
		$data->user = $this->course_model->get_user($courseid);
		$this->load->view('course/course_editer_view',$data);
	}

	function add_course_editor($courseid,$single=FALSE) {
		  $this->access_model->checkaccess_any('admin_assign_editor');
        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 ) {
            return FALSE;
        }

      if ($this->course_model->insert_course_editor($courseid , $data,$single))
          echo 'success';
	}

	function del_course_editor($courseid,$userid) {
		$this->access_model->checkaccess_any('admin_assign_editor');
		if (is_numeric($courseid) == FALSE && is_numeric($userid) == FALSE)
            return FALSE;
		if ($this->course_model->update_course_editor($courseid , $userid,0))
          echo 'success';
	}

	//Printd the resource stage for resource refresh
	function stage($stagenum, $action, $descid) {
		$descobj = $this->course_model->get_descbyid($descid);
		$data = array('descobj' => $descobj);
		echo $this->_load_resource($action, $data, $stagenum);
	}

	//Actual function to load the reosurce
	private function _load_resource($action, $data, $stage_num=FALSE) {
		if ( $this->config->item('cms_desc_notshow_upload') ) {
			return '';
		}

		$descobj = FALSE;
		if ( array_key_exists('descobj', $data )) {
			$descobj = $data['descobj'];
		}
		if ( empty($descobj) ) {
			$action = CMS_ACTION_READ;
			$unitid = 0;
			$courseid = 0;
		}
		else {
			$unitid = $descobj->id;
			//$courseid = $descobj->courseid;
			$courseid = 0;
		}
		$this->load->library('unit/Unitmain',
									array('action'=>$action,'unitid'=>$unitid, 'courseid'=>$courseid,
											'unit_template'=>'course_desc') );
		if ( $stage_num === FALSE ) {
			$html = $this->unitmain->render();
			if ( strlen($html) < 50 ) {
				//Do this so we can get rid of the empty box
				return '';
			}
			return $html;
		}
		return $this->unitmain->render_stage($stage_num);
	}

}

?>