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

if($_REQUEST['values'] && $_POST['values'] && AllowEdit())
{
	foreach($_REQUEST['values'] as $id=>$columns)
	{		
		if($id!='new')
		{
			$sql = "UPDATE GRADUATION_REQ_SUBJECTS SET ";
							
			foreach($columns as $column=>$value)
			{
				$sql .= $column."='".str_replace("\'","''",$value)."',";
			}
			$sql = substr($sql,0,-1) . " WHERE ID='$id'";
			db_execute($sql);
		}
		else
		{
			$sql = "INSERT INTO GRADUATION_REQ_SUBJECTS ";

			$fields = 'ID,SCHOOL_ID,';
			$values = db_seq_nextval('GRADUATION_REQ_SUBJECTS_SEQ').",'".get_school_id()."',";

			$go = 0;
			foreach($columns as $column=>$value)
			{
				if($value)
				{
					$fields .= $column.',';
					$values .= "'".str_replace("\'","''",$value)."',";
					$go = true;
				}
			}
			$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
			
			if($go)
				db_execute($sql);
		}
	}
}

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

if($_REQUEST['servicefunction']=='remove' && AllowEdit())
{
	if(DeletePrompt(_('subject')))
	{
		db_execute("DELETE FROM GRADUATION_REQ_SUBJECTS WHERE ID='$_REQUEST[id]'");
		unset($_REQUEST['servicefunction']);
	}
}

if($_REQUEST['servicefunction']!='remove')
{
	$sql = "SELECT ID,TITLE,SORT_ORDER,CREDITS,SHORT_NAME FROM GRADUATION_REQ_SUBJECTS WHERE SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER";
	$QI = db_execute($sql);
	$subjects_array = db_request($QI,array('SORT_ORDER'=>'_makeTextInput','TITLE'=>'_makeTextInput','SHORT_NAME'=>'_makeTextInput','CREDITS'=>'_makeTextInput'));

	$columns = array('SORT_ORDER'=>_('Sort Order'),'TITLE'=>_('Title'),'SHORT_NAME'=>_('Short Name'),'CREDITS'=>_('Credits Required for Graduation'));

	$link['add']['html'] = array('TITLE'=>_makeTextInput('','TITLE'),'SORT_ORDER'=>_makeTextInput('','SORT_ORDER'),'SHORT_NAME'=>_makeTextInput('','SHORT_NAME'),'CREDITS'=>_makeTextInput('','CREDITS'));
	$link['remove']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=remove";
	$link['remove']['variables'] = array('id'=>'ID');
	
	echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=update method=POST>";
	DisplayHeader('',$submitButton->createSButton(_('Save')));
	Gridoutput($subjects_array,$columns,_('Subject'),_('Subjects'),$link);
	echo '<CENTER>'.$submitButton->createSButton(_('Save')).'</CENTER>';
	echo '</FORM>';
}

function _makeTextInput($value,$name)
{	global $THIS_array;
	
	if($THIS_array['ID'])
		$id = $THIS_array['ID'];
	else
		$id = 'new';
	
	if($name!='TITLE')
		$addition = 'size=5 maxlength=10';
	else
		$addition = 'size=25';
	
	return TextInput($value,'values['.$id.']['.$name.']','',$addition);
}

?>