<?php

include_once('modules/mod_students/includes/studatafieldsfunc.inc.php');
if(get_student_id() && get_user('PROFILE') == 'applicant')
{
   $verif = db_request(db_execute("select APPLICANT_VERIFIED from app_identify where student_id = '".get_student_id()."'"));
    if($verif[1]['APPLICANT_VERIFIED'] == 'N')
        $_SYSTEM['allow_edit'] = false;
}
if($_REQUEST['servicefunction']=='delete' && $_REQUEST['enrollment_id'] && get_user('PROFILE')=='admin')
{
	if(!$_REQUEST['delete_ok'] && !$_REQUEST['delete_cancel'])
		echo '</FORM>';
	if(DeletePrompt(_('enrollment record')))
	{
		db_execute("DELETE FROM STUDENT_REGISTRATION WHERE ID='$_REQUEST[enrollment_id]'");
		unset($_REQUEST['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_REQUEST['enrollment_id']);
		unset($_SESSION['_REQUEST_vars']['enrollment_id']);
		unset($_SESSION['_REQUEST_vars']['delete_ok']);
		echo '<script language=javascript>document.location.href="'.SetRequestOptions().'";</script>';
		exit;
	}
        exit;
}

if(($_REQUEST['month_values'] && $_POST['month_values']) || ($_REQUEST['values']['STUDENT_REGISTRATION'] && $_POST['values']['STUDENT_REGISTRATION']))
{
	if(!$_REQUEST['values']['STUDENT_REGISTRATION']['new']['ENROLLMENT_CODE'] && !$_REQUEST['month_values']['STUDENT_REGISTRATION']['new']['START_DATE'])
	{
		unset($_REQUEST['values']['STUDENT_REGISTRATION']['new']);
		unset($_REQUEST['day_values']['STUDENT_REGISTRATION']['new']);
		unset($_REQUEST['month_values']['STUDENT_REGISTRATION']['new']);
		unset($_REQUEST['year_values']['STUDENT_REGISTRATION']['new']);
	}
	else
	{
		$date = $_REQUEST['year_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$_REQUEST['month_values']['STUDENT_REGISTRATION']['new']['START_DATE'].'-'.$_REQUEST['day_values']['STUDENT_REGISTRATION']['new']['START_DATE'];
		$found_array = db_request(db_execute("SELECT ID FROM STUDENT_REGISTRATION WHERE STUDENT_ID='".get_student_id()."' AND SCHOOL_YEAR='".get_school_year()."' AND '$date' BETWEEN START_DATE AND END_DATE"));
		if(count($found_array))
		{
			unset($_REQUEST['values']['STUDENT_REGISTRATION']['new']);
			unset($_REQUEST['day_values']['STUDENT_REGISTRATION']['new']);
			unset($_REQUEST['month_values']['STUDENT_REGISTRATION']['new']);
			unset($_REQUEST['year_values']['STUDENT_REGISTRATION']['new']);
			echo ErrorMessage(array(_('The student is already enrolled in this date, and could not be re-enrolled a second time on the date you specified. You have to change the date, and try enroll the student again.')));
		}
	}
	
	$iu_extra['STUDENT_REGISTRATION'] = "STUDENT_ID='".get_student_id()."' AND ID='__ID__'";
	$iu_extra['fields']['STUDENT_REGISTRATION'] = 'ID,SCHOOL_YEAR,STUDENT_ID,';
	$iu_extra['values']['STUDENT_REGISTRATION'] = db_seq_nextval('STUDENT_REGISTRATION_SEQ').",'".get_school_year()."','".get_student_id()."',";
	if(!$new_student)
		SaveData($iu_extra,'',$field_names);

	unset($_SESSION['_REQUEST_vars']['month_values']);
	unset($_SESSION['_REQUEST_vars']['day_values']);
	unset($_SESSION['_REQUEST_vars']['year_values']);
	unset($_REQUEST['values']['STUDENT_REGISTRATION']);
	unset($_SESSION['_REQUEST_vars']['values']['STUDENT_REGISTRATION']);
}

$have_state_columns = StateFieldsSet("STUDENT_REGISTRATION");

$functions = array('START_DATE'=>'_makeStartInput','END_DATE'=>'_makeEndInput','GROUP_ID'=>'get_group_title');
if($_REQUEST['servicemod']=='mod_apply/Applicants.php')
{
    $functions['CFIELD_15']='_fromadding';
    $functions['CFIELD_16']='get_teacher_allschools';
    $application_field = 'e.CFIELD_15,e.CFIELD_16,';
}
$functions['CFIELD_1']='_make_state_TextInput';
$functions['CFIELD_2']='_make_state_DateInput';

if($have_state_columns)
    $functions += StateFieldsFunctions("STUDENT_REGISTRATION", "_make_state_CheckboxInput", "_make_state_SelectInput", "_make_state_TextInput");

if($_REQUEST['historical']=='Y')
{
	$functions['SCHOOL_YEAR'] = 'MakeSchoolYear';
	$functions['CLASSLEVEL_ID'] = 'get_classlevel';
}

if(SystemPreferences('CHANGESRSCHOOL', 'applicants', false) == 'Y')
    $functions['SCHOOL_ID'] = '_make_change_school';
else
    $functions['SCHOOL_ID'] = 'get_school';
$state_fields = $have_state_columns ? (StateFieldsSet("STUDENT_REGISTRATION")?",".StateFieldsSQL("STUDENT_REGISTRATION", "e", "STUDENT_REGISTRATION","CFIELD_15"):"") : "";
//$fields = ($_REQUEST['servicemod']=='mod_apply/AddApp.php')?$values."'byoperator',":$values;
unset($THIS_array);
if(get_student_id()) 
{
	if($_REQUEST['historical'] == 'Y') 
		$array = db_request(db_execute("SELECT e.ID,e.SCHOOL_YEAR,e.CFIELD_1,e.CFIELD_2,e.CLASSLEVEL_ID,e.INCLUDE_IN_GROUP_RANK,".$application_field."e.GROUP_ID,e.ENROLLMENT_CODE,e.START_DATE,e.DROP_CODE,e.END_DATE,e.END_DATE AS END2,e.SCHOOL_ID,e.NEXT_SCHOOL,e.CALENDAR_ID,e.INCLUDE_IN_CLASS_RANK{$state_fields} FROM STUDENT_REGISTRATION e WHERE e.STUDENT_ID='".get_student_id()."' ORDER BY e.START_DATE"),$functions);
	else 
		$array = db_request(db_execute("SELECT e.ID,e.ENROLLMENT_CODE,e.CFIELD_1,e.CFIELD_2,e.START_DATE,e.DROP_CODE,e.END_DATE,e.END_DATE AS END2,".$application_field."e.SCHOOL_ID,e.NEXT_SCHOOL,e.INCLUDE_IN_GROUP_RANK,e.GROUP_ID,e.CALENDAR_ID,e.INCLUDE_IN_CLASS_RANK{$state_fields} FROM STUDENT_REGISTRATION e WHERE e.STUDENT_ID='".get_student_id()."' AND e.SCHOOL_YEAR='".get_school_year()."' ORDER BY e.START_DATE"),$functions);
}
else
	$array = array();

$link['add'] = false;
$add = true;
if(count($array))
{
	foreach($array as $value)
	{
		if(($value['DROP_CODE']=='' || !$value['DROP_CODE']) && ($value['END2']=='' || !$value['END2']))
			$add = false;
	}
}
if($add)
	$link['add']['html'] = array('START_DATE'=>_makeStartInput('','START_DATE'),'SCHOOL_ID'=>_makeSchoolInput('','SCHOOL_ID'));

$columns = array('START_DATE'=>_('Date of Student Enrollment - Enrollment Code'),
		 'END_DATE'=>_('Student Dropped Date - Enrollment Code'),
		 'SCHOOL_ID'=>_('School Name'),
		 'GROUP_ID'=>_('Class Group'),
		 'CFIELD_1'=>_('Order Number'),
		 'CFIELD_2'=>_('Order Date'),
                 'CFIELD_15'=>_('Added By'),
                 'CFIELD_16'=>_('Created By')
		 );
if($_REQUEST['servicemod']<>'mod_apply/Applicants.php')
{
	unset($columns['CFIELD_15']);
	unset($columns['CFIELD_16']);
}
if(Preferences('DISPLAY_GROUP') != 'Y' || $_REQUEST['servicemod']=='mod_apply/Applicants.php')
	unset($columns['GROUP_ID']);
if($student_id == 'new')
{
	unset($columns['END_DATE']);
        unset($columns['CFIELD_15']);
}

if($_REQUEST['historical']=='Y')
{
	$columns['SCHOOL_YEAR'] = _('School Year');
	$columns['CLASSLEVEL_ID'] = _('Class Level');
	$columns['GROUP_ID'] = _('Class Group');
        $columns['CFIELD_15'] = _('Added By');        
	if(Preferences('DISPLAY_GROUP') != 'Y')
		unset($columns['GROUP_ID']);
        if($_REQUEST['servicemod']<>'mod_apply/Applicants.php')
                unset($columns['CFIELD_15']);
}

if($have_state_columns)
    $columns += StateFieldsArray("STUDENT_REGISTRATION");

$_REQUEST['servicefunction'] = '';
$schools_array = db_request(db_execute("SELECT ID,TITLE FROM SCHOOLS WHERE ID!='".get_school_id()."'"));
$next_school_options = array(get_school_id()=>_('Next grade level at current school'),
			     '0'=>_('Retain'),
			     '-1'=>_('Do not enroll for the next school year'));
if($_REQUEST['servicemod']==='mod_apply/Applicants.php')
{
$app_schools_array = db_request(db_execute("SELECT ID,TITLE FROM SCHOOLS WHERE ID NOT IN (".implode(',',get_apply_school_array()).")"));
//	unset($next_school_options[0]);
//	unset($next_school_options[-1]);
//	unset($next_school_options[get_school_id()]);
	$next_school_options = array('0'=>_('Participate in entry competition'),
			     '-1'=>_('Do not enroll to any school '));
	
}
if(count($schools_array) && $_REQUEST['servicemod']!='mod_apply/Applicants.php')
{
	foreach($schools_array as $school)
		$next_school_options[$school['ID']] = _('Enroll to: ').$school['TITLE'];
}
else
{
	if(!is_array($app_schools_array)) $app_schools_array = array();
	foreach($app_schools_array as $school)
		$next_school_options[$school['ID']] = _('Enroll to: ').$school['TITLE'];
}

$school_years = get_school_year();
if(get_student_id() && $_REQUEST['historical']=='Y')
{
    $school_years_array = db_request(db_execute("SELECT SCHOOL_YEAR FROM STUDENT_REGISTRATION WHERE STUDENT_ID=".get_student_id().""));
    $school_years = '';
    foreach($school_years_array as $year)
    {
	$school_years .= "".$year['SCHOOL_YEAR'].",";
    }
    $school_years = substr($school_years,0,-1);
}
$calendars_array = db_request(db_execute("SELECT CALENDAR_ID,DEFAULT_CALENDAR,TITLE FROM SCHOOL_CALENDARS WHERE SCHOOL_YEAR IN (".$school_years.") AND SCHOOL_ID='".get_school_id()."' ORDER BY DEFAULT_CALENDAR ASC"));
if(count($calendars_array))
{
	foreach($calendars_array as $calendar)
		$calendar_options[$calendar['CALENDAR_ID']] = $calendar['TITLE'];
}

if($_REQUEST['student_id']!='new') // && $_REQUEST['servicefunction']!=='delete'
{
	$link['remove']['link'] = SetRequestOptions(null,array('enrollment_id','servicefunction','values')).'&servicefunction=delete';
	$link['remove']['variables'] = array('enrollment_id'=>'ID');

	if(count($array))
		$id = $array[count($array)]['ID'];
	else
		$id = 'new';

//	if($_REQUEST['include']=='Enrollment')
	if($_REQUEST['servicemod']!=='mod_apply/Applicants.php')
		$options['middle'] = CheckBoxOnclick('historical',_('Include Historical Enrollment Records'));

	Gridoutput($array,$columns,_('Enrollment Records'),_('Amount of Enrollment Records'),$link,null,$options);
	$next_school_name = 'values[STUDENT_REGISTRATION]['.$id.'][NEXT_SCHOOL]';
        $ssf_enrollment_code_name = 'values[STUDENT_SPEC_FIELDS]['.$id.'][ENROLLMENT_CODE]';
        $ssf_enrollment_code = '';
	if($id)
		$next_school = $array[count($array)]['NEXT_SCHOOL'];
	$calendar_name = 'values[STUDENT_REGISTRATION]['.$id.'][CALENDAR_ID]';
	if($id)
		$calendar = $array[count($array)]['CALENDAR_ID'];
	$include_in_class_rank = $array[count($array)]['INCLUDE_IN_CLASS_RANK'];
	$include_in_class_rank_name = 'values[STUDENT_REGISTRATION]['.$id.'][INCLUDE_IN_CLASS_RANK]';
	$include_in_classgroup_rank = $array[count($array)]['INCLUDE_IN_GROUP_RANK'];
	$include_in_classgroup_rank_name = 'values[STUDENT_REGISTRATION]['.$id.'][INCLUDE_IN_GROUP_RANK]';
	$div = true;
}
else
{
	$options['sort'] = false;
//	Gridoutput($array,$columns,_('Enrollment Record'),_('Enrollment Records'),$link,array(),array('count'=>false));
	Gridoutput($array,$columns,_('Enrollment Records'),_('Amount of Enrollment Records'),$link,null,$options);
	$next_school_name = 'values[STUDENT_REGISTRATION][new][NEXT_SCHOOL]';
	$next_school = get_school_id();
        $ssf_enrollment_code_name = 'values[STUDENT_SPEC_FIELDS][new][ENROLLMENT_CODE]';
        $ssf_enrollment_code = '';
	$calendar_name = 'values[STUDENT_REGISTRATION][new][CALENDAR_ID]';
	$include_in_class_rank = 'Y';
	$include_in_class_rank_name = 'values[STUDENT_REGISTRATION][new][INCLUDE_IN_CLASS_RANK]';
	$include_in_classgroup_rank = 'Y';
	$include_in_classgroup_rank_name = 'values[STUDENT_REGISTRATION][new][INCLUDE_IN_GROUP_RANK]';
	$div = false;
}
	echo '<TABLE><TR>'.(count($calendars_array)>1?'<TD>'.SelectInput($calendar,$calendar_name,_('School Calendar').' <font color=red>*</font>',$calendar_options,' - '._('Choose').' - ','',$div).'</TD><TD width=30></TD>':'<TD><INPUT type=hidden name='.$calendar_name.' value='.$calendars_array[1]['CALENDAR_ID'].'></TD>').
		'<TD>'.SelectInput($next_school,$next_school_name,_('Rolling Options'),$next_school_options,false,'',$div).'<input type="hidden" name="old_next_school" value="'.$next_school.'"></TD>';//.SelectInput($ssf_enrollment_code,$ssf_enrollment_code_name,_('Wave'),array(''=>_('N/A'),'W1C'=>_('1 Wave'),'W2C'=>_('2 Wave')),false,'',$div)
		if($_REQUEST['servicemod']!=='mod_apply/Applicants.php')
		{
			echo '<TD width=30></TD><TD>'.CheckboxInput($include_in_class_rank,$include_in_class_rank_name,_('Include Student to the Rating in Class'),'',false,_('Yes'),_('No'),$div).'</TD>';
			echo '<TD width=30></TD><TD>'.CheckboxInput($include_in_classgroup_rank,$include_in_classgroup_rank_name,_('Include Student to the Rating in Class Group'),'',false,_('Yes'),_('No'),$div).'</TD>';
		}
		echo '</TR></TABLE>';


function _make_change_school($value,$name)
{
    global $school_array,$SYSTEM,$THIS_array;
    //if(!$school_array)
    {
        $school_array = db_request(db_execute("SELECT ID,TITLE FROM SCHOOLS"),array(),array('ID'));
    }
    $schools = (($_REQUEST['historical']=='Y' || is_applicant()!=='Y')?get_school_array():get_apply_school_array());
    foreach($schools as $index=>$id)
    {
        if($school_array[$id][1]['TITLE']<>'')
            $smas[$id] = $school_array[$id][1]['TITLE'];
    }
    if($_REQUEST['historical']=='Y')
        return NoInput ($school_array[$value][1]['TITLE']);
    else
        return SelectInput($value, 'values[STUDENT_REGISTRATION]['.$THIS_array['ID'].'][SCHOOL_ID]','',$smas);

}
?>