<?php
/**
 * category.php - admin category config
 *
 * @author $Author: dtong $
 * @version $Id: category.php,v 1.17 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 Category extends CI_Controller{
	const PAGE_URL = 'admin/category';
	const CATEGORY_DIV = 'category_input';
	const DHTML_WIDTH = 600;
	const DHTML_HEIGHT = 550;
	const REFRESH_PAGE = 'page_content';
	private $divid = 'adminss';

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

	function index($filter = CMS_ADMIN_ENABLE){
		$data = new stdClass();
		$this->load->library('mapping/display_list');
		$display = $this->display_list;
		$display->divid = $this->divid;
		$data->filter = $filter;
		// ADD button in title table
		$add_button = $this->_display_add_button($filter);
		// set title row
		$display->titles = array(
										 lang('admin_category_display_category_name'),
										 lang('admin_category_display_mingrade'),
										 lang('admin_category_display_maxgrade'),
										 lang('admin_category_display_department_name'),
										 lang('admin_category_display_sort'),
										 lang('admin_category_display_enabled'),
										 $add_button
		);
		// set title row width
		$display->widths = array('25%', '13%', '13%', '33%', '10%', '3%', '3%');
		// display all category
		$category_array = $this->_display_row($filter);
		foreach ($category_array as $result) {
			$display->add($result);
		}
		// no sort(sort_columns) and display all result in one page(allpage)
		//$display->sort_columns = FALSE;
		$display->allpage = TRUE;
		$display->cssclass_titlerow = 'table_head_col';
		$display->cssclass_datarow1 = 'table_body_row';
		$display->cssclass_datarow2 = 'table_body_row_none';
		$data->indexurl = self::PAGE_URL . '/index/';
		$data->refreshpage = self::REFRESH_PAGE;
		$data->display = $display;
		// tell user 'cms_menutree_use_category' config is on or not
		if ( $this->config->item('cms_menutree_use_category') ) {
			$data->isset_category_config = lang('admin_category_use_category_on');
		}
		else{
			$data->isset_category_config = lang('admin_category_use_category_off');
		}
		$display->column_data_align[4] = 'center';
		$display->default_col = 4;
		$display->column_sort_function[4] = 'osa_numeric_str_compare';
		$display->iswindow = FALSE;
		$display->force_sort = TRUE;
		$display->change_sort_direction = TRUE;
		$display->prepare_page();
		$this->load->view('admin/category_list_view', $data);
	}

	private function _display_add_button($filter){
		$add_url = self::PAGE_URL . '/add/'. $filter;
		$add_imagepath = osa_imagepath() . 'add_24.gif';
		return $this->admin_base->newDhtmlWindow($add_url, lang('admin_category_add_title'), self::DHTML_WIDTH, self::DHTML_HEIGHT,
															  self::CATEGORY_DIV, $add_imagepath, lang('admin_category_add_title'));
	}

	// return array $category_result
	private function _display_row($filter){
		$all_category_department = $this->category_model->get_all_category_department($filter);
		$category_id = '';
		$i = 0;
		$edit_div = self::CATEGORY_DIV;
		$edit_imgfilepath = osa_imagepath() . 'edit_16.gif';
		$disable_imgfilepath = osa_imagepath() . 'disable_16.gif';
		$enable_imgfilepath = osa_imagepath() . 'enabled_16.gif';
		$category_result = array();
		// if department has the same category id, concat department name with separator in the same array
		// note: work with sort by category id in model->get_all_category_department
		foreach ($all_category_department as $result){
			// if category result has same category id, use the same row and separate department by comma (,)
			if ($category_id == $result->c_id) {
				$department_name .= ', ' . $result->dp_name;
				$category_result[$i-1] = array($category_name, $mingrade, $maxgrade, $department_name, $sort, $enabled_text, $action_link);
				continue;
			}
			$department_name = $result->dp_name;
			// no dapartments mean select all departments
			if ( $department_name == NULL) {
				$department_name = lang('admin_category_display_no_department_name');
			}
			$category_name = $result->c_name;
			$category_id = $result->c_id;
			$maxgrade = $result->maxgrade;
			$mingrade = $result->mingrade;
			$sort = $result->c_sort;
			$enabled = $result->c_enabled;
			// Edit config
			$edit_link = self::PAGE_URL . '/edit/' . $category_id  .'/' .$filter;;
			// Disable config
			$enabled_link = self::PAGE_URL . '/enabled/' . $category_id;

			$edit_dhtml =
				$this->admin_base->newDhtmlWindow($edit_link, lang('admin_category_edit_title'), self::DHTML_WIDTH, self::DHTML_HEIGHT,
															 $edit_div, $edit_imgfilepath, lang('admin_category_title_edit') );
			// if category is enable, has disable image
			if ( $enabled == CMS_ADMIN_ENABLE) {
				$enabled_link = $enabled_link .'/'. CMS_ADMIN_DISABLE .'/'. $filter;
				$enabled_dhtml =
					$this->admin_base->delTarget($enabled_link, self::REFRESH_PAGE, lang('admin_category_disable_warning'),
													  $disable_imgfilepath, lang('admin_category_disable_title') );
				$enabled_text = '<div class="show">' . lang('admin_category_row_enable') . '</div>';
			}
			else if ( $enabled == CMS_ADMIN_DISABLE ){
				$enabled_link = $enabled_link .'/' . CMS_ADMIN_ENABLE .'/'. $filter;
				$enabled_dhtml =
					$this->admin_base->delTarget($enabled_link, self::REFRESH_PAGE, lang('admin_category_enable_warning'),
													  $enable_imgfilepath, lang('admin_category_enable_title') );
				$enabled_text = '<div class="hide">' . lang('admin_category_row_disable') . '</div>';
			}

			$action_link = "<nobr>$enabled_dhtml $edit_dhtml</nobr>";
			$category_result[$i] = array($category_name, $mingrade, $maxgrade, $department_name, $sort, $enabled_text, $action_link);
			$i++;
		}
		return $category_result;
	}

	function edit($catgory_id, $filter, $action = CMS_ADMIN_EDIT){
		if ( $action != CMS_ADMIN_ADD && $action != CMS_ADMIN_EDIT ) {
			echo osa_ajaxmsg( lang('gen_internalservererror') );
			false;
		}
		$data = new stdClass();
		$data->action = $action;
		$data->refresh_link = base_url() . self::PAGE_URL . '/index/'. $filter;
		$data->all_grades = $this->category_model->get_name_grades();
		if ( $action == CMS_ADMIN_ADD ) {
			$data->all_dapartments = $this->category_model->get_all_departments();
			$sort_value = $this->category_model->get_sort_category();
			$data->title = lang('admin_category_add_title');
			// set default selected
			$data->selected_gmin_dropdown = $data->all_grades[0];
			$data->selected_gmax_dropdown = $data->all_grades[0];
			$data->selected_department = '';
			$data->checked = CMS_ADMIN_ENABLE;
			$data->category_id = '';
			$data->category_name = '';
			// first add, sort value must be 1
			if ( $sort_value ) {
				$data->sort = (int) max($sort_value) + 1;
			}
			else {
				$data->sort = 1;
			}
			$data->mode = self::PAGE_URL .'/'. CMS_ADMIN_INSERT;
		}
		else if ( $action == CMS_ADMIN_EDIT) {
			$all_departments = $this->category_model->get_all_departments(TRUE);
			//get the category
			$records = $this->category_model->get_category_department($catgory_id);
			if ( !$records ) {
				echo osa_ajaxmsg(lang('gen_internalservererror'));
				exit;
			}
			$deparement_id = array();
			foreach ($records as $result) {
				$title = $result->c_name;
				$deparement_id[] = $result->dp_id;
				$enabled = $result->c_enabled;
				$data->selected_gmin_dropdown = $result->mingrade;
				$data->selected_gmax_dropdown = $result->maxgrade;
				$data->sort = $result->c_sort;
			}

			//Check for diabled departments there were not selected for the category and delete them here
			//We do want to show selected disabled departments here
			$data->all_dapartments = array();
			foreach ($all_departments as $key => $value) {
				if ( $value->enabled == CMS_DB_BOOLEAN_TRUE || in_array($value->id, $deparement_id)) {
					$data->all_dapartments[$key] = $value->name;
				}
			}
			$data->title = $title;
			$data->selected_department = $deparement_id;
			// form_checkbox() uses boolean to determine whether the box should be checked or not.
			$data->checked = (boolean) $enabled;
			$data->category_id = $catgory_id;
			$data->category_name = $title;
			$data->mode = self::PAGE_URL  .'/'. CMS_ADMIN_UPDATE;
		}
		else {
			//No valid action so just print an error
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		$this->load->view('admin/category_input_view', $data);
	}
	// ADD using EDIT function
	function add($filter) {
		$this->edit(FALSE, $filter, CMS_ADMIN_ADD);
	}

	// Handle form update/insert function
	private function _form_handle($action){
		if ( $action != CMS_ADMIN_INSERT && $action != CMS_ADMIN_UPDATE ){
			echo osa_ajaxmsg( lang('gen_internalservererror') );
			false;
		}
		$this->form_validation->set_rules('name', 'lang:admin_category_column_name', 'required');
		$this->form_validation->set_rules('mingradeid', 'lang:admin_category_column_mingrade', 'required|callback_minmax_grade_check');
		$this->form_validation->set_rules('maxgradeid', 'lang:admin_category_column_maxgrade', 'required|callback_minmax_grade_check');
		$this->form_validation->set_rules('sort', 'lang:admin_category_column_sort', 'required|callback_sortvalue_check');
		if ( ! $this->form_validation->run() ) {
			echo osa_ajaxmsg( validation_errors() );
			exit;
		}
		$post_record_data = array();
		$post_arraykeys = array_keys($_POST);
		$category_id = '';
		$category_enabled = '';
		foreach ( $post_arraykeys as $arrkey ){
			if ( $arrkey == 'id' ){
				$category_id = $_POST[$arrkey];
			}
			// convert enabled field from checkbox to interger value
			if ( $arrkey == 'enabled' ) {
		    	  	 if ( $_POST[$arrkey] == 'accept' ){
		    		 	 $category_enabled = CMS_ADMIN_ENABLE;
		    	  	 }
		    		 else {
		    			 $category_enabled = CMS_ADMIN_DISABLE;
		    		 }
	    	}
			$post_record_data[$arrkey] = $_POST[$arrkey];
		} // end foreach

		if ( $action == CMS_ADMIN_UPDATE ){
			$result = $this->category_model->update_category($category_id, $category_enabled, $post_record_data);
		}
		else if ( $action == CMS_ADMIN_INSERT ){
			$result = $this->category_model->insert_category($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 grade dropdown or not, value zero of grade dropdown is default selected item
	 * check min grade always has to be less than max grade
	 */
	function minmax_grade_check(){
		if ( $this->input->post('mingradeid') == 0 || $this->input->post('maxgradeid') == 0) {
			$this->form_validation->set_message('minmax_grade_check', lang('admin_category_custom_errmsg') );
			return FALSE;
		}
		// check min max values by using sort
		$grade = $this->category_model->get_sort_grades();
		$grademin = $grade[$this->input->post('mingradeid')];
		$grademax = $grade[$this->input->post('maxgradeid')];
		if ( $grademax < $grademin ) {
			$this->form_validation->set_message('minmax_grade_check', lang('admin_category_custom_errmsg_minmax') );
			return FALSE;
		}
		return TRUE;
	}
	// check a sort number is duplicate or not
	// sort order number can't be duplicate
	function sortvalue_check($sort_value){
		if ( osa_is_int($sort_value) === FALSE ){
			$this->form_validation->set_message('sortvalue_check', lang('admin_category_error_sort'));
			return FALSE;
		}
		$hidden_grade_id =  $this->input->post('id');
		$sort_array = $this->category_model->get_sort_category();
		// $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_category_custom_errmsg_noduplicate'));
			return FALSE;
	 	}
	 	else {
	 		return TRUE;
	 	}
	}
	// Disable/Enable category
	function enabled($category_id, $action, $filter){
		if ( $category_id == FALSE || ($action != CMS_ADMIN_ENABLE && $action != CMS_ADMIN_DISABLE ) ) {
			echo osa_ajaxmsg( lang('gen_internalservererror') );
			exit;
		}
		$this->category_model->enabled($category_id, $action);
		$this->index($filter);
	}

}