<?php
/**
 * strand.php - Controller for handling input pages.
 *
 * @author $Author: dtong $
 * @version $Id: strand.php,v 1.43 2011/05/09 11:59:58 dtong Exp $
 * @copyright Copyright (c) 2009, Tiller Software Co., Ltd.
*/

require_once(APPPATH . 'libraries/mapping/display_list.php');
class Strand extends CI_Controller{
	//This is used as the session variable name. All admin features use this name
   private $divid = 'strand'; //Used to be 'strand'
   //To start a new display session or not
   private $new_display_session = FALSE;

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

	//$index can be just an int or int_int like 7_2. The 2nd int is for sub index other than 1
	//Could add a optional parameter but since standard has to use int_int so do the same here
	function index($type,$index,$index_standard,$index_benchmark) {
		if ( !is_numeric($type) ) {
			return FALSE;
		}
		$this->new_display_session = TRUE;
		$this->refresh(CMS_ADMIN_ENABLE,$type,FALSE,FALSE,FALSE,$index,$index_standard,$index_benchmark);
	}

	function refresh($enableflag, $type=FALSE, $page_con=FALSE, $dep_schid=FALSE, $filter=FALSE,
						  $index=FALSE, $index_standard=FALSE, $index_benchmark=FALSE) {
		if ( $enableflag != CMS_ADMIN_DISABLE && $enableflag != CMS_ADMIN_ENABLE && $enableflag != CMS_ADMIN_ALL ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		//Hack to allow the sub/second index to pass in
		$sub_index = 1;
		if ( $index !== FALSE ) {
			$tmp_index = explode('_',$index);
			if ( count($tmp_index) > 1 ) {
				$index = $tmp_index[0];
				$sub_index = $tmp_index[1];
			}
		}

		$this->CI =  get_instance();
   		//Add Config
   	//$divid       = 'strand' ;
		$url_add	 = 'admin/strand/add/'.$enableflag;
		$div		 = 'strand_input';
		$width		 = 600;
		$height		 = 400;
		$title_add	 = lang('admin_strand_add_title');
		$imgaddname	 = osa_imagepath() . 'add_24.gif';
		$imgaddtitle = lang('admin_strand_title_add');
	   $imgeadd = $this->admin_base->newDhtmlWindow($url_add, $title_add, $width, $height, $div , $imgaddname,$imgaddtitle );

   	//$display  = $this->admin_base->init_display(CMS_ADMIN_STRAND_TYPE, $enableflag,$this->divid);
		if ( $this->new_display_session ) {
			$display = & $this->admin_base->init_display(CMS_ADMIN_STRAND_TYPE, $enableflag, $this->divid);
			$display->column_use_striptag[1] = TRUE;
		}
		else {
			$this->load->library('search/searchutil');
			$display = & $this->searchutil->get_session($this->divid);
			$display->reset_data();
		}
   	$display->menu = lang('admin_menu_strand');
   	$display->search = lang('admin_strand_search');
   	$_title = FALSE;
   	$_schoolflag = FALSE;
   	if (is_numeric($index) == FALSE){
			$temp  = $this->CI->searchsort_model->getSort($this->divid);
			$index = $temp->index;
   	}
   	$temp = $this->menu_main->get_template('admin');
		$template = $temp[$index][$sub_index];
		if (osa_get_template_value($template,'_title') != FALSE )
			$_title  = osa_get_template_value($template,'_title');
		if (osa_get_template_value($template,'_schoolflag') != FALSE )
			$_schoolflag  = osa_get_template_value($template,'_schoolflag');
		$_table = FALSE;
		if (osa_get_template_value($template,'_table') != FALSE )
			$_table  = osa_get_template_value($template,'_table');

		if ($index_standard == FALSE){
			$temp  = $this->CI->searchsort_model->getSort($this->divid);
			$index_standard = $temp->index_standard;
   	}
		$display->index_standard = $index_standard;

		if ($index_benchmark == FALSE){
			$temp  = $this->CI->searchsort_model->getSort($this->divid);
			$index_benchmark = $temp->index_benchmark;
   	}
		$display->index_benchmark = $index_benchmark;

		$display->table = $_table;
		$display->pagetitle = $_title;
   	$display->index = $index;
   	$display->schoolflag = $_schoolflag;

		$display->widths = array('30%', '57%', '10%', '3%');
   	$display->type = $type;
   		//$display->filter = $filter;
   	$display->filter=FALSE;
   	if ($filter != FALSE)
			$display->filter = $filter;
		else {
			if (isset($_POST['filter']))
				$display->filter = $_POST['filter'];
		}

  		$titles   = array( null,lang('admin_strand_display_strand'),
   					      lang('admin_strand_display_enabled'),
   					      $imgeadd
   					);
   	$display->dep_schid=FALSE;

   	if ($dep_schid != FALSE)
			$display->dep_schid = $dep_schid;
		else {
			if (isset($_POST['dep_schid']))
				$display->dep_schid = $_POST['dep_schid'];
		}

		if (isset($_schoolflag) && $_schoolflag != FALSE){
			$display->search_dep_sch = lang('admin_search_school');
			$titles[0] = lang('admin_strand_display_school');
			$display->data_dep_sch   = $this->strand_model->get_school($type,FALSE,$_table);
			$data = $this->strand_model->get_allstrand($enableflag, $display->type, $display->filter,FALSE,$display->dep_schid,$_table);
		}
		else{
			$display->search_dep_sch = lang('admin_search_department');
			$titles[0] = lang('admin_strand_display_department');
			$display->data_dep_sch   = $this->strand_model->get_department();
			$data = $this->strand_model->get_allstrand($enableflag, $display->type, $display->filter,$display->dep_schid,FALSE);
		}

	   $display->titles     = $titles;
	 	$page	= 'page_content';
		$display->refresh = $page;
		//TODO: Both are the same value...
		$display->enableflag = $enableflag;
		$display->selectlistitem = $enableflag;
		$display->strand=array();
		$display->standard =array();
		$splits = $this->admin_base->split($display->filter);
		if ($data != FALSE) {
			foreach ($data as $rows) {
				$enabled = $rows->enabled;
				if ($rows->enabled == CMS_ADMIN_DISABLE) {
					$rows->enabled  = '<div class="hide">'.lang('admin_list_convert_disabled').'</div>';
				   $imgdelname		= osa_imagepath() . 'enabled_16.gif';
				   $imgdeltitle	= lang('admin_strand_title_enable');
			    	$massage		= lang('admin_strand_message_enable');
				}
				elseif ($rows->enabled == CMS_ADMIN_ENABLE) {
					$rows->enabled  = '<div class="show">'.lang('admin_list_convert_enabled').'</div>';
				   $imgdelname		= osa_imagepath() . 'disable_16.gif';
				   $imgdeltitle	= lang('admin_strand_title_disable');
			    	$massage		= lang('admin_strand_message_disable');
				}

				//Edit Config
				$url_edit		= 'admin/strand/edit/'.$rows->id.'/'.$enableflag;
				$div			= 'strand_input';
				$title_edit		= lang('admin_strand_edit_title');
				$imgeditname	= osa_imagepath() . 'edit_16.gif';
				$imgedittitle	= lang('admin_strand_title_edit');

				//Link Config
				$lnkwidth	 	= 800;
				$lnkheight	 	= 750;
				$lnkdiv			= 'standard_list';
				$display->lnkdiv =$lnkdiv;

				if (isset($_schoolflag) && $_schoolflag != FALSE){
					$url_lnk = 'admin/standard/link/'.$display->type.'/'.$index_standard.'/'.'0'.'/'.$rows->schoolid.'/'.$rows->id.'/'.$index_benchmark;
				}
				else{
					$url_lnk = 'admin/standard/link/'.$display->type.'/'.$index_standard.'/'.'0'.'/'.$rows->departmentid.'/'.$rows->id.'/'.$index_benchmark;
				}

				$title_lnk = $_title;
				$linktitle = lang('admin_strand_link_title');

				//Delete Config
				$url_del		= 'admin/strand/delete/'.$rows->id.'/'.$enabled.'/'.$enableflag.'/'.$display->type;

				if ( $this->config->item('cms_lt_importid_support') && !empty($rows->importid) ) {
			  		$highlight_name = $this->admin_base->highlight($splits, "$rows->importid $rows->data");
				}
				else {
					$highlight_name = $this->admin_base->highlight($splits, $rows->data);
				}

			    $linkname = $this->admin_base->linkDhtmlWindow($url_lnk, $title_lnk, $lnkwidth, $lnkheight, $lnkdiv ,$highlight_name,$linktitle );
			    $imgedit  = $this->admin_base->newDhtmlWindow($url_edit, $title_edit, $width, $height, $div , $imgeditname,$imgedittitle );
			    $imgdel   = $this->admin_base->delTarget($url_del, $page ,$massage,$imgdelname, $imgdeltitle);
			    //$imgedit  = '<span class="strand_col_body_center_edit">' .$imgedit. '</span>';
			    //$imgdel   = '<span> class="strand_col_body_center_del">'  .$imgdel. '</span>';

			    $rowtemp = $rows->department;
			    if ( $rows->department_enabled == CMS_DB_BOOLEAN_FALSE ){
			    	//TODO: display sorting issue with HTML tags
			    	 $rowtemp = "<font color=\"grey\">$rowtemp</font>";
			    }
			    if (isset($_schoolflag) && $_schoolflag != FALSE) {
	   			 $rowtemp =  $rows->school;
			    }

		 		$temp = array($rowtemp,$linkname ,$rows->enabled, "<nobr>$imgdel $imgedit</nobr>");
				$display->add($temp);
			}
		}
		if ( $this->new_display_session ) {
			$display->default_col = 1;
		}
	   $this->admin_base->load_view($display);
	}

	// Inserts/adds a new strand
	function insert() {
		$data = array();
	   //$strandid = FALSE;
	   $keys = array_keys($_POST);
		$this->form_validation->set_rules('data', 'Strand', 'trim|required') ;
		$this->form_validation->set_rules('departmentid', 'Department ID', 'trim') ;
		$this->form_validation->set_rules('schoolid', 'School ID', 'trim') ;
		$run_result = $this->form_validation->run();

		//We need either department or school ID
		$deptid = set_value('departmentid');
		$schoolid = set_value('schoolid');
		if ( (!$run_result) || (empty($deptid) && empty($schoolid)) ) {
			echo osa_ajaxmsg(lang('admin_strand_validate_error'));
		   exit();
		}
		//This is all the fields in table strand except 'id' since no id is needed for insert
		$allowed_post_keys = array('schoolid','departmentid','type','enabled','importid','data');
		foreach ($keys as $key) {
			$lower_key = strtolower($key);
			if ( !in_array($lower_key, $allowed_post_keys) ) {
				continue;
			}
	      $value = trim($_POST[$key]);
	      if ($lower_key == 'enabled') {
		      if (strtolower($value) == 'on')
		     	 	$value = 1;
		     	else
		    	 	$value = 0;
	      }
	      /* elseif ($this->config->item('cms_lt_importid_support') && $lower_key == 'importid') {
				if ( !empty($value) ) {
					$bigint = osa_dotnum2int($value);
					if ( $bigint !== FALSE ) {
						$data['importid_int'] = $bigint;
					}
				}
	      } */
	     	$data[$lower_key] = $value;
	   }
		$result = $this->strand_model->add_strand($data);
		if ($result==1) {
			$result = 'success';
		}
		echo $result;
	}

	function update() {
		$this->CI =  get_instance();
		$data     = array();
	   $strandid = FALSE;
	   $keys = array_keys($_POST);

		$this->form_validation->set_rules('data', 'Data', 'required') ;
		$this->form_validation->set_rules('id', 'ID', 'required|is_numeric') ;
		$this->form_validation->set_rules('departmentid', 'deptid', 'trim') ;
		$this->form_validation->set_rules('schoolid', 'schoolid', 'trim') ;
		$run_result = $this->form_validation->run();
		$deptid = set_value('departmentid');
		$schoolid = set_value('schoolid');
		if ( (!$run_result) || (empty($deptid) && empty($schoolid) )) {
			echo osa_ajaxmsg(lang('admin_strand_validate_error'));
		   exit();
		}
	   foreach ($keys as $key) {
	    	switch($key) {
	    		case 'departmentid':
	    		case 'schoolid':
	    		case 'data':
	    		case 'importid':
	    			$value = trim($_POST[$key]);
	    			$data[$key] = $value;
	    			/* if ( $this->config->item('cms_lt_importid_support') ) {
	    				$data['importid_int'] = NULL;
		    			if ( !empty($value) ) {
							$bigint = osa_dotnum2int($value);
							if ( $bigint !== FALSE ) {
								$data['importid_int'] = $bigint;
							}
						}
	    			} */
	    			break;
	    		case 'id':
	    			$strandid = trim($_POST[$key]);
	    			break;
	    		case 'enabled':
	    			$value = 0;
	    			if ($_POST['enabled'] == 'on')
	    				$value = 1;
	    			$data['enabled'] = $value;
	    	}
	   }

	   //$divid = 'strand' ;
	   $temp  = $this->CI->searchsort_model->getSort($this->divid);

		$result=$this->strand_model->update_strand($strandid,$data);

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

		$temp->strandid = $strandid;
		$this->CI->searchsort_model->setSortSession($temp);
	}

    function add($enableflag=FALSE) {
        $this->edit(FALSE, $enableflag, CMS_ADMIN_ADD);
	}

	function edit($strandid, $list, $action=CMS_ADMIN_EDIT) {
		if ( is_numeric($list) == FALSE || $list < CMS_ADMIN_DISABLE || $list > CMS_ADMIN_ALL ) {
			// show error message
			echo 'error list';
			return FALSE;
		}
		$this->CI =  get_instance();
	   $data = FALSE;
	   //$divid = 'strand' ;
    	$temp = $this->CI->searchsort_model->getSort($this->divid);
    	$data->type = $temp->type;
	   $data->page = $this->admin_base->getpage(CMS_ADMIN_STRAND_TYPE);
      $data->selectlistitem = $list;
      //Note, even if a department is disabled it will show in the edit department list according to $strandid
	   $data->department = $this->strand_model->get_department($strandid);
	   $_table = FALSE;
	  	if (isset ($temp->table) && $temp->table != FALSE)
	  		$_table = $temp->table;
	   $data->school = $this->strand_model->get_school($data->type,FALSE,$_table);
	  	$data->dep_schid = $temp->dep_schid;
	  	$_schoolflag = FALSE;
	  	if (isset ($temp->schoolflag) && $temp->schoolflag != FALSE)
	  		$_schoolflag = $temp->schoolflag;
	  	$data->schoolflag = $_schoolflag;
   	if ($data->dep_schid == FALSE || $data->dep_schid =='')
   			$data->dep_schid ='0';
   	$data->filter=$temp->filter;
    	if ($temp->filter==FALSE && $temp->filter=='')
    		$data->filter = FALSE;

	   	$data->action = $action;

	    if ($action == CMS_ADMIN_EDIT ) {
			$strand = $this->strand_model->get_strand($strandid);
			if ($strand==FALSE || count($strand)==0) {
				// show error message
				echo osa_ajaxmsg(lang('gen_internalservererror'));
				exit;
			}

	   		$data->data = $strand;
	   		$row = $strand[0];
	   		$selected_dep = $row->departmentid;
	   		$selected_school = $row->schoolid;
	   		$selected_type = $row->type;
	   		$selected_display = $row->data;
	    }
	    elseif ($action == CMS_ADMIN_ADD ) {
	    	//TODO: These 2 lines do nothing at all...
    		$selected_dep 	= $data->department[0];
   		$selected_school = $data->school[0];
    		if ( property_exists($data, 'dep_schid') && !empty($data->dep_schid) ) {
    			//Seems like the code assigns school or dept to dep_schid
    			//We can have only school or department so the code works but very messy
    			//All these will have to go away...
				$selected_dep = $data->dep_schid;
				$selected_school = $data->dep_schid;
    		}
   		$selected_type = $data->type[0];
   		$selected_display	= lang('admin_strand_add_head');
	    }

	      $data->selected_dep 	= $selected_dep;
	   	$data->selected_school = $selected_school;
	   	$data->selected_type = $selected_type;
	   	$data->selected_display = $selected_display;

	   	$data->show_importid = FALSE;
	   	if ( $this->config->item('cms_lt_importid_support') ) {
				$data->show_importid = TRUE;
	   	}
	  		$this->load->view('admin/strand_input_view',$data);
	}

	function delete($strandid, $enabled, $enabledflag,$type) {
		if ( is_numeric($strandid)==FALSE ||  is_numeric($enabled)==FALSE ||  is_numeric($enabledflag)==FALSE ) {
			// show error message
			echo 'error list';
			return FALSE;
		}

		if ( $enabled < CMS_ADMIN_DISABLE && $enabled > CMS_ADMIN_ENABLE ) {
			// show error message
			echo 'error list';
			return FALSE;
		}
		$this->CI = get_instance();
		//$divid = 'strand' ;
		$temp  = $this->CI->searchsort_model->getSort($this->divid);
		$dep_schid= '0';
	    if ($temp->dep_schid!=FALSE && $temp->dep_schid!='')
	    	$dep_schid = $temp->dep_schid;
	    $filter= FALSE;
	    if ($temp->filter!=FALSE && $temp->filter!='')
	    	$filter = $temp->filter;

		if ($enabled==CMS_ADMIN_DISABLE) {
			$enabled= CMS_ADMIN_ENABLE;
			$temp->strandid = $strandid;
			$this->CI->searchsort_model->setSortSession($temp);
		}
		else {
			$enabled= CMS_ADMIN_DISABLE;
		}

	   $this->strand_model->del_strand($strandid, $enabled);
	   $this->refresh($enabledflag,$type,FALSE,$dep_schid,$filter);
	}
/*
	function search() {
		$this->CI =  get_instance();
		//$divid = 'strand' ;
		$strand  = $this->CI->searchsort_model->getSort($this->divid);
	   	$_type = $strand->type;
	   	$dep_schid= '0';
	    if ($strand->dep_schid!=FALSE && $strand->dep_schid!='')
	    $dep_schid=	$strand->dep_schid;

	 	$keys = array_keys($_POST);
		 foreach ($keys as $key) {
		    if ($key != 'bustcache') {
		    	$value = trim($_POST[$key]);
				if ($key == 'filter'){
					$filter = $value;
				}
				elseif ($key == 'filters'){
					$enableflag = $value;
				}

			}
		}
    	echo $enableflag.'/'.$_type.'/'.'0'.'/'.$dep_schid.'/'.$filter;
	}
*/

	function search() {
		$this->access_model->checkaccess_any('admin_system_management');
		$this->load->library('search/searchutil');
		$display = & $this->searchutil->get_session($this->divid);
		//$display->selectlistitem = $enableflag;
		$filter = FALSE;
		if ( array_key_exists('filter', $_REQUEST) ) {
			$filter = $_REQUEST['filter'];
		}
		$this->refresh($display->selectlistitem, $display->type, 'page_content', $display->dep_schid,
							$filter, $display->index, $display->index_standard, $display->index_benchmark);
	}

}
?>