<?php
/**
 * itstd.php
 *
 * IT Standards controll file. TODO: This implementation needs a rewrite badly.
 *
 * @author $Author: dtong $
 * @version $Id: itstd.php,v 1.42 2011/05/13 03:39:31 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/

class itstd extends CI_Controller {

	function __construct() {
		parent::__construct();
		//$this->load->helper('form');
		// THA : FOR ID STAND SHOW UNIT
		osa_load_lang('home');
		osa_load_lang('general');
		$this->load->library('user_agent');

		$this->load->model('unit/resource_model');
		$this->load->model('unit/unit_model');
		$this->load->model('unit/itstd_model');
		osa_load_lang('unit');
		osa_load_lang('target');
		$this->access_model->checkaccess_any('unit_read', FALSE, TRUE, TRUE);
		$this->output->enable_profiler($this->config->item('cms_debug_enable_profiler'));
		/* if ( !$this->access_model->checkaccess_any('unit_read', FALSE, FALSE, FALSE) ) {
			//A view won't print to the client until this returns and an exist
			//would result in no output. So, just echo it here. Noticed the 3rd parameter in the load->view
			echo $this->load->view('unit/unit_htmlerror_view', array('errormsg'=>lang('unit_no_permissionmsg')),TRUE);
			exit;
		}*/
	}

	//The is the unit page ICT button
	function addo($type, $resourcetype, $unitid) {
		if ( !is_numeric($type) || !is_numeric($resourcetype) || !is_numeric($unitid) ) {
			$this->load->view('template/ajax_error_view',
			array('errormsg' => lang('gen_internalservererror'), 'divid' => 'itstandards'));
			return;
		}

		//Only editors can run this, exits if false
		if ( ($unit = $this->unit_model->check_unit_editaccess($unitid)) == FALSE ) {
			$this->load->view('template/ajax_error_view',
				array('errormsg' => lang('unit_no_permissionmsg'), 'divid' => 'itstandards'));
			return;
		}
	 	$this->_add_real_byschool($type, $resourcetype, FALSE, $unit ,FALSE);
	}

	// fix for new require under schoolid
	function sample($type, $resourcetype, $schoolid, $role_type=CMS_ICT_USER_TYPE) {
		if ( !is_numeric($type) || !is_numeric($resourcetype) ) {
			$this->load->view('template/ajax_error_view',
			array('errormsg' => lang('gen_internalservererror'), 'divid' => 'itstandards'));
			return;
		}
		if ( !$this->access_model->is_ict_editor($role_type, $schoolid) ) {
			$this->load->view('template/ajax_error_view',
				array('errormsg' => lang('unit_no_permissionmsg'), 'divid' => 'itstandards'));
			return;
		}

		$this->_add_real_byschool($type, $resourcetype, $schoolid, FALSE, TRUE, FALSE, $role_type);
	}

	// fix for new require readonly for not ict editor
	function readonly($type, $resourcetype, $schoolid) {
		if ( !is_numeric($type) || !is_numeric($resourcetype) ) {
			$this->load->view('template/ajax_error_view',
			array('errormsg' => lang('gen_internalservererror'), 'divid' => 'itstandards'));
			return;
		}

		$this->_add_real_byschool($type, $resourcetype, $schoolid, FALSE, TRUE, TRUE);
	}
	function readict($type, $resourcetype, $unitid) {
		if ( !is_numeric($type) || !is_numeric($resourcetype) || !is_numeric($unitid) ) {
			$this->load->view('template/ajax_error_view',
			array('errormsg' => lang('gen_internalservererror'), 'divid' => 'itstandards'));
			return;
		}

		//Only editors can run this, exits if false
		$unit = $this->unit_model->get_unit($unitid);
	 	$this->_add_real_byschool($type, $resourcetype, FALSE, $unit ,FALSE, TRUE);
	}

	//This updates the selections from ICT button popup.
	function update($unitid, $type) {
		if ( !is_numeric($unitid) || !is_numeric($type) ) {
			$this->load->view('template/ajax_error_view',
				array('errormsg' => lang('unit_no_permissionmsg'), 'divid' => 'itstandards'));
			return;
		}
		//Only editors can run this, exits if false
		if ( ($unit = $this->unit_model->check_unit_editaccess($unitid)) == FALSE) {
			$this->load->view('template/ajax_error_view',
				array('errormsg' => lang('gen_internalservererror'), 'divid' => 'itstandards'));
			return;
		}

		$keys = array_keys($_POST);
		$pattern = 'itstd';
		$select1 = array();
		$select2 = array();
		$sep = '';
		$tmp = '';
		foreach($keys as $key) {
			$tok = strtok($key,'_');
			if ($tok==$pattern) {
				$selectid = strtok('_');
				if ( is_numeric($selectid) ) {
					$formid = strtok('_');
					if ( is_numeric($formid)) {
						if (($_POST[$key]!=null)) {
							if ($selectid == 1)
								$select1[$formid] = $_POST[$key];
							if ($selectid == 2)
								$select2[$formid] = $_POST[$key];
						}
					}
				}
			}
		}

		if ( ($this->itstd_model->update($unitid, $type, $select1 , $select2)) == FALSE ) {
			echo osa_ajaxmsg(lang('unit_failedtoadddata'));
			exit;
		}

		echo 'success';
		exit;
	}

	//Deletes one selection from the unit page
	function delete ($unitid, $targetid) {
		$this->unit_model->check_unit_editaccess($unitid);
	    if ( !$this->itstd_model->delete($unitid,$targetid) ) {
			echo osa_ajaxmsg(lang('unit_failedtodeletedata'));
      	exit;
		}
	}

	private function _add_real_byschool($type, $resourcetype, $schoolid, $unit, $upload_flag, $readonly=FALSE, $role_type=FALSE) {
		if (!$upload_flag)  {
			if ( !$unit || !isset($unit->courseid) || !isset($unit->id) ) {
				echo osa_ajaxmsg(lang('unit_unitnotavailable'));
				exit;
			}
			$courseid = $unit->courseid;
			$unitid = $unit->id;
		} else {
			$unitid = 0;
			$courseid =0;
			if ( !is_numeric($schoolid) ) {
			  	return FALSE;
			}
		}

		if ( !$readonly ) {
			// Add security tokens
			$this->load->library('cms/cms_security');
			$this->cms_security->init(CMS_ACTION_EDIT, CMS_TEMPLATE_DEFAULT, $unitid, $courseid);
			$this->cms_security->has_full_security(CMS_ACTION_EDIT, TRUE);
			$this->cms_security->save();
		}

		//Get the itstand template object
		$this->load->library('unit/unitmain',
			array('action'=>CMS_ACTION_ADD,'unitid'=>$unitid, 'courseid'=>$courseid));
		$template  = $this->unitmain->get_itstd_obj($type, $unitid);
		if ( !$template || $template->template_data() == FALSE ) {
			osa_errorlog(__METHOD__ . " - Failed to get template type:$type unit:$unitid.");
			$this->load->view('template/ajax_error_view',
				array('errormsg' => lang('gen_internalservererror'), 'divid' => 'itstandards'));
			return;
		}

		$grade_table_replacement = FALSE;
		if ($template->getval('_grade_related_data') != FALSE)
			$grade_table_replacement = $template->getval('_grade_related_data');

		$schools_all =  array();
		if (isset($schoolid) && $schoolid != FALSE){
			$schools_all[] = $schoolid;
		}
		elseif ($grade_table_replacement === FALSE){
			$course_grade =  $this->itstd_model->get_grade_bycourse($courseid);
			$min_grade = $course_grade->gmin;
			$max_grade = $course_grade->gmax;
			if ( $min_grade > $max_grade){
			   $gmin = $max_grade;
			   $gmax = $min_grade;
			}
			$schools_all =  $this->itstd_model->get_grade_type(false, $min_grade, $max_grade);
		}
		else {
			$course_grade =  $this->itstd_model->get_grade_bycourse($courseid, $grade_table_replacement);
			$min_grade = $course_grade->gmin;
			$max_grade = $course_grade->gmax;
			if ( $min_grade > $max_grade){
			   $gmin = $max_grade;
			   $gmax = $min_grade;
			}
			$schools_all =  $this->itstd_model->get_grade_type($grade_table_replacement,$min_grade, $max_grade);
		}


		$result = FALSE;
	    if (!$result && is_array ($schools_all))
			 $result = $schools_all;
		// Unit Integrated and Unified: get schools form all childs
	    if ( $unitid !== 0 && ($unit->type == $this->unit_model->TYPE_INT_PARENT || $unit->type == $this->unit_model->TYPE_UNI_PARENT) ) {
	    	$publish = FALSE;
			$publish = $this->unit_model->get_publish_units_bygroup($unit);
			if (!$publish)
				$publish_id = $unitid;	// nothing for else
			else
				$publish_id = $publish->id;
			$childs = $this->unit_model->get_childs_unit($publish_id);

	    //	if ( $unit->status == $this->unit_model->STATUS_EDIT && !is_null($unit->currentunitid) )
	    	//	$childs = $this->unit_model->get_childs_unit($unit->currentunitid);
	    //	else
	    //	 	$childs = $this->unit_model->get_childs_unit($unitid);
/*
	    	if ( is_array ($childs) )
		    	foreach ($childs as $child) {
		    		$schools_min = $this->itstd_model->get_schools_bygrade($child->courseid,TRUE);	//true is mingrade
					$schools_max = $this->itstd_model->get_schools_bygrade($child->courseid,FALSE);	//false is maxgrade
					$schools_all = $this->itstd_model->merge_schools($schools_min, $schools_max);

					if ( is_array ($result) && is_array ($schools_all) )
						 $result = array_merge($result, $schools_all);
		    	}
		    	*/
		    if ( is_array ($childs) ){
		    	if ($grade_table_replacement === FALSE){
		    		foreach ($childs as $child) {
		    			$course_grade =  $this->itstd_model->get_grade_bycourse($child->courseid);
						$min_grade = $course_grade->gmin;
						$max_grade = $course_grade->gmax;
						if ( $min_grade > $max_grade){
			   			$gmin = $max_grade;
			   			$gmax = $min_grade;
						}
						$result =  $this->itstd_model->get_grade_type(false, $min_grade, $max_grade);
		    		}
		    	}
		    	else{
		    		foreach ($childs as $child) {
		    			$course_grade =  $this->itstd_model->get_grade_bycourse($child->courseid, $grade_table_replacement);
						$min_grade = $course_grade->gmin;
						$max_grade = $course_grade->gmax;
						if ( $min_grade > $max_grade){
			   			$gmin = $max_grade;
			   			$gmax = $min_grade;
						}
						$result =  $this->itstd_model->get_grade_type($grade_table_replacement,$min_grade, $max_grade);
		    		}
		    	}
		    }
	    }

	    // re-array not duplicate
	    if ( is_array ($result) ) {
		    foreach ($result as $key=>$schoolid) {
			    if ( !in_array($schoolid,$schools_all) ) {
		    		$schools_all[] = $schoolid;
		    	}
		    }
	    }

		if (!is_array($schools_all) || count($schools_all)==0) {
			return FALSE;
		}

		//Get the selections from the DB
		$itstddb = $this->itstd_model->get_selections_byschool($type, $schools_all);
		//echo '<pre>'; print_r($itstddb); echo '</pre>';
		$data->db = $itstddb;
		$data->template = $template;

		$db_struct = array();
		//Old ZMS uses multiple queries to do this, but we just use one query
		//It is a lot more code but it is 10 times faster!
		$selectedids = FALSE;
		$reverseids = FALSE;
		$oriids =  array();

	    $last_strand = '';
		$last_standard = '';
		$schoolname = '';

		//$schools_arr = $this->itstd_model->get_all_schools('id',TRUE);

		$schools = $this->itstd_model->get_all_schools('id',TRUE,$grade_table_replacement);
		if ($schoolid == FALSE ){
			return FALSE;
		}
		if (array_key_exists($schoolid , $schools)) {
			$schoolname = $schools[$schoolid]->name;
		}

		$title_school = array();
		foreach ($schools_all as $schoolid) {
			if (array_key_exists($schoolid , $schools)) {
				  $title_school[$schoolid] = $schools[$schoolid]->name;
			}
		}
		//var_dump($title_school);
		//var_dump($schools_all);
		$itstd_school = array();
		if  ( $itstddb ) {
			foreach($itstddb as $record) {
					if ($last_strand != $record->strandid) {
						$db_struct[$record->strandid][0] =$record->strand;
						$last_strand = $record->strandid;
					}

					if ($last_standard != $record->standardid) {
						$db_struct[$record->strandid][$record->standardid][0] =$record->standard;
						$last_standard = $record->standardid;
					}

					$db_struct[$record->strandid][$record->standardid][] = $record;
					$oriids[] = $record->benchmarkid;

				if (!array_key_exists($record->schoolid , $itstd_school)) {
					$record->schoolname = $title_school[$record->schoolid];
					$itstd_school[$record->schoolid] =  $record;
				}

			}
		}

		//$resourcetype = $this->unitmain->get_itstd_resourcetype($type);

		if ($upload_flag == FALSE) {
			$reverseids   = $this->itstd_model->get_reverse_link_bycourse($unitid, $courseid, $type, $oriids);
			$selectedids  = $this->itstd_model->get_strand_tree($unitid, $type);
		}

		$resourceids  = $this->itstd_model->get_uploads_targetids($resourcetype);
		$tec = '<font class="text_red"">T</font>';
		$lib = '<font class="text_blue"">L</font>';

		//$value is a pointer, it is like $resourceids[][]
		//The following code looks like not doing anything useful but it actually
		//assigns property libtype to $resourceids[][]
		if (isset($resourceids) && $resourceids != FALSE){
			foreach($resourceids as $id => $resource) {
				$temp = $resource;
				foreach ($temp as $value) {
					if ($value->libict==CMS_LIBTEC_TYPE)
						 $libtech = $tec . $lib ;
					elseif ($value->libict==CMS_LIB_TYPE)
						 $libtech = $lib ;
					elseif ($value->libict==CMS_TEC_TYPE)
						 $libtech = $tec   ;
					else
						 $libtech = '';
					$value->libtype = $libtech;
				}
			}
		}

	   $benchmarkids = $this->itstd_model->get_targets_byschools($type, $schools_all);

	   $unit_selecteds = array();
	   if ( isset($selectedids)==FALSE || !$selectedids ) {	$selectedids = array();	}
		else {
			$ids = array();
			foreach($selectedids as $unit_target) {
				$ids[$unit_target->benchmarkid] = $unit_target;
			}
			$unit_selecteds = $ids;
			//$unit_selecteds = $selectedids;
				//$ids = array();
				//foreach($selectedids as $unit_target) {
				//	$ids[$unit_target->targetid] = $unit_target->benchmarkid;
				//} $selectedids = $ids;
				//foreach($selectedids as $unit_target) {
				//	$ids[$unit_target->benchmarkid] = $unit_target;
				//} $selectedids = $ids;
				//echo '<pre>';		print_r($ids); echo '</pre>';
		}

		if ( !$benchmarkids ) {
			$benchmarkids = array();
		}
		else { //khon it
			$ids = array();
			foreach($benchmarkids as $unit_target) {
				//$ids[] = $unit_target->benchmarkid;
				$selectedids[$unit_target->benchmarkid] = $unit_target;
				//$libtypes[$unit_target->benchmarkid] = $unit_target;
			}	$benchmarkids = $ids;
		}

		$data->unit_selecteds = $unit_selecteds;

		$data->upload_flag = $upload_flag; // TRUE  , FALSE
		//$data->resourceids = $resourceids;
		$data->benchmarkids = $benchmarkids;
		$data->resourceids = $resourceids;
		$data->reverseids = $reverseids;
		$data->selectedids = $selectedids;
		$data->db_struct = $db_struct;
		$data->courseid = $courseid;
		$data->unitid = $unitid;
		$data->schoolid = $schoolid;
		$data->schoolname = $schoolname;
		$data->itstd_school = $itstd_school;
		$data->type = $type;
		//var_dump($itstd_school);
		//var_dump($itstd_school);
		//$data->deptid = $deptid;
		//$data->department = $department;

		$data->browser = strtolower($this->agent->browser());
	  // $data->access = 'editor';
		$data->readonly = $readonly;
		$data->role_type = $role_type;
		//multi url
		$data->res_urls = $this->resource_model->get_res_urls(0,$resourcetype);
		$this->load->view('unit/unit_itstdadd_view', $data);
	}

	function update_check($unitid, $type=FALSE) {
		$keys = array_keys($_POST);
		$pattern = 'itstd';
		$temp = array();


		foreach($keys as $key) {
			$tok = strtok($key,'_');
			if ($tok==$pattern) {
				$selectid = strtok('_');
				if ( is_numeric($selectid) ) {
					$formid = strtok('_');
					if ( is_numeric($formid) && $_POST[$key]!=null) {
						    if (isset($temp[$formid])===FALSE)
						    	  $temp[$formid] = (int)$selectid;
						    else
						   	  $temp[$formid] += (int)$selectid;
					}
					else {
 						if (isset($temp[$formid])===FALSE)
						    $temp[$formid] = 0;
					}

				}
			}
		}
		//echo '<pre>';print_r($temp); echo '</pre>';
		$update = array();
		$ids = '';
		$notin = '';
		$comma = '';
		foreach($temp as $id => $value) {
			/*
			if (isset($update[$value])==FALSE)
				$update[$value] = $id;
			else
				$update[$value] .= $comma . $id;
			$comma = ',';
			*/
			$notin .= $comma .'"'.$id.'_'.$value.'"';
			$ids   .= $comma . $id;
			$comma = ',';
		}

		$type = 8;

		$update_id = $this->itstd_model->get_notin_select($type, $ids , $notin);

		if (is_array($update_id)) {
			foreach($update_id as $value) {
				//echo $temp[$value->id] . '<br />';
				//echo "update target_text set select3={$temp[$value->id]} where id = {$value->id}";
				$set = '';
				if ($temp[$value->id] == 3)
					 $set = "select1=1, select2=1 ";
				elseif ($temp[$value->id] == 2)
					 $set = "select1=0, select2=1 ";
				elseif ($temp[$value->id] == 1)
					 $set = "select1=1, select2=0 ";
				elseif ($temp[$value->id] == 0)
					 $set = "select1=0, select2=0 ";

				$this->itstd_model->update_select($type, $value->id , $set);
			}
		}

		//update_select
		//print_r($update_id);


		//if ($this->itstd_model->update_target_select($update, $type))
			// echo 'success' . $unitid;


		//echo $this->itstd_model->update_target_select($update, $type);
		/*
		foreach($update as $id => $value) {
			//echo $id . ':' .$value . '|';
			$this->itstd_model->update_target_select($id, $value);
		}
		*/

	}
}
?>