<?php
/**
 * goal.php - Controller for handling input pages.
 *
 * @author $Author: dtong $
 * @version $Id: goal.php,v 1.28 2011/05/10 16:11:56 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/

require_once(APPPATH . 'libraries/mapping/display_list.php');

class goal extends CI_Controller{
	//private $hidden_title_pdf = FALSE;
	private $CI;
	private $new_display_session = FALSE;

	function __construct() {
		parent::__construct();
		if ( !osa_is_function_name(array('loadpdf', 'loadpdfall')) ) {
			$this->access_model->checkaccess_any('goal_read');
		}
		$this->load->helper('form');
		osa_load_lang('admin');
		$this->load->library('admin/admin_base');
		$this->load->library('form_validation');
		$this->load->model('auth/login_model');
		$this->load->model('admin/user_model');
		$this->load->model('admin/loginas_model');
		$this->load->model('sort/searchsort_model');
		osa_load_lang('unit');
		osa_load_lang('goal');
		$this->load->model('goal/goal_model');
		$this->load->model('template/linkunit_model');
		$this->CI = get_instance();
	}

	function create_goal() {
		$stagenum = FALSE;
		$data = '';
		$div = 'create_goal';
		$action = CMS_ACTION_READ;
		$entryid = FALSE;
		$type = FALSE;
		$completedate = FALSE;

		$data->div = $div;
		$data->pdf_mode = FALSE;
		$data->goal_write = FALSE;
		$data->mode_edit = FALSE;
		$data->editornames = FALSE;
		$data->goalid = FALSE;
		$data->type = $type;
		$data->entryid = $entryid;
		$data->title =lang('goal_create_title');
		$data->title2 = '';
		$data->create_goal = TRUE;
		$data->btn_addteam_member = FALSE;
		$div = 'create_goal';
		$template = $this->get_goal_obj();
		$data->entry_title = '';
		$data->hide_entrypoint = $this->config->item('cms_goal_hide_entrypoint');
		$data->goal_title = '';
		//Always fill in a defualt title
		if ($this->config->item('cms_goal_use_default_title'))
   		$data->goal_title = sprintf(lang('goal_create_default_title'),date("Y"));

	  	if ( isset($template->entry_title) )
	  		$data->entry_title = $template->entry_title;
	  	$data->item = array();
	  	if ( isset($template->entry_types) )
 			$data->item = $template->entry_types;
		$data->selectitem = $type;
		$goal = $this->goal_model->get_mygoal($this->get_userid(),$this->get_goal_types());
		if ($goal == FALSE ){
			$goal = array();
		}
		$data->mygoal = $goal;
		$data->stagenum = FALSE;
		$data->unitbody = FALSE;

		$this->load->view('goal/goal_create_view',$data);
	}
	function save_goal() {
		$data = FALSE;
		if(!isset($_POST['txttitle'])){
			//validate hidden value
			return FALSE;
		}
		$this->form_validation->set_rules('txttitle', 'Title', 'required|max_length[1024]') ;
		if ( ! $this->form_validation->run()) {
			echo osa_ajaxmsg(lang('goal_required_title'));
			exit;
		}
		$hide_entrypoint = $this->config->item('cms_goal_hide_entrypoint');
		$this->form_validation->set_rules('selected', 'Selected Entry Point', 'required|is_natural_no_zero') ;
		if ( ! $this->form_validation->run() && $hide_entrypoint === FALSE) {
			echo osa_ajaxmsg(lang('goal_required_entry'));
			exit;
		}
		$type = set_value('selected');
		//default entrypoint type (type=99999)
		if (isset($type) && $type == FALSE)
			$type = CMS_DEFAULT_ENTRYPOINT_TYPE;
		//add goal
		$goalid = $this->add_goal(set_value('txttitle'));
		if(is_numeric($goalid) == FALSE) { // verify add
			echo osa_ajaxmsg(lang('goal_required_title'));
   		exit();
		}
		//add entry point
		$entryid = $this->add_entry_point($goalid,$type);
	 	if(is_numeric($entryid) == FALSE) { // verify add
		 	echo osa_ajaxmsg(lang('goal_required_entry'));
   		exit();
		}
		$this->read($goalid, $entryid, $type);
		//This previous link is needed since saving the goal is like reading the goal
		//Can't go back to save goal again and has to be read_goal
		//osa_previous_url("goal/goal/read_goal/$goalid");
		osa_url_history(CMS_URLHISTORY_GOAL, "goal/goal/read_goal/$goalid");
	}
	private function add_goal($title) {//add goal
		if(($creatorid = $this->get_userid()) == FALSE) {
			//not found object user login
			echo osa_ajaxmsg(lang('goal_menu_message_crategoal'));
			return;
		}
		if ($this->config->item('cms_multi_goals') == FALSE){//cms_multi_goals != TRUE
			if($this->goal_model->get_goalall($creatorid) != FALSE) {
				echo osa_ajaxmsg(lang('goal_menu_message_crategoal'));
		      return;
			}
		}
		$data = FALSE;
		$data->title = $title;
		$data->creatorid = $creatorid;
		$data->createdate = osa_dbdate();
		$goalid = $this->goal_model->add_goal($data);
		return $goalid;
	}
	private function add_entry_point($goalid=FALSE,$type=FALSE) {
		$entry = FALSE;
		$entry->type = $type;
		$entry->goalid = $goalid;
		$entry->creatorid = $this->get_userid();
		$entry->title = lang('goal_create_title');
		$entry->createdate = osa_dbdate();
		$entryid = $this->goal_model->add_goal(FALSE,$entry);
		return $entryid;
	}
	function update_goal($goalid=FALSE) {
		$data = FALSE;
		if(!isset($_POST['txttitle'])){
			//validate hidden value
			return FALSE;
		}
		if(!isset($_POST['action'])){
			//validate hidden value
			return FALSE;
		}

		$this->form_validation->set_rules('txttitle', 'Title', 'required|max_length[1024]') ;
		if ( ! $this->form_validation->run()) {
			echo osa_ajaxmsg(lang('goal_required_title'));
			exit;
		}
		elseif ($goalid != FALSE) {
			//edit title2 from goal
			$data->title = set_value('txttitle');
			if($this->goal_model->edit_goal($goalid, $data) == FALSE) {  // verify add
				echo osa_ajaxmsg(lang('goal_required_title'));
		   	exit();
			}
		}

		$action = $_POST['action'];
		$goal = $this->goal_model->get_entry_bygoal($goalid);

		if ($action == CMS_ACTION_READ)
			 $this->read($goal->goalid, $goal->entryid, $goal->type);
		elseif ($action == CMS_ACTION_EDIT)
			 $this->edit($goal->goalid, $goal->entryid, $goal->type);
	}

	function update_entry($goalid=FALSE) {
		$entry_point = $this->goal_model->get_entry_bygoal($goalid);
		$data = FALSE;
		$data->modifydate = osa_dbdate();
		if(isset($_POST['fielddate']))
			$data->completedate = $_POST['fielddate'];
		$this->goal_model->edit_entry_point($entry_point->entryid,$data);//edit modifydate and completedate from entry_point
	}
	function mapping_goal($goalid=FALSE,$type=FALSE,$entryid=FALSE) {
		$this->read_goal($goalid,$type,$entryid,TRUE);
	}
	function select($mode_edit=0,$goalid=FALSE,$type=FALSE,$div_pop =FALSE) {
		if ($mode_edit == 0){
				$entryid = FALSE;
				if ($type != FALSE && $goalid != FALSE){
					$goal = $this->goal_model->get_goalbyentryid($type,$goalid);
					if (isset($goal->entryid)){
						$entryid = $goal->entryid;
					}
				}
				if (isset($_POST['div_pop']))
					$div_pop = $_POST['div_pop'];
				if ($div_pop !=0){
					if ($entryid!=FALSE ){//Edit Entry Point
						$this->type = $type ;
						$this->read_goal($goalid,$type,$entryid,TRUE,$mode_edit,$div_pop);
					}
					else{//Add Entry Point
						$this->read_goal($goalid,$type,FALSE,TRUE,$mode_edit,$div_pop);

					}
				}
				else{
					if ($entryid!=FALSE ){//Edit Entry Point
						$this->type = $type ;
						$this->read_goal($goalid,$type,$entryid,FALSE,$mode_edit);
					}
					else{//Add Entry Point
						$this->read_goal($goalid,$type,FALSE,FALSE,$mode_edit);

					}
				}
		}
		else{
			$this->edit_goal($mode_edit,$goalid,$type);
		}
	}
	function refresh_linkunit($extid=FALSE) {
		$this->stage(FALSE,$extid,1);
	}
	function refresh($enableflag=FALSE,$filter=FALSE,$selectentry=FALSE){
		$divid = 'goal' ;
		$goal = $this->CI->searchsort_model->getSort($divid);
	   $menuflag = FALSE;
		if (isset($goal->menuflag) && $goal->menuflag != FALSE){
		   $menuflag = $goal->menuflag;
		}
		$creatorid = FALSE;
		if ($menuflag == CMS_MYGOAL)
			 $creatorid = $this->get_userid();
		$selectfilter = $enableflag;
		if (isset($_POST['filters']))
			 $selectfilter = $_POST['filters'];
		if (isset($_POST['selected']))
			 $selectentry = $_POST['selected'];
		$filter = htmlspecialchars($filter);
		if (isset($_POST['filter']))
		    $filter =  htmlspecialchars($_POST['filter']);
		$data = $this->goal_model->get_goalall($creatorid, $selectfilter, $filter, $selectentry);

		$this->refresh_goal($menuflag,$selectfilter,$filter,$selectentry,$data);
	}
	function load_goal($menuflag=FALSE){
		$data = FALSE;
		$creatorid = FALSE;
		if ($menuflag == CMS_MYGOAL)
			 $creatorid = $this->get_userid();
	 	$data = $this->goal_model->get_goalall($creatorid, CMS_ADMIN_ENABLE);
	 	$this->new_display_session = TRUE;
	 	$this->refresh_goal($menuflag,CMS_ADMIN_ENABLE,false,false,$data);
	}
	function refresh_goal($menuflag=FALSE,$enableflag=CMS_ADMIN_ENABLE,$filter=FALSE,$selectentry=FALSE,$data=FALSE) {
		//Add Config
		$url_add	 = 'goal/goal/create_goal';
		$div = '"page_content"';
		$width		 = 550;
		$height		 = 450;
		$title_add	 = '';
		$imgaddname	 = osa_imagepath() . 'add_24.gif';
		$imgaddtitle = lang('goal_list_img_add');
	   $imgeadd     = $this->admin_base->new_getpage($url_add, $title_add, $width, $height, $div , $imgaddname,$imgaddtitle );
	 	$divid		 = 'goal' ;
   	//$display  = $this->admin_base->init_display('', $enableflag,$divid);
		if ( $this->new_display_session ) {
			$display = & $this->admin_base->init_display('', $enableflag, $divid);
			$display->column_use_striptag[0] = TRUE;
		}
		else {
			$this->load->library('search/searchutil');
			$display = & $this->searchutil->get_session($divid);
			$display->reset_data();
			$display->selectlistitem = $enableflag;
		}
   	$display->page = 'goal/goal';
   	$template = $this->get_goal_obj();
   	$entry = array();
   	if ( isset($template->entry_types) )
			$entry = $template->entry_types;
		$display->entry = $entry;
		$display->selectentry = $selectentry;
		$display->filter = $filter;

   	if ($this->access_write() ==FALSE && $menuflag != CMS_MYGOAL ){
   		$display->listitem = FALSE;
   	}
   	if ($this->access_write() ==FALSE && $this->check_editor()==FALSE){
   		$display->listitem = FALSE;
   	}

		$display->menuflag = $menuflag;
   	$display->type = '';
   	//$display->menu = lang('goal_menu_user');
   	$display->menu = ''; //Not used but admin view needs this variable
   	$display->search = lang('goal_list_search_title');
   	if ($display->menuflag == 1){
   		$display->pagetitle = lang('goal_menu_list_goals');
   	}
   	else{
   		$display->pagetitle = lang('goal_menu_list_my_goal');
   	}


   	$display->titles     = array(lang('goal_list_display_title'),
   									  lang('goal_list_display_entrypoint'),
   				                 lang('goal_list_display_editor'),
   				                 lang('goal_list_display_date'),
   				                 lang('goal_list_display_enabled'),
   				                 $imgeadd
   				                 ) ;
		$display->widths     = array('27%','27%','15%','15%','10%','6%');

		if (!$this->config->item('cms_goal_user_title')){
			$display->titles     = array(lang('goal_list_display_editor'),
	   				                 lang('goal_list_display_date'),
	   				                 lang('goal_list_display_enabled'),
	   				                 $imgeadd
	   				                 ) ;
			$display->widths     = array('61%','24%','10%','5%');
		}
		$hide_entrypoint = $this->config->item('cms_goal_hide_entrypoint');
		$display->hide_entrypoint = $hide_entrypoint;
		if ($hide_entrypoint){
			$display->titles = array(lang('goal_list_display_title'),
											  lang('goal_list_display_editor'),
	   				                 lang('goal_list_display_date'),
	   				                 lang('goal_list_display_enabled'),
	   				                 $imgeadd
	   				                 ) ;
			$display->widths = array('45%','27%','15%','8%','5%');
		}

		$page = 'page_content';
		$display->refresh = $page;
		$display->strand=array();
		$display->data_dep_sch =array();
		$display->standard =array();


		//$display->url_refresh = 'refresh';

		$splits = $this->admin_base->split($display->filter);
		if ($data != FALSE) {
			$first_loop = TRUE;
			foreach ($data as $rows) {
				//Fixed (issue: 83), not display username when user->displayname is missing
				$rows->displayname = osa_user_getname($rows);
				$imgdelname	= osa_imagepath() . 'deletes.gif';
				$imgdeltitle = lang('goal_list_img_del');
				$massage_del	= lang('goal_list_message_del');

				$enabled = $rows->enabled;
				if ($rows->enabled == CMS_ADMIN_DISABLE){
					$rows->enabled  = '<div class="hide">'.lang('goal_list_convert_disabled').'</div>';
				    $imgenablename = osa_imagepath() . 'enabled_16.gif';
				    $imgenabletitle = lang('goal_list_img_enable');
				    $massage = lang('goal_list_message_enable');
				}
				elseif ($rows->enabled == CMS_ADMIN_ENABLE){
					$rows->enabled  = '<div class="show">'.lang('goal_list_convert_enabled').'</div>';
				    $imgenablename = osa_imagepath() . 'disable_16.gif';
				    $imgenabletitle = lang('goal_list_img_disable');
				    $massage = lang('goal_list_message_disable');
				}


				//Edit Config
				//$url_edit		= 'goal/goal/read_goal/'.$rows->id.'/'.$rows->type.'/'.$rows->entryid;
				$url_edit		= 'goal/goal/read_goal/'.$rows->id;

				$div = '"page_content"';
				$title_edit		= '';
				$imgeditname	= osa_imagepath() . 'edit_16.gif';
				$imgedittitle	= lang('goal_list_img_edit');
				$linktitle		= lang('goal_list_img_link');

				//Enabled Config
				$url_enable		= 'goal/goal/enable_goal/'.$rows->id.'/'. $enabled.'/'.$enableflag.'/'.$selectentry;
				//Delete Config
				$url_del		= 'goal/goal/delete_goal/'.$rows->id.'/'.$enableflag.'/'.$selectentry;

				$title = $rows->title;
				if ($title == '' && $title == null){
					$title = lang('goal_list_display_title_null');
				}
				$highlight_name = $this->admin_base->highlight($splits, $title);
				if ( $first_loop ) {
					$url_edit_sprintf = 'goal/goal/read_goal/%s';
					//$linkname = $this->admin_base->link_getpage($url_edit, $title_edit, $width, $height, $div ,$highlight_name,$linktitle );
					$linkname = $this->admin_base->link_getpage($url_edit_sprintf, $title_edit, $width, $height, $div ,display_list::HIDEDATA_REPLACE_STR,$linktitle );
					$display->add_urllink_template_str(0,$linkname);
				}
				$imgedit  = $this->admin_base->new_getpage($url_edit, $title_edit, $width, $height, $div , $imgeditname,$imgedittitle );
				$imgenable   = $this->admin_base->delTarget($url_enable, $page ,$massage,$imgenablename, $imgenabletitle);
				$imgdel   = $this->admin_base->delTarget($url_del, $page ,$massage_del,$imgdelname, $imgdeltitle);
				//$imgedit  = '<div class="user_col_body_center_edit">' .$imgedit. '</div>';
				//$imgenable   = '<div class="user_col_body_center_del">'  .$imgenable. '</div>';
				//$imgdel   = '<div class="user_col_body_center_del">'  .$imgdel. '</div>';
				$entryname = '';
				if (isset($rows->type) && is_numeric($rows->type) && $rows->type !== FALSE ){
					if ( array_key_exists($rows->type , $entry) )
						$entryname = $entry[$rows->type];
				}
				//Can't delete goal so hide it for now(issue: 164)
				//$tmp_buttons = "<nobr>$imgenable $imgdel $imgedit</nobr>";
				$tmp_buttons = "<nobr>$imgenable $imgedit</nobr>";
				$temp = array($highlight_name , $entryname,$rows->displayname, osa_date_format($rows->createdate), $rows->enabled, $tmp_buttons);
				if (!$this->config->item('cms_goal_user_title')){
					$temp = array($rows->displayname, osa_date_format($rows->createdate), $rows->enabled,$tmp_buttons);
				}
				if ($hide_entrypoint){
					$temp = array($highlight_name,$rows->displayname, osa_date_format($rows->createdate), $rows->enabled, $tmp_buttons);
				}

				if ($this->access_write() == FALSE ){
					if ($this->check_creator($rows->id) == FALSE ){
						if ($this->check_editor($rows->id)==FALSE ){
							$imgenable = "<img src=". osa_imagepath() . "dis_disable.gif    border='0' >";
							$imgdel = "<img src=". osa_imagepath() . "dis_delete.gif    border='0' >";
							//$display->listitem = FALSE;
						}
						else{
							$imgdel = "<img src=". osa_imagepath() . "dis_delete.gif    border='0' >";
						}

					}
					else{
						//logic creator Modify table column deleted in a goal.
						$url_deleteflag	= 'goal/goal/update_deleted/'.$rows->id.'/'. $enabled.'/'.$enableflag.'/'.$selectentry;
						$imgdel   = $this->admin_base->delTarget($url_deleteflag, $page ,$massage_del,$imgdelname, $imgdeltitle);
						//$imgdel = '<div class="user_col_body_center_del">'  .$img_delflag. '</div>';
					}
					$tmp_buttons = "<nobr>$imgenable $imgdel $imgedit</nobr>";
					$temp = array($highlight_name ,$entryname, $rows->displayname, osa_date_format($rows->createdate),$rows->enabled,$tmp_buttons);
					if (!$this->config->item('cms_goal_user_title')){
						$temp = array($rows->displayname, osa_date_format($rows->createdate),  $rows->enabled,$tmp_buttons);
					}
					if ($hide_entrypoint){
						$temp = array($highlight_name,$rows->displayname, osa_date_format($rows->createdate), $rows->enabled, $tmp_buttons);
					}
				}
				$display->add_hidden_data(0, $temp, "{$rows->id},{$rows->id}");
				$display->add($temp);
			}
		}
		$display->column_data_align[2] = 'center';
		$display->iswindow = FALSE;
		$display->force_sort = TRUE;
      $display->prepare_page();
      $data = new stdClass();
      $data->display = $display;
      echo $this->CI->load->view('tablelist/goal_list_view', $data, TRUE);
	}

	function search() {
	 	$keys = array_keys($_POST);
	 	$enableflag = CMS_ADMIN_ENABLE;
		foreach ($keys as $key) {
			$value = trim($_POST[$key]);
			if ($key == 'filter')
				$filter = htmlspecialchars($value);
			elseif ($key == 'selectfilter')
				$enableflag = $value;
	    }
    	echo $enableflag.'/'.$filter;
	}
	function enable_goal($goalid, $enabled=FALSE,$enableflag=FALSE,$selectentry=FALSE) {
		if ( is_numeric($goalid)==FALSE ||  is_numeric($enabled)==FALSE) {
			return FALSE;
		}
		if ($enabled==CMS_ADMIN_DISABLE)
			$enabled= CMS_ADMIN_ENABLE;
		else
		    $enabled= CMS_ADMIN_DISABLE;

		$data = FALSE;
		$data->enabled = $enabled;
		$divid = 'goal' ;
		$goal  = $this->CI->searchsort_model->getSort($divid);

	   $filter= FALSE;
	   if ($goal->filter!=FALSE && $goal->filter!='')
	    	$filter = $goal->filter;
	   $this->goal_model->edit_goal($goalid,$data);
	   $this->refresh($enableflag,$filter,$selectentry);
	}
	//Function Modify table column deleted in a goal.
	function update_deleted($goalid,$enabled=FALSE,$filerflag=FALSE,$selectentry=FALSE) {
		$divid = 'goal' ;
		$user  = $this->CI->searchsort_model->getSort($divid);
	   $filter= FALSE;
	   if ($user->filter!=FALSE && $user->filter!='')
	   	$filter=$user->filter;
	   $data = FALSE;
	   $data->deleted = $enabled;
		$this->goal_model->update_deleted($goalid,$data);
		$this->refresh($filerflag,$filter,$selectentry);
	}
	function delete_goal($goalid,$enableflag=FALSE,$selectentry=FALSE) {
		if (is_numeric($goalid) != FALSE && $goalid != FALSE ){
			//$template = $this->get_goal_obj();
			$goal = $this->goal_model->get_entry_pointbygoalid($goalid,$this->get_goal_types());
			if ($goal != FALSE ){
				//delete resourse and linkunit
				$resourceid = FALSE;
				foreach ($goal as $value){
					if ($value->resid != FALSE){
						$resourceid[] = $value->resid;
					}
				}
				//delete resourse
				if ($resourceid != FALSE ){
					$this->goal_model->del_upload('upload',$resourceid);
					$this->goal_model->del_resource('resource',$resourceid);
				}
				//delete linkunit
				$this->linkunit_model->delete_linkunit($goalid);
			}

			//delete team_members
			$this->goal_model->del_team_members('team_members',$goalid);
			//delete entry point
			$this->goal_model->del_entry_goal('entry_point',$goalid);
			//delete goal
			$this->goal_model->del_goal('goal',$goalid);
		}
		$divid = 'goal' ;
		$user  = $this->CI->searchsort_model->getSort($divid);
	   $filter= FALSE;
	   if ($user->filter!=FALSE && $user->filter!='')
	   	$filter=$user->filter;
		$this->refresh($enableflag,$filter,$selectentry);

	}
	private function get_resource($goalid=FALSE,$entryid=FALSE,$type=FALSE){
		if ($goalid!=FALSE && $entryid!=FALSE){
			$goal = $this->goal_model->get_goaltopdf($goalid,$type);
		}
		if (isset($goal) && $goal !=FALSE){
			return TRUE;
		}
		return FALSE;
	}
	private function get_userid(){
		$user = FALSE;
		if ( ($user = $this->login_model->getLogin()) !== FALSE )
			return $user->id;
		return FALSE;
	}
	private function access_write(){
		$access_write = $this->access_model->checkaccess_any('admin_goal_write',FALSE,FALSE,FALSE);
		if ($access_write || $this->goal_model->is_goal_admin())
			return TRUE;
		return FALSE;
	}
	private function access_readonly(){
		$access_readonly = $this->access_model->checkaccess_any('admin_goal_readonly',FALSE,FALSE,FALSE);
		return $access_readonly;
	}
	private function check_creator($goalid){
		$iseditor = FALSE;
		$goalcreator = $this->goal_model->check_goal_creator($goalid, $this->get_userid());
		if ($goalcreator != FALSE && $goalcreator->iseditor != FALSE){
			$iseditor = TRUE;
		}
		return $iseditor;
	}
	private function check_editor($goalid=FALSE){
		$iseditor = FALSE;
		$goaleditor = $this->goal_model->check_goal_editor($goalid, $this->get_userid());
		if ($goaleditor != FALSE && $goaleditor->iseditor != FALSE){
			$iseditor = TRUE;
		}
		return $iseditor;
	}
	private function check_goal_editor($goalid){
		if ( !is_numeric($goalid))
			 return FALSE;

		if ($this->access_write())
			 return TRUE;

		if ($this->check_editor($goalid) != FALSE)
			 return TRUE;
		return FALSE;
	}

	//Gets the list of member names
	//Modifies display name or last name to identify member type
	private function get_team_members($goalid){
		$team_creator = $this->goal_model->get_creator($goalid);
		if ($team_creator != FALSE) {
			 foreach ($team_creator as $member) {
			  	if (isset($member->displayname)) {
			  		 $member->displayname .= lang('goal_create_meber_creator');
			  	}
			  	elseif (isset($member->lastname)) {
			  		$member->lastname .= lang('goal_create_meber_creator');
			  	}
			  	$all_member[] = $member;
			 }
		}

		$team_member = $this->goal_model->get_team($goalid);
		if ($team_member != FALSE) {
			 foreach ($team_member as $member) {
			 	if ($member->iseditor != FALSE) {
			 		if (isset($member->displayname)) {
			 		 	$member->displayname .= lang('goal_create_meber_editor');
			 		}
			 		elseif (isset($member->lastname)) {
			 			$member->lastname .= lang('goal_create_meber_editor');
			 		}
			 	}
				$all_member[] = $member;
			 }
		}

		$editornames = osa_user_getname($all_member);
		return $editornames;
	}

	function loadpdfall($goalid=FALSE, $phpsessionid=FALSE) {
		$this->loadpdf($goalid , $phpsessionid);
	}

	function loadpdf($goalid=FALSE,$phpsessionid=FALSE) {
		global $g_pdf_mode;
		$g_pdf_mode = TRUE;
		osa_init_phpci_sessions($phpsessionid);
		$this->access_model->checkaccess_any('goal_read');
		if (!is_numeric($goalid))
			return FALSE;
		$goal = $this->goal_model->get_entry_bygoal($goalid);
		if ($goal === FALSE )
			 return FALSE;
		$this->load->view('goal/goal_closebutton_view');
		$this->readonly($goal->goalid, $goal->entryid, $goal->type);
		$this->load->view('goal/goal_closebutton_view');
	}
	function stage($stagenum=FALSE, $action=FALSE, $goalid=FALSE) {
		$this->update_entry($goalid);
		$this->edit_goal($goalid, $stagenum);
	}

	//Same as edit_goal but no $stagenum param, couldn't think of a better name
	//Only used for paging links
	function edit_goal2($goalid, $current_page) {
		$this->edit_goal($goalid, FALSE, $current_page);
		//osa_previous_url("goal/goal/edit_goal2/$goalid/$current_page");
	}

	function edit_goal($goalid=FALSE, $stagenum=FALSE, $current_page=1) {
		//Saves the URL so we can go back after creating a new survey
		$entry_point = $this->goal_model->get_entry_bygoal($goalid);
		$this->edit($goalid, $entry_point->entryid, $entry_point->type, $stagenum, $current_page);
		//osa_previous_url("goal/goal/edit_goal2/$goalid/$current_page");
		osa_url_history(CMS_URLHISTORY_GOAL, "goal/goal/edit_goal2/$goalid/$current_page");
	}
	function read_goal($goalid, $current_page=1) {
		//Saves the URL so we can go back after creating a new survey
		$goal = $this->goal_model->get_entry_bygoal($goalid);
		$this->read($goal->goalid, $goal->entryid, $goal->type, $current_page);
		//osa_previous_url("goal/goal/read_goal/$goalid/$current_page");
		osa_url_history(CMS_URLHISTORY_GOAL, "goal/goal/read_goal/$goalid/$current_page");
	}
	private function edit($goalid=FALSE, $entryid=FALSE, $type=FALSE, $stagenum=FALSE,$current_page=1) {
		$action = CMS_ACTION_EDIT;
	  	$goal = $this->goal_model->get_goal($goalid);
	  	if ( !$goal ) {
	  		return;
	  	}
	  	//config one goal for one entryid
	  	$entry = $this->goal_model->get_entry($goalid, $entryid);
	  	if ( !$entry ) {
	  		return;
	  	}

	 	if ( $this->config->item('cms_goal_show_creatorname') === TRUE ) {
			$tmp_user = $this->login_model->getDbUserByid($goal->creatorid);
			if ( $tmp_user ) {
				$data->creator_name = osa_user_getname($tmp_user);
			}
	   }

	  	$data->action = $action;
	  	$data->goalid = $entry->goalid;
  		$data->entryid = $entry->entryid;
	  	$data->type = $entry->type;

	  	$completedate = osa_date_format($entry->completedate) ;
	  	//$data->visible_title = $visible_title;
	  	$data->editornames = $this->get_team_members($goalid);
	  	$data->title = lang('goal_create_title');
	  	$data->title2 = $goal->title;

	  	$data->goal_turn_on = $this->is_edit_goal($goalid);
		$data->goal_editor = $this->goal_model->is_edit_goal($goalid);
	  	$data->url_mode = 'update_goal';
	  	$data->stagenum = $stagenum;

 		$this->load->library('unit/unitmain',
									array('action'=>$action,'unitid'=>$goalid,'courseid'=>0,
						  					'unit_template'=> CMS_GOAL_TEMPLATE,'current_page'=>$current_page));

		$template = $this->unitmain->get_template();
 		$data->entry_title = '';
	  	if ( isset($template->entry_title) )
	  		$data->entry_title = $template->entry_title;
 		$entry_list = array();
 		if ( isset($template->entry_types) )
 			$entry_list = $template->entry_types;
 		$data->selectitem_name = '';
	  	if ( is_numeric($type) && $type!== FALSE ) {
	  		if ( array_key_exists($type , $entry_list) )
	  			$data->selectitem_name = $entry_list[$type];
	  	}
	  	if ( isset($template->page_title) && is_array($template->page_title) && array_key_exists($current_page,$template->page_title) )
	  		$data->title = $template->page_title[$current_page];
		$data->hidden_pdf = $this->get_resource($entry->goalid, $entry->entryid, $this->get_goal_types());
		if ( $stagenum != FALSE ) {
			$data->unitbody = $this->unitmain->render_stage($stagenum);
		}
		else {
			//We don't care does the template uses paging or not since render_page() does nothing if no paging amd returns empty string
			$data->unitpage = $this->unitmain->render_page($entry->entryid,$current_page,'goal/goal/edit_goal2/');
			$data->unitbody = $this->unitmain->render();
		}
	 	$data->hide_members = $this->config->item('cms_goal_hide_members');
		$data->hide_entrypoint = $this->config->item('cms_goal_hide_entrypoint');

		//Modify params in $data for survey buttons if needed
		$this->_prepare_survey_buttons($data, $goalid);
		$this->load->view('goal/goal_edit_view',$data);
	}

	private function read($goalid=FALSE, $entryid=FALSE, $type=FALSE,$current_page=1) {
		$action = CMS_ACTION_READ;
	  	$goal = $this->goal_model->get_goal($goalid);
	  	//config one goal for one entryid
	  	$entry = $this->goal_model->get_entry($goalid, $entryid);
	  	if (!$entry || !isset($entry->goalid) || !isset($entry->entryid) || !isset($entry->type))
	  		 return;

	   if ( $this->config->item('cms_goal_show_creatorname') === TRUE ) {
			$tmp_user = $this->login_model->getDbUserByid($goal->creatorid);
			if ( $tmp_user ) {
				$data->creator_name = osa_user_getname($tmp_user);
			}
	   }

	  	$data->action = $action;
	  	$data->goalid = $entry->goalid;
  		$data->entryid = $entry->entryid;
	  	$data->type = $entry->type;

	  	$completedate = '';
	  	if (isset($entry->completedate))
	  		 $completedate = osa_date_format($entry->completedate) ;
	  	$data->editornames = $this->get_team_members($goalid);
	  	$data->title = lang('goal_create_title');
	  	$data->title2 = $goal->title;
	  	$data->goal_turn_on = $this->is_edit_goal($goalid);
	   $data->goal_editor = $this->goal_model->is_edit_goal($goalid);
	  	$data->url_mode = 'update_goal';
 		$this->load->library('unit/unitmain',
									array('action'=>$action,'unitid'=>$goalid,'courseid'=>0,
						  					'unit_template'=> CMS_GOAL_TEMPLATE,'current_page'=>$current_page));

		$template = $this->unitmain->get_template();
 		$data->entry_title = '';
	  	if ( isset($template->entry_title) )
	  		$data->entry_title = $template->entry_title;
 		$entry_list = array();
 		if ( isset($template->entry_types) )
 			$entry_list = $template->entry_types;
 		$data->selectitem_name = '';
	  	if ( is_numeric($type) && $type!== FALSE ) {
	  		if ( array_key_exists($type , $entry_list) )
	  			$data->selectitem_name = $entry_list[$type];
	  	}
		$data->hidden_pdf = $this->get_resource($entry->goalid, $entry->entryid, $this->get_goal_types());
	  	if ( isset($template->page_title) && is_array($template->page_title) && array_key_exists($current_page,$template->page_title) )
	  		$data->title = $template->page_title[$current_page];

	  //	$this->load->library('cms/cms_template/cms_template');
	  	//Check to see if the template requires paging
		//if ( $this->cms_template->ispaging($template) ) {
		//This adds the paging part
 		$data->unitpage = $this->unitmain->render_page($entry->entryid,$current_page,'goal/goal/read_goal/');
		//}

 		$data->unitbody = $this->unitmain->render();
		$data->hide_members = $this->config->item('cms_goal_hide_members');
		$data->hide_entrypoint = $this->config->item('cms_goal_hide_entrypoint');
		$data->current_page = $current_page;
		//Modify params in $data for survey buttons if needed
		$this->_prepare_survey_buttons($data, $goalid);
		$this->load->view('goal/goal_read_view',$data);
	}

	//Modifies the $data params so the view would show the survey buttons
	private function _prepare_survey_buttons(&$data, $goalid) {
		//We started with only one survey per goal but we changed to support multiple surveys per goal
		$data->show_create_survey = FALSE;
		$data->show_list_survey = FALSE;
		if ( $this->config->item('cms_use_goal_survey') ) {
			$data->show_create_survey = TRUE;
			if ( $this->goal_model->has_survey($goalid) ) {
				$data->show_list_survey = TRUE;
			}
			/* else {
				$data->show_create_survey = TRUE;
			} */
		}
	}

	private function readonly($goalid=FALSE, $entryid=FALSE, $type=FALSE,$current_page=1) {
		$action = CMS_ACTION_READ;
	  	$goal = $this->goal_model->get_goal($goalid);
	  	//config one goal for one entryid
	  	$entry = $this->goal_model->get_entry($goalid, $entryid);

	 	if ( $this->config->item('cms_goal_show_creatorname') === TRUE ) {
			$tmp_user = $this->login_model->getDbUserByid($goal->creatorid);
			if ( $tmp_user ) {
				$data->creator_name = osa_user_getname($tmp_user);
			}
	   }

	  	$completedate = osa_date_format($entry->completedate) ;
	  //	$data->visible_title = $visible_title;
	  	$data->editornames = $this->get_team_members($goalid);
	  	$data->title = lang('goal_create_title');
	  	$data->title2 = $goal->title;

 		$this->load->library('unit/unitmain',
									array('action'=>$action,'unitid'=>$goalid,'courseid'=>0,
						  					'unit_template'=> CMS_GOAL_TEMPLATE,'current_page'=>$current_page));

		$template  = $this->unitmain->get_template();
 		$data->entry_title = '';
	  	if ( isset($template->entry_title) )
	  		$data->entry_title = $template->entry_title;
 		$entry_list = array();
 		if ( isset($template->entry_types) )
 			$entry_list = $template->entry_types;
 		$data->selectitem_name = '';
	  	if ( is_numeric($type) && $type!== FALSE ) {
	  		if ( array_key_exists($type , $entry_list) )
	  			$data->selectitem_name = $entry_list[$type];
	  	}

 		$data->unitbody = $this->unitmain->render();
 		if ( isset($template->page_title) && is_array($template->page_title) && array_key_exists($current_page,$template->page_title) )
	  		$data->title = $template->page_title[$current_page];
		$data->hide_members = $this->config->item('cms_goal_hide_members');
		$data->hide_entrypoint = $this->config->item('cms_goal_hide_entrypoint');
		$this->load->view('goal/goal_readonly_view',$data);
	}
	private function is_edit_goal($goalid){
		if ( !is_numeric($goalid) )
			return FALSE;
		if ($this->goal_model->is_edit_goal($goalid) || $this->goal_model->is_goal_member($goalid))
			return TRUE;
		return FALSE;
	}
	private function get_goal_obj(){
 		/*$this->load->library('unit/unitmain',
			array('action'=>CMS_ACTION_ADD,'unitid'=>0, 'courseid'=>0,'unit_template'=> CMS_GOAL_TEMPLATE));
		$template  = $this->unitmain->get_goal_obj();*/
		$template = osa_get_template_object(CMS_GOAL_TEMPLATE);
		return $template;
	}
/*
	//Fucntion Add or Update template_date table
	function update_template_date($extid=FALSE,$type=FALSE) {
		$this->load->model('unit/uph/template_date_model');
		$data = FALSE;
		if( isset($extid) && $extid != FALSE )
			$data->extid = $extid;
		if( isset($type) && $type !== FALSE )
			$data->type = $type;
		if( isset($_POST['teacher_completion_date'][$type]) )
			$data->date = $_POST['teacher_completion_date'][$type];
		if( isset($_POST['appraiser_completion_date'][$type]) )
			$data->date = $_POST['appraiser_completion_date'][$type];

		$this->template_date_model->add_template_date($data);
	}
*/
	//Function Get Goal Type.
	private function get_goal_types(){
		$this->load->library('cms/cms_template/cms_template');
		$goal_type = $this->cms_template->types(CMS_GOAL_TEMPLATE);
		if ( $goal_type === FALSE ){
			osa_errorlog(__METHOD__ . " -  Invalidate goal types in Function get_goal_types ", $goal_type);
			echo osa_ajaxmsg(lang('unit_no_permissionmsg'));
			exit;
		}
		return $goal_type;
	}
}