<?php

// This report doesn't take into consideration days of the week correctly.  It should use the _conflictingDays() function at the bottom of the report.
// This limitation only affects schools with lots of courses that don't meet all week

if($_REQUEST['month_date'] && $_REQUEST['day_date'] && $_REQUEST['year_date'])
{
	while(!VerifyDate($effective_date = $_REQUEST['year_date'].'-'.$_REQUEST['month_date'].'-'.$_REQUEST['day_date']))
		$_REQUEST['day_date']--;
}
else
{
	$effective_date = db_request(db_execute("SELECT min(SCHOOL_DATE) AS START_DATE FROM SCHOOL_CALENDAR_DAYS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
	$effective_date = $effective_date[1]['START_DATE'];
	if(!$effective_date || get_db_date('postgres')>$effective_date)
		$effective_date = get_db_date();
}

DisplayHeader(".:".ProgramTitle().":.");
Widgets('all');
$addition['new'] = true;

if($_REQUEST['search_servicefunction']!='list')
	Search('student_id',$addition);
elseif($_REQUEST['search_servicefunction']=='list')
{
	echo '<FORM>';
	$_SYSTEM['ereg_replace'] = false; // because the '' in the replace() statements was converted to NULL
	
	if($_REQUEST['_search_all_schools']=='Y' && get_user('SCHOOLS'))
	{
		$schools_extra = " AND SCHOOL_ID IN ('".str_replace(',',"','",substr(get_user('SCHOOLS'),1,-1))."')";
		$periods_array = db_request(db_execute("SELECT DISTINCT SHORT_NAME,SHORT_NAME AS ORIG_SHORT_NAME,TITLE,BLOCK FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' ".$schools_extra." ORDER BY 1"),array('SHORT_NAME'=>'_replaceNonAlphaNumeric'));
	}
	elseif($_REQUEST['_search_all_schools']!='Y')
	{
		$schools_extra = " AND SCHOOL_ID='".get_school_id()."'";
		$periods_array = db_request(db_execute("SELECT SHORT_NAME,SHORT_NAME AS ORIG_SHORT_NAME,TITLE,BLOCK FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' ".$schools_extra." ORDER BY SORT_ORDER"),array('SHORT_NAME'=>'_replaceNonAlphaNumeric'));
	}
	else 	// if _search_all_schools is Y, but the user has no schools, that means the user can access every school, so we don't need to add a schools_extra
		$periods_array = db_request(db_execute("SELECT DISTINCT SHORT_NAME,SHORT_NAME AS ORIG_SHORT_NAME,TITLE,BLOCK FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' ORDER BY SHORT_NAME"),array('SHORT_NAME'=>'_replaceNonAlphaNumeric'));
	
	$all_periods_array = db_request(db_execute("SELECT SHORT_NAME,SCHOOL_ID,TITLE,BLOCK FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' ".$schools_extra." ORDER BY SHORT_NAME"),null,array('SCHOOL_ID','SHORT_NAME'));
/*
	foreach($periods_array as $period)
	{
		if($period['BLOCK'])
			$periods_w_blocks = true;
		else
		{
			$periods_wo_blocks = true;
			if(!$wo_example)
				$wo_example = $period['ORIG_SHORT_NAME'];
		}
	}

	if($periods_w_blocks && $periods_wo_blocks)
		$blocks_message = '<BR><BR>'.sprintf(_('Uncheck periods without blocks (example, %s) in the "Periods in the School Day" section below.  These periods are automatically counted in all similar periods that have a block (example, %sA and %sB).'),$wo_example,$wo_example,$wo_example);
*/

	DisplayHeader('<div style="width:900px;">'._('"Conflicting Schedules List" is a type of conflict report when there are students with two sections scheduled into any period in their timetable.Sections which don\'t take attendance are not included. If some periods allow students to be enrolled in two sections, you can exclude periods by unchecking them below. You can click the student\'s name to view or modify his or her schedule.').$blocks_message.'<BR><BR></div>');
	$left = '<BR><B>'._('Effective Date').': </B>'.PrepareDate($effective_date,'_date',false,array('submit'=>true)).' &nbsp; &nbsp;  &nbsp; &nbsp; <B>'._('School Term').'</B>: '.get_school_term(get_user_school_term());
	DisplayHeader($left);
	
	echo '<BR><CENTER><TABLE cellspacing=0 width=65%><TR><TD colspan=2 background=themes/'.Preferences('HIGHLIGHT_FRAME').'/bottom_shadow.png height=20 width=200><B>'._('Periods in the School Day:').'</B></TD>';

	if($_REQUEST['_search_all_schools']=='Y')
		$curr_school = 'all';
	else
		$curr_school = get_school_id();

	$custom = false;
	foreach($periods_array as $period)
	{
		if($_REQUEST['period_'.$period['SHORT_NAME']])
		{
			$custom = true;
			$custom_periods['period_'.$period['SHORT_NAME']] = 'Y';
		}
	}
	
	if(!$custom)
	{
		if(Preferences('MULTI_CHECKBOX_PERIODS_IN_DAY_SHORT_NAME'.$curr_school,'Schedule'))
		{
			$_REQUEST += unserialize(Preferences('MULTI_CHECKBOX_PERIODS_IN_DAY_SHORT_NAME'.$curr_school,'Schedule'));
		}
		else
		{
			foreach($periods_array as $period)
				$_REQUEST['period_'.$period['SHORT_NAME']] = 'Y';
		}
	}
	else
	{
		$_SYSTEM['ereg_replace'] = true;
		SetPreference('MULTI_CHECKBOX_PERIODS_IN_DAY_SHORT_NAME'.$curr_school,'Schedule',serialize($custom_periods));
		$_SYSTEM['ereg_replace'] = false;
	}
	
	if(count($periods_array))
	{
		foreach($periods_array as $period)
		{
			echo '<TD colspan=2 background=themes/'.Preferences('HIGHLIGHT_FRAME').'/bottom_shadow.png height=20>'.CheckBoxOnclick('period_'.$period['SHORT_NAME'],$period['ORIG_SHORT_NAME']).'</TD>';
			if($_REQUEST['period_'.$period['SHORT_NAME']]=='Y')
				$periods_extra .= ",'".$period['ORIG_SHORT_NAME']."'";
	
		}
		if($periods_extra)
			$periods_extra = ' AND sp.SHORT_NAME IN ('.substr($periods_extra,1).') ';
	}
	
	echo '</TR></TABLE></CENTER><BR>';
	echo '</FORM>';
	
	$schedule_extra = $addition;
	$schedule_extra['DATE'] = $effective_date;
	$schedule_extra['SELECT_ONLY'] = 'sp.SHORT_NAME AS PERIOD_SHORT_NAME,s.STUDENT_ID,cp.DAYS,ssm.SCHOOL_ID';
	if(SystemPreferences('ODD_EVEN_WEEKS','system') == 'Y')
	{
		$schedule_extra['SELECT_ONLY'] .= ',cp.WEEK';
		$gweek = 'cp.WEEK,';
	}
	$schedule_extra['FROM'] .= ',SCHOOL_PERIODS sp,STUDENT_SCHEDULE ss,COURSE_SECTIONS cp';
	$schedule_extra['WHERE'] .= ' AND cp.DOES_ATTENDANCE=\'Y\' AND (\''.$effective_date.'\' BETWEEN ss.START_DATE AND ss.END_DATE OR (ss.END_DATE IS NULL AND \''.$effective_date.'\'>=ss.START_DATE)) 
				    AND ss.SCHOOL_ID=ssm.SCHOOL_ID AND ss.SCHOOL_TERM_ID IN ('.get_all_school_term('QTR',get_user_school_term()).') AND ss.STUDENT_ID=ssm.STUDENT_ID 
				    AND ss.SCHOOL_YEAR=ssm.SCHOOL_YEAR AND ss.COURSE_SECTION_ID=cp.COURSE_SECTION_ID AND cp.SCHOOL_PERIOD_ID=sp.SCHOOL_PERIOD_ID ';
	$schedule_extra['GROUP'] = 's.STUDENT_ID,ssm.SCHOOL_ID,cp.DAYS,'.$gweek.'sp.SHORT_NAME HAVING COUNT(*)>1';
	$schedule_extra['group'] = array('STUDENT_ID','PERIOD_SHORT_NAME');
	$schedule_extra['new'] = true;
	
	$schedule_array = get_student_list($schedule_extra);
	unset($_SYSTEM['ereg_replace']);

	$addition['DATE'] = $effective_date;
	
	if($_REQUEST['_search_all_schools']=='Y')
		$addition['columns_after']['LIST_SCHOOL_ID'] = _('School');
	
	foreach($periods_array as $period)
	{
		if($_REQUEST['period_'.$period['SHORT_NAME']]=='Y')
		{
			$addition['SELECT'] .= ',NULL AS PERIOD_'.$period['SHORT_NAME'];
			$addition['columns_after']['PERIOD_'.$period['SHORT_NAME']] = $period['TITLE'];
			$addition['functions']['PERIOD_'.$period['SHORT_NAME']] = '_preparePeriods';
		}
	}

	$singular = _('Students with conflicting schedules');
	$plural = _('Amount of Students with conflicting schedules');

	if(!is_array($addition['columns_after']))
		$addition['columns_after'] = array();
	$link['FULL_NAME']['link'] = "modloader.php?servicemod=mod_curriculum/Curriculum.php&useontop=false";
	$link['FULL_NAME']['variables'] = array('GridOutputCount'=>'index','student_id'=>'STUDENT_ID');
	$link['FULL_NAME']['js'] = true;
	$addition['GridOutputCount'] = true;
	$addition['dont_print_array'] = true;

	$students_array = Search('student_id',$addition);

	$i = 0;
	$_SESSION['student_list'] = array();
	foreach($students_array as $student)
	{
		foreach($periods_array as $period)
		{
			if($_REQUEST['period_'.$period['SHORT_NAME']])
			{
				if($_REQUEST['_search_all_schools']!='Y' || $all_periods_array[$student['SCHOOL_ID']][$period['ORIG_SHORT_NAME']])
				{
					if($schedule_array[$student['STUDENT_ID']][$period['ORIG_SHORT_NAME']] && _daysConflict($schedule_array[$student['STUDENT_ID']][$period['ORIG_SHORT_NAME']]))
					{
						$i++;
						$student['index'] = $i;
						$bad_students[$i] = $student;
						$_SESSION['student_list'][] = array('student_id'=>$student['STUDENT_ID'],'school_id'=>get_school_id());
						continue 2;
					}
				}
			}
		}
		//if(count($schedule_array[$student['STUDENT_ID']])!=count($periods_array))
		//	$bad_students[] = $student;
	}

	echo '<BR>';
	Gridoutput($bad_students,array('FULL_NAME'=>_('Student Name'),'STUDENT_ID'=>_('ID number'),'CLASSLEVEL_ID'=>_('Class Level'))+$addition['columns_after'],$singular,$plural,$link);
}

function _preparePeriods($value,$name)
{	global $THIS_array,$schedule_array,$periods_w_blocks,$periods_wo_blocks,$periods_array;

	$period_sn = substr($name,7);
	foreach($periods_array as $period)
	{
		if($period_sn==ereg_replace('[^A-Za-z0-9_]','',$period['SHORT_NAME']))
		{
			$school_period_id = $period['ORIG_SHORT_NAME'];
			break;
		}
	}
//	echo var_dump($schedule_array[$THIS_array['STUDENT_ID']][$school_period_id])."<br>";
	if($schedule_array[$THIS_array['STUDENT_ID']][$school_period_id] && _daysConflict($schedule_array[$THIS_array['STUDENT_ID']][$school_period_id]))
		return '<IMG SRC=images/x.gif>';
	else
		return '';
}

function _daysConflict($sections)
{
	// this function doesn't work since $schedules_array doesn't contain the section info.
	//return true;
	$days_conflict = false;
//var_dump($sections);
	for($o=1;$o<count($sections);$o++)
	{
		for($i=$o+1;$i<=count($sections);$i++)
		{
//		echo strlen($sections[$o]['DAYS'])."-".strlen($sections[$i]['DAYS']);
			if(strlen($sections[$o]['DAYS'])+strlen($sections[$i]['DAYS'])>21)
				$days_conflict = true;
			else
			{
				$days_len = strlen($sections[$o]['DAYS']);
				for($c=0;$i<$days_len;$c=+3)
				{
//				echo $c;
					if(strpos($sections[$i]['DAYS'],substr($sections[$o]['DAYS'],$c,3))!==false)
					{
//					echo substr($sections[$o]['DAYS'],$c,3);
						$days_conflict = true;
						break;
					}
				}
			}
		}
	}
	if($days_conflict)
		return true;
}

function _replaceNonAlphaNumeric($value,$name)
{
	return ereg_replace('[^A-Za-z0-9_]','_',$value);
}
?>