<?php
include_once($staticpath.'classes/InputButton.php');
//die('yy');
$submitButton = new InputButton;

if(!$_REQUEST['CREATEPDF'])
{
	echo GetBaseJavaFunc();
}
//die('bb');
$table = db_properties('DISCIPLINE_CUSTOM_FIELDS_ASG');
if(!$table['SELECT_CODES'])
{
	db_execute('ALTER TABLE DISCIPLINE_CUSTOM_FIELDS_ASG ADD SELECT_CODES VARCHAR(10000)');
}

DisplayHeader(".:".ProgramTitle().":.");

if($_REQUEST['values'] && $_POST['values'])
{
	foreach($_REQUEST['values'] as $id=>$columns)
	{
		if($id!='new')
		{
			$sql = "UPDATE DISCIPLINE_CUSTOM_FIELDS_ASG SET ";

			$go = false;
			foreach($columns as $column=>$value)
			{
				if($column!='DATA_TYPE')
				{
					$sql .= $column."='".str_replace("\'","''",$value)."',";
					$go = true;
				}
				else
					db_execute("UPDATE DISCIPLINE_REPORT_FIELDS SET DATA_TYPE='".$value."' WHERE ID='".$id."'");
			}
			$sql = substr($sql,0,-1) . " WHERE ID='$id'";
			if($go)
				db_execute($sql);
		}
		else
		{
			$sql = "INSERT INTO DISCIPLINE_REPORT_FIELDS ";
			
			$fields = "ID,COLUMN_NAME,";
			$values = db_seq_nextval('DISCIPLINE_REPORT_FIELDS_SEQ').",'CATEGORY_".$id."',";


			$go = 0;
			if($columns['TITLE'])
			{
            
				foreach($columns as $column=>$value)
				{
					if($value && $column!='SORT_ORDER' && $column!='SELECT_OPTIONS' && $column!='SELECT_CODES')
					{
						$fields .= $column.',';
						$values .= "'".str_replace("\'","''",$value)."',";
						if($column!='USER_TYPE')
							$go = true;
					}
				}
			
				$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
				if($go)
				{
					db_execute($sql);
					$id = db_seq_currval('DISCIPLINE_REPORT_FIELDS_SEQ');
				}
				$usage_sql = "INSERT INTO DISCIPLINE_CUSTOM_FIELDS_ASG ";
				
				$fields = "ID,DISCIPLINE_FIELD_ID,SCHOOL_YEAR,SCHOOL_ID,";
				$values = db_seq_nextval('DISCIPLINE_CUSTOM_FIELDS_ASG_SEQ').",'".$id."','".get_school_year()."','".get_school_id()."',";
            //print_r($values);
				
				foreach($columns as $column=>$value)
				{
					if($value && $column!='DATA_TYPE')
					{
						$fields .= $column.',';
						$values .= "'".str_replace("\'","''",$value)."',";
					}
				}
			
				$usage_sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';

				switch($columns['DATA_TYPE'])
				{
					case 'checkbox':
						db_execute("ALTER TABLE STUDENT_DISCIPLINE_REPORTS ADD CATEGORY_$id VARCHAR(1)");
					break;
					
					case 'text':
					case 'multiple_radio':
					case 'multiple_checkbox':
					case 'select':
						db_execute("ALTER TABLE STUDENT_DISCIPLINE_REPORTS ADD CATEGORY_$id VARCHAR(1000)");
					break;
					
					case 'numeric':
						db_execute("ALTER TABLE STUDENT_DISCIPLINE_REPORTS ADD CATEGORY_$id NUMERIC(10,2)");
					break;
					
					case 'date':
						if($DBType == 'mssql')
							db_execute("ALTER TABLE STUDENT_DISCIPLINE_REPORTS ADD CATEGORY_$id DATETIME");
						else
							db_execute("ALTER TABLE STUDENT_DISCIPLINE_REPORTS ADD CATEGORY_$id DATE");
					break;
					
					case 'textarea':
						db_execute("ALTER TABLE STUDENT_DISCIPLINE_REPORTS ADD CATEGORY_$id VARCHAR(5000)");
					break;
				}
				db_execute("CREATE INDEX STUDENT_DISCIPLINE_REPORTS_IND$id ON STUDENT_DISCIPLINE_REPORTS (CATEGORY_$id)");
				db_execute($usage_sql);
			}
		}

	}
	unset($_REQUEST['values']);
	unset($_SESSION['_REQUEST_vars']['values']);
}

if($_REQUEST['servicefunction']=='delete')
{
	if(DeletePrompt(_('this field from the report')))
	{
		$id = $_REQUEST['id'];
		db_execute("DELETE FROM DISCIPLINE_REPORT_FIELDS WHERE ID='$id'");
		db_execute("DELETE FROM DISCIPLINE_CUSTOM_FIELDS_ASG WHERE DISCIPLINE_FIELD_ID='$id'");
		if($DBType == 'mssql')
		  db_execute("DROP INDEX STUDENT_DISCIPLINE_REPORTS.STUDENT_DISCIPLINE_REPORTS_IND$id");
		db_execute("ALTER TABLE STUDENT_DISCIPLINE_REPORTS DROP COLUMN CATEGORY_$id");
		unset($_REQUEST['servicefunction']);
		unset($_REQUEST['id']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['id']);
	}
}

if($_REQUEST['servicefunction']=='delete_usage')
{
	if(DeletePrompt(_('this field in the report'),'deactivate'))
	{
		$id = $_REQUEST['id'];
		db_execute("DELETE FROM DISCIPLINE_CUSTOM_FIELDS_ASG WHERE ID='$id'");
		unset($_REQUEST['servicefunction']);
		unset($_REQUEST['id']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['id']);
	}
}

if($_REQUEST['servicefunction']=='add_usage')
{
	db_execute("INSERT INTO DISCIPLINE_CUSTOM_FIELDS_ASG (ID,DISCIPLINE_FIELD_ID,SCHOOL_YEAR,SCHOOL_ID,TITLE,SELECT_OPTIONS,SELECT_CODES,SORT_ORDER,USER_TYPE) SELECT ".db_seq_nextval('DISCIPLINE_CUSTOM_FIELDS_ASG_SEQ')." AS ID,'".$_REQUEST['id']."' AS DISCIPLINE_FIELD_ID,'".get_school_year()."' AS SCHOOL_YEAR,".get_school_id()." AS SCHOOL_ID,TITLE,NULL AS SELECT_OPTIONS,NULL AS SELECT_CODES,NULL AS SORT_ORDER,USER_TYPE FROM DISCIPLINE_REPORT_FIELDS WHERE ID='".$_REQUEST['id']."'");
	unset($_REQUEST['servicefunction']);
	unset($_REQUEST['id']);
	unset($_SESSION['_REQUEST_vars']['servicefunction']);
	unset($_SESSION['_REQUEST_vars']['id']);
}


if(!$_REQUEST['servicefunction'])
{
	$sql = "SELECT NULL AS REMOVE,du.ID AS USAGE_ID,df.ID,COALESCE(du.TITLE,df.TITLE) AS TITLE,du.SORT_ORDER,df.DATA_TYPE,du.SELECT_OPTIONS,du.SELECT_CODES,du.USER_TYPE FROM DISCIPLINE_REPORT_FIELDS df LEFT OUTER JOIN DISCIPLINE_CUSTOM_FIELDS_ASG du ON (du.DISCIPLINE_FIELD_ID=df.ID AND du.SCHOOL_YEAR='".get_school_year()."' AND du.SCHOOL_ID='".get_school_id()."') ORDER BY du.SORT_ORDER,du.ID";
	$QI = db_execute($sql);
//print_r($QI);
	$referrals_array = db_request($QI,array('REMOVE'=>'_makeRemove','TITLE'=>'_makeTextInput','SORT_ORDER'=>'_makeTextInput','DATA_TYPE'=>'_makeType','SELECT_OPTIONS'=>'_makeTextAreaInput','SELECT_CODES'=>'_makeTextAreaInput','USER_TYPE'=>'_makeUserType'));
//print_r($referrals_array); die('tt');
	foreach($referrals_array as $key=>$item)
	{
		if(!$item['USAGE_ID'])
			$referrals_array[$key]['row_color']='CCCCCC';
	}

	if(count($referrals_array) && AllowEdit() && !isset($_REQUEST['CREATEPDF']))
		$columns = array('REMOVE'=>'');
	else
		$columns = array();

	$columns += array('TITLE'=>_('Title'),'SORT_ORDER'=>_('Sort Order'),'DATA_TYPE'=>_('Data Field Type'),'SELECT_OPTIONS'=>_('List of Options for Pull-Down & Multiple Choices'),'SELECT_CODES'=>_('List of Codes'),'USER_TYPE'=>_('Permission to Modify'));
	$link['add']['html'] = array('REMOVE'=>button('add'),'TITLE'=>_makeTextInput('','TITLE'),'SORT_ORDER'=>_makeTextInput('','SORT_ORDER'),'SELECT_OPTIONS'=>_makeTextAreaInput('','SELECT_OPTIONS'),'SELECT_CODES'=>_makeTextAreaInput('','SELECT_CODES'),'DATA_TYPE'=>_makeType('','DATA_TYPE'),'USER_TYPE'=>_makeUserType('','USER_TYPE'));
	
	echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod] method=POST>";
	DisplayHeader('',$submitButton->createSButton(_('Save')));
	Gridoutput($referrals_array,$columns,_('Discipline Report Fields'),_('Amount of discipline report fields'),$link);
	echo '<CENTER>'.$submitButton->createSButton(_('Save')).'</CENTER>';
	echo '</FORM>';
}
//die('tt');
function _makeType($value,$name)
{	global $THIS_array;

	$new_options = array('checkbox'=>_('Checkbox'),'text'=>_('Text'),'multiple_checkbox'=>_('Select Multiple from Options'),'multiple_radio'=>_('Select One from Options'),'select'=>_('Pull-Down'),'date'=>_('Date'),'numeric'=>_('Numeric'),'textarea'=>_('Long Text'));
	
	if($THIS_array['ID'] && $value!='multiple_radio' && $value!='select')
		return $new_options[$value];
	elseif($THIS_array['ID'])
		return SelectInput($value,'values['.$THIS_array['ID'].']['.$name.']','',array('multiple_radio'=>_('Select One from Options'),'select'=>_('Pull-Down')),false);
	else
		return SelectInput($value,'values[new]['.$name.']','',$new_options,false);
}

function _makeUserType($value,$name)
{	global $THIS_array;

	if($THIS_array['USAGE_ID'])
		$id = $THIS_array['USAGE_ID'];
	elseif($THIS_array['ID'])
		$id = 'usage';
	else
		$id = 'new';

	$new_options = array('teacher'=>_('Teacher & Administration'),'official'=>_('Administration Only'));
	if($id=='usage')
		return '';		

	return SelectInput($value,'values['.$id.']['.$name.']','',$new_options,false);
}

function _makeTextInput($value,$name)
{	global $THIS_array;
	
	if($THIS_array['USAGE_ID'])
		$id = $THIS_array['USAGE_ID'];
	elseif($THIS_array['ID'])
		$id = 'usage';
	else
		$id = 'new';
	
	if($name!='TITLE')
		$addition = 'size=5 maxlength=2';
	if($name=='SORT_ORDER')
		$comment = '<!-- '.$value.' -->';

	if($id=='usage')
		return $value;		
	else
		return $comment.TextInput($value,'values['.$id.']['.$name.']','',$addition);
}

function _makeTextAreaInput($value,$name)

{	global $THIS_array;
	
	if($THIS_array['USAGE_ID'])
		$id = $THIS_array['USAGE_ID'];
	elseif($THIS_array['ID'])
		$id = 'usage';
	else
		$id = 'new';

	if($id=='usage')
		return $value;
	elseif($id=='new' || $THIS_array['DATA_TYPE']=='multiple_checkbox' || $THIS_array['DATA_TYPE']=='multiple_radio' || $THIS_array['DATA_TYPE']=='select')
		return TextAreaInput(str_replace('"','\"',$value),'values['.$id.']['.$name.']');
	else
		return _('N/A');
}

function _makeRemove($value,$column)
{	global $THIS_array;
	
	if($THIS_array['USAGE_ID'])
	{
		$return = button('deactivate',_('Deactivate field'),"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete_usage&id=$THIS_array[USAGE_ID]");
		$return .= button('remove',_('Delete field'),"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete&id=$THIS_array[ID]");
	}
	else
		$return = button('add',_('Activate field'),"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=add_usage&id=$THIS_array[ID]");

	return $return;
}
?>
