<?php
/**
 * grade.php - Admin grade config
 *
 * @author $Author: dtong $
 * @version $Id: grade.php,v 1.15 2011/04/27 05:46:26 dtong Exp $
 * @copyright Copyright (c) 2011, Tiller Software Co., Ltd.
*/
require_once APPPATH . 'libraries/mapping/display_list.php';
Class Grade extends CI_Controller {

	const page_url = 'admin/grade';
	const grade_div = 'grade_input';
	const dhtml_width = 600;
	const dhtml_height = 250;

	private $divid = 'adminss';

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

	function index(){
		$data = new StdClass();
		$all_grades_data = $this->grade_model->get_all_grades();
		$add_image = $this->_display_add();
		$this->load->library('mapping/display_list');
		$display = $this->display_list;
		$display->titles = array(
									lang('admin_grade_display_name'),
									lang('admin_grade_display_school'),
									lang('admin_grade_display_sort'),
									$add_image
									);
		$display->widths = array('47%','40%','10%','3%');
		//$display->sort_columns = FALSE;
		$display->divid = $this->divid;
		$display->default_col = 2;
		$display->allpage = TRUE;
		$display->cssclass_titlerow = 'table_head_col';
		$display->cssclass_datarow1 = 'table_body_row';
		$display->cssclass_datarow2 = 'table_body_row_none';
		foreach ($all_grades_data as $result) {
			$row = $this->_display_row($result);
			if ( !is_array($row) ) {
				osa_errorlog(__METHOD__ . ' got no data row.', array($row, $result));
				continue;
			}
			$display->add($row);
		}
		//Use different compare function for sort numbers becuase of th negative numbers.
		$display->column_data_align[2] = 'center';
		$display->column_sort_function[2] = 'osa_numeric_str_compare';
		$display->iswindow = FALSE;
		$display->force_sort = TRUE;
		$display->change_sort_direction = TRUE;
		$display->prepare_page();
		$data->display = & $display;
		$this->load->view('admin/grade_list_view', $data);
	}

	function _display_row($result){
		if ( !is_array($result) && count($result) <= 0 ) {
			return FALSE;
		}
		$width = self::dhtml_width;
		$height = self::dhtml_height;
		$grade_id = $result->id;
		$grade_name = $result->name;
		$grade_sort = $result->sort;
		$grade_school_name = $result->school_name;
		$refresh_page ='page_content';
		// Edit config
		$grade_edit_link = self::page_url . '/edit/' . $grade_id;
		$grade_div = self::grade_div;
		$grade_edit_image_filepath	= osa_imagepath() . 'edit_16.gif';
		// Delete config
		$grade_delete_link = self::page_url . '/delete/' . $grade_id;
		$grade_delete_image_filepath	= osa_imagepath() . 'x.gif';

		$grade_edit_image_newdhtmlwindow =
			$this->admin_base->newDhtmlWindow($grade_edit_link, lang('admin_grade_edit_title'), $width, $height, $grade_div,
														 $grade_edit_image_filepath, lang('admin_grade_title_edit') );
		$grade_delete_image_newdhtmlwindow =
			$this->admin_base->delTarget($grade_delete_link, $refresh_page, lang('admin_grade_delete_warning'),
												  $grade_delete_image_filepath, lang('admin_grade_delete_title') );
		// if has grade id on other tables, disable delete function
		if ( $this->_check_existing($grade_id) ){
				$grade_delete_image_filepath	= osa_imagepath() . 'x_dis.gif';
				$grade_delete_image_newdhtmlwindow = "<img src='{$grade_delete_image_filepath}' />" ;
		}
		$grade_edit_div_image = "<div style=\"display: inline;\">" . $grade_edit_image_newdhtmlwindow . "</div>";
		$grade_delete_image_div = "<div style=\"display: inline;\">" . $grade_delete_image_newdhtmlwindow . "</div>";
		$link = "<nobr>$grade_delete_image_div $grade_edit_div_image</nobr>";

		return array($grade_name, $grade_school_name, $grade_sort, $link);
	}

	// add button
	function _display_add(){
		$width = self::dhtml_width;
		$height  = self::dhtml_height;
		$add_url = self::page_url . '/add/';
		$div = self::grade_div;
		$image_name = osa_imagepath() . 'add_24.gif';

		return $this->admin_base->newDhtmlWindow($add_url, lang('admin_grade_add_title'), $width, $height, $div, $image_name, lang('admin_grade_add_title'));
	}

	// edit page
	function edit($grade_id, $action = CMS_ACTION_EDIT){
		if ( !isset($action) ) {
			echo osa_ajaxmsg( lang('gen_internalservererror') );
			exit;
		}

		$data = new stdClass();
		$sort_value = array();
		$data->page = self::page_url;
		$data->action = $action;
		$all_school_data = $this->grade_model->get_all_schools();
		$data->all_schools = $all_school_data;
		if ( $action == CMS_ADMIN_EDIT ){
			$get_grade = $this->grade_model->get_grade($grade_id);
			$data->grade_data = $get_grade;
			$result = $get_grade[0];
			$selected_title = $result->name;
			$selected_dropdown = $result->schoolid;
		}
		if ( $action == CMS_ADMIN_ADD ){
			$selected_title = lang('admin_grade_add_new_title');
			$selected_dropdown = $all_school_data[0];
			$all_grades_data = $this->grade_model->get_all_grades();
			// the newest should add at bottom so select a maximum sort value and plus one
			foreach ($all_grades_data as $result) {
				$sort_value[] = $result->sort;
			}
			// first add, sort value must be 1
			if ( $sort_value ) {
				$data->selected_sort = (int) max($sort_value) + 1;
			}
			else {
				$data->selected_sort = 1;
			}
		}
		$data->selected_title = $selected_title;
		$data->default_dropdown = $selected_dropdown;

		$this->load->view('admin/grade_input_view', $data);
	}
	// add page
	function add(){
		$this->edit(FALSE, CMS_ADMIN_ADD);
	}

	private function _form_handle($action){
		if ( $action != CMS_ADMIN_INSERT && $action != CMS_ADMIN_UPDATE ){
			echo osa_ajaxmsg( lang('gen_internalservererror') );
			exit;
		}

		$post_record_data = array();
		$grade_id = FALSE;
		$post_arraykeys = array_keys($_POST);
		$this->form_validation->set_rules('name', 'lang:admin_grade_column_name', 'required');
		$this->form_validation->set_rules('schoolid', 'lang:admin_grade_column_school', 'callback_schoolid_check');
		$this->form_validation->set_rules('sort', 'lang:admin_grade_column_sort', 'required|callback_sortvalue_check');
		if ( ! $this->form_validation->run() ) {
			echo osa_ajaxmsg( validation_errors() );
			exit;
		}
		// check integer in SORT field
		if ( osa_is_int($_POST['sort']) === FALSE){
			echo osa_ajaxmsg(lang('admin_grade_error_sort'));
			exit;
	 	}

		foreach ( $post_arraykeys as $arrkey ){
			if ( $arrkey != 'bustcache' && $arrkey != 'id' ) {
				$value = trim($_POST[$arrkey]);
				$post_record_data[$arrkey] = $value;
			}
			else if ( $arrkey == 'id' ){
				$grade_id = $_POST[$arrkey];
			}
		}

		if ( $action == CMS_ADMIN_UPDATE ) {
			if ( $grade_id == FALSE || is_numeric($grade_id) == FALSE) {
				echo osa_ajaxmsg( validation_errors() );
				exit;
			}
			$result = $this->grade_model->update_grade($grade_id, $post_record_data);
		}
		else if ( $action == CMS_ADMIN_INSERT ){
			$result = $this->grade_model->insert_grade($post_record_data);
		}
	}

	// passing values from EDIT page
	function update(){
		$this->_form_handle(CMS_ADMIN_UPDATE);
	}

	// passing values from ADD page
	function insert(){
		$this->_form_handle(CMS_ADMIN_INSERT);
	}

	// check value zero in school dropdown or not
	// value zero of school dropdown is default selected item
	function schoolid_check($gradeid){
		if ( $gradeid == '0' ){
			$this->form_validation->set_message('schoolid_check', lang('admin_grade_custom_errmsg'));
	 		return FALSE;
	 	}
	 	else {
	 		return TRUE;
	 	}
	}

	// check a sort number is duplicate or not
	// sort order number can't be duplicate
	function sortvalue_check($sort_value){
		$hidden_grade_id =  $this->input->post('id');
		$sort_array = array();
		$all_grades_data = $this->grade_model->get_all_grades();
		foreach ($all_grades_data as $result) {
				$sort_array[$result->id] = $result->sort;
		}
		// $key_value: in EDIT case we should check deuplicate same as ADD
		// but we must check exist value is changed or not, if not don't check
		$key_value = array_search($sort_value, $sort_array);
		if ( in_array($sort_value, $sort_array) && $key_value != $hidden_grade_id )	 {
			$this->form_validation->set_message('sortvalue_check', lang('admin_grade_custom_errmsg_noduplicate'));
			return FALSE;
	 	}
	 	else {
	 		return TRUE;
	 	}
	}

	// Delete function
	function delete($grade_id){
		if ( is_numeric($grade_id) == FALSE || !$this->_can_delete($grade_id) ){
			echo osa_ajaxmsg( lang('gen_internalservererror') );
			exit;
		}

		$result = $this->grade_model->delete_grade($grade_id);
		$this->index();
	}

	// check the relationship between grade and other tables
	// @return boolean
	private function _check_existing($gradeid) {
		return $this->grade_model->check_grade_relation_exists($gradeid);
	}

	// if another user changed a grade. this function can find out before delete.
	// @return boolean
	function _can_delete($gradeid){
		return !$this->grade_model->check_grade_relation_exists($gradeid);
	}

}