<?php
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;
//die('hh');
/* create an empty incident and add a referral in it */
if($_REQUEST['discipline_report_id'] && $_REQUEST['new_incident'] == true)
{
	$sql = "INSERT INTO STUDENT_DISCIPLINE_INCIDENTS ";
	$fields = 'ID,SCHOOL_YEAR';		
	$values = db_seq_nextval('STUDENT_DISCIPLINE_INCIDENTS_SEQ').",'".get_school_year()."'";
	$sql .= '(' .$fields. ') values(' .$values. ')';
	db_execute($sql);
	$incident_id = db_seq_currval('STUDENT_DISCIPLINE_INCIDENTS_SEQ');

	if($incident_id)
		db_execute("INSERT INTO DISCIPLINE_INCIDENTS_ASG_REPORTS VALUES ('".$incident_id."','".$_REQUEST['studentRefId']."')");
//print_r($incident_id);
	
	unset($_REQUEST['new_incident']);	
	$_REQUEST['servicemod']='mod_discipline/DisIncidentList.php';
	echo '<script>location.href="modloader.php?servicemod=mod_discipline/DisIncidentList.php&incident_id='.$incident_id.'"</script>';
}

require_once($staticpath.'functions/extra/StudentsFunctional.fnc.php');
require_once($staticpath.'functions/extra/ShowIncidentRefer.fnc.php');
require_once($staticpath.'functions/extra/DelIncident.fnc.php');

$existingReff = db_request(db_execute("SELECT * FROM STUDENT_DISCIPLINE_REPORTS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
/*echo "<pre>";
print_r($existingReff);


echo "</pre>";
die('cc');
*/

if($_REQUEST['servicefunction'] == "removeRef")
{
	_removeReferralsFromTheIncident();
}	
else 
{
	if(!$_REQUEST['include'])
		$_REQUEST['include'] = 'stuaddlinfo';
	
	if(!$_REQUEST['category_id'])
		$_REQUEST['category_id'] = 1;
	
	if($_REQUEST['incident_id'] && !UserIncidentID())
	{
		$_SESSION['incident_id'] = $_REQUEST['incident_id'];
		$_REQUEST['search_servicefunction'] = 'list';	
	}	
	
	if($_REQUEST['servicefunction']=='update' && AllowEdit())
	{
		if(is_array($_REQUEST['month_incident']))
		{
			foreach($_REQUEST['month_incident'] as $column=>$value)
			{
				$_REQUEST['incident'][$column] = $_REQUEST['year_incident'][$column].'-'.$_REQUEST['month_incident'][$column].'-'.$_REQUEST['day_incident'][$column];
				if($_REQUEST['incident'][$column]=='--')
					$_REQUEST['incident'][$column] = '';
				elseif(!VerifyDate($_REQUEST['incident'][$column]))
				{
					unset($_REQUEST['incident'][$column]);
					$note = _("The invalid date could not be saved.");
				}
			}
		}
		unset($_REQUEST['day_incident']); unset($_REQUEST['month_incident']); unset($_REQUEST['year_incident']);
		
		if((is_array(count($_REQUEST['incident']) || count($_REQUEST['values']))) && AllowEdit())
        
		{
			//if($_REQUEST['incident_id'] && $_REQUEST['incident_id']!='new')
				//$students_extra = " AND STUDENT_ID!='".$_REQUEST['student_id']."'";
			
			if($_REQUEST['incident_id'] && $_REQUEST['new_incident']!=true)
			{ 
				$go = true;
				if(count($_REQUEST['incident']))
				{
					$date = get_db_date();
					//$user = get_user('USER_ID');
					//$last_updated_sql = "LAST_UPDATED_DATE='{$date}',LAST_UPDATED_USER='{$user}',";
		
					$sql = "UPDATE STUDENT_DISCIPLINE_INCIDENTS SET ";
					
					/* ---------- Edit Rules Block start ---------------*/
					/*
						already, we have this array with the old values. If user changed one of it
						we will add its new value into the array
					*/
					foreach($_REQUEST['incident'] as $column_name=>$value)
					{ 
						$_SESSION['customValues'][$column_name] = $value;
						$fieldId = explode('CFIELD_',$column_name);
						$fieldIdArr[] = $fieldId[1];
					}
					/* 
						now we have the array with field id's, we will use it for search the Edit Rules
					*/
					$resWithEdits = _getAllEditsRules($fieldIdArr, 2);
		
					$border = array();
					$go = true;
					/* check user values using Edits Rules when we try to add a new student */
					$errorArr = _executeEditRulesAndGetMsg($_REQUEST['incident'], 'incident', $resWithEdits);
					/* ---------- Edit Rules Block end ---------------*/
		
					foreach($_REQUEST['incident'] as $column_name=>$value)
					{
						if(!is_array($value))
							$sql .= "$column_name='".str_replace("\'","''",str_replace('``','"',$value))."',";
						else
						{
							$sql .= $column_name."='||";
							foreach($value as $val)
							{
								if($val)
									$sql .= str_replace("\'","''",str_replace('``','"',$val)).'||';
							}
							$sql .= "',";
						}
					}
					
					/*
						if there are some errors, in this part, we will just return $go = false
					*/
					$go = _showErrorWarningMsg($errorArr);
		
					if($_REQUEST['override'] == true AND $_SESSION['overrideDisabled'])	
					{
						/*
							if user click on the 'Override' button, we will unset all
							override error messages and a red border for this field
						*/
						unset($_SESSION['overrideDisabled']);
						unset($errorArr['override_error']);
						unset($forceFieldName);
						unset($border);
						$go = true;
					}
								
					$sql = substr($sql,0,-1) . " WHERE ID='".UserIncidentID()."'";
		
					if($go)
						db_execute($sql);
				}
			}
			else
			{
				/* ---------- Edit Rules Block start ---------------*/
				/* 
				   we need this array, because admin (user) can use in the Edits rule
				   condition with the field name. So, we will make a foreach and will have
				   the required for us values		
				*/
				$_SESSION['customValues'] = _makeInternalArrayWithCustomFields($_REQUEST['incident']);
				/*
					save all user values into the $_SYSTEM
				*/
				_saveStudentEnteredValues($_REQUEST);

				$fieldIdArr = _getIDsForEditRules($_REQUEST['incident'], 'incident');
				/* 
					now we have the array with field id's, we will use it for search the Edit Rules
				*/
				$resWithEdits = _getAllEditsRules($fieldIdArr, 4);
			
				$go = true;
				/* check user values using Edits Rules when we try to add a new student */
				$errorArr = _executeEditRulesAndGetMsg($_REQUEST['incident'], 'incident', $resWithEdits);
				/* ---------- Edit Rules Block end ---------------*/
				
				/*
					we may have the required fields from other categories
				*/
				$required_fields_array = db_request(db_execute("SELECT ID,TITLE,REQUIRED FROM DISCIPLINE_INCIDENT_FIELDS cf LEFT JOIN DISCIPLINE_INCIDENTS_FIELDS_IN_CATS sfjc
									ON sfjc.FIELD_ID = cf.ID AND sfjc.CATEGORY_ID = cf.CATEGORY_ID WHERE TYPE!='radio' AND REQUIRED='Y' OR cf.ID IN (sfjc.FIELD_ID)"));
				foreach($required_fields_array as $field)
				{
					if($field['REQUIRED'])
					{
					
						if(!$_REQUEST['incident']['CFIELD_'.$field['ID']])
						{
							$required_violation++;
							$required_text .= $field['TITLE'].', ';
						}
					}	
				}
				if($required_violation==1)
				{
					$errorArr['err'][] = 'The incident was not added since '.substr($required_text,0,-2).' is a required field. Fill this field and try again.';
					$go = false;
				}
					//BackPrompt(_('The student was not added since').' '.substr($required_text,0,-2).' '._('is a required field. Fix this and try again.'));
				elseif($required_violation)
				{
					$errorArr['err'][] = 'The incident was not added since the following fields are required: '.substr($required_text,0,-2).'. Fill these fields and try again.';
					//BackPrompt(_('The student was not added since the following fields are required:').' '.substr($required_text,0,-2).'. '._('Please fix these fields and try again.'));
					$go = false;
				}
				
				/*
					if there are some errors, in this part, we will just return $go = false,
					but will setup $show as true, because we need to show the additional message
					'The record was not added. Please, correct...' 
				*/
				if(!$go)
				    DisplayHeader(".:".ProgramTitle().":.");
				$go = _showErrorWarningMsg($errorArr,false,true);
				$show = true;
				
				if($_REQUEST['override'] == true AND $_SESSION['overrideDisabled'])	
				{
					unset($_SESSION['overrideDisabled']);
					$go = true;
				}
				
				$sql = "INSERT INTO STUDENT_DISCIPLINE_INCIDENTS ";
				$fields = 'ID,SCHOOL_YEAR,';		
				
				$values = db_seq_nextval('STUDENT_DISCIPLINE_INCIDENTS_SEQ').",'".get_school_year()."',";
		
				foreach($_REQUEST['incident'] as $column=>$value)
				{
					if($value)
					{
						$fields .= $column.',';
						if(!is_array($value))
							$values .= "'".str_replace("\'","''",$value)."',";
						else
						{
							$values .= "'||";
							foreach($value as $val)
							{
								if($val)
									$values .= $val.'||';
							}
							$values .= "',";
						}
					}
				}
				$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
				
				if($go)
				{
					db_execute($sql);

					$incident_id = db_seq_currval('STUDENT_DISCIPLINE_INCIDENTS_SEQ');

					//save the referrals
					if($_REQUEST['student'])
					{	
						foreach($_REQUEST['student'] as $ref_id_key => $value)
						{
							$refSql = "INSERT INTO DISCIPLINE_INCIDENTS_ASG_REPORTS VALUES ('".$incident_id."','".$ref_id_key."')";
							db_execute($refSql);
						}
					}
				}	
				$_REQUEST['incident_id'] = $incident_id;
				$_SESSION['incident_id'] = $incident_id;	
					
				/*if(Preferences('DEFAULT_TAB')!=1)
				{
					$_REQUEST['include'] = 'Other_Info';
					$_REQUEST['category_id'] = $_REQUEST['category_id'];
				}*/
			}
		}
		
		unset($_REQUEST['servicefunction']);
		// SHOULD THIS BE HERE???
		if(!UserIncidentID())
			unset($_REQUEST['incident']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['values']);
	}
	
	
	if($_REQUEST['new_incident']==true)
	{
		unset($_SESSION['incident_id']);
                if(!isset($_REQUEST['search_servicefunction']))
		$_REQUEST['search_servicefunction'] = 'list';
		// So the HeaderIcon is set
		ProgramTitle();
		DisplayHeader(".:"._('Add an Incident').":.");
	}
	elseif(!$errorArr) // if($_REQUEST['servicefunction'] != 'add_incident_ref')
		DisplayHeader(".:".ProgramTitle().":.");
	
	if(!UserIncidentID() && $_REQUEST['new_incident'] != true && !$_REQUEST['incident_id'])
	{
		unset($_SESSION['List_PHP_SELF']);
		unset($_SESSION['student_id']);
		unset($_SESSION['user_id']);
		Widgets('all');
		$addition['options']['wrap'] = true;
		Search('incident_id',$addition);
	}
	
	
	if((UserIncidentID() || $_REQUEST['new_incident']==true) && !$_REQUEST['delete_ok'] && ($_REQUEST['servicefunction'] != 'add_incident_ref'))
	{
		if($_REQUEST['servicefunction']!='delete' || $_REQUEST['delete_ok']=='1')
		{
			if($_REQUEST['new_incident']!=true)
			{
		//			if($_REQUEST['include']!='Comments')
		//				DrawStudentHeader();
				echo "<FORM name=incident action=modloader.php?servicemod=$_REQUEST[servicemod]&include=$_REQUEST[include]&incident_id=".UserIncidentID()."&category_id=$_REQUEST[category_id]&useontop=$_REQUEST[useontop]&GridOutputCount=".$_REQUEST['GridOutputCount']."&servicefunction=update id=incident method=POST>";
			}
			else
				echo "<FORM name=incident id=incident action=modloader.php?servicemod=mod_discipline/DisIncidentList.php&include=$_REQUEST[include]&category_id=$_REQUEST[category_id]&GridOutputCount=".$_REQUEST['GridOutputCount']."&servicefunction=update method=POST>";
		
			if($errorArr['override_error'])
			{
				if(!$errorArr['err'])
				{
					$overrideDisabled = '';
					$_SESSION['overrideDisabled'] = true;
				}
				else 
					$overrideDisabled = 'DISABLED';
		
				$override_button = '<INPUT type=button value='._('Override').' '.$overrideDisabled.' onclick="checkOverride(\'student\');"> &nbsp; ';
			}
			
			if(UserIncidentID() && get_user('PROFILE')=='admin')
				$delete_button = '<INPUT style="width:100px;" type=button value='._('Delete').' onclick="window.location=\'modloader.php?servicemod='.$_REQUEST['servicemod'].'&incident_id='.UserIncidentID().'&servicefunction=delete\'"> &nbsp; &nbsp;';
	
			//if(($existingReff && $_REQUEST['new_incident']==true) || (UserIncidentID()))	
			//{
			echo $name;
				if(!$_REQUEST['CREATEPDF'])
					DisplayHeader($name,$override_button.$delete_button.$submitButton->createSButton(_('Save')));//1
			//}		
			/*
				if there are some errors, we will show them
			*/
			 _showErrorWarningMsg($errorArr, $show, true);	
			 
			if(get_user('PROFILE')=='admin' || true)
			{
				if(is_numeric(get_user('PROFILE_ID')))
				{
					$can_use_array = db_request(db_execute("SELECT MODNAME FROM PROFILE_SETTINGS WHERE PROFILE_ID='".get_user('PROFILE_ID')."' AND VIEWER='N'"),array(),array('MODNAME'));
				}
				else
					$can_use_array = db_request(db_execute("SELECT MODNAME FROM USER_SETTINGS WHERE USERNAME='".get_user('USERNAME')."' AND VIEWER='N'"),array(),array('MODNAME'));
			}
		
			$categories_array = db_request(db_execute("SELECT ID,TITLE FROM DISCIPLINE_INCIDENT_CATEGORIES ORDER BY SORT_ORDER,TITLE"));
			
			$first_category = $categories_array[1];
			foreach($categories_array as $category)
			{
				if(!$can_use_array['mod_discipline/DisIncidentList.php&category_id='.$category['ID']])
					$tabs[] = array('title'=>$category['TITLE'],'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&include=stuaddlinfo&category_id=".$category['ID']."&GridOutputCount=".$_REQUEST['GridOutputCount']."&incident_id=".$_REQUEST['incident_id']);
			}

			$_SYSTEM['selected_tab'] = "modloader.php?servicemod=$_REQUEST[servicemod]&include=$_REQUEST[include]";
			
			if($_REQUEST['category_id'])
				$_SYSTEM['selected_tab'] .= '&category_id='.$_REQUEST['category_id']."&GridOutputCount=".$_REQUEST['GridOutputCount']."&incident_id=".$_REQUEST['incident_id'];
		
			echo '<BR>';
			
			if(Preferences('MENU')=='Top')
				$width = 'width=95%';
			else
				$width = 'width=99%';
			
			if($_REQUEST['new_incident']==true)
				$tabs = false;
			
			if($_REQUEST['include']=='Comments')
				$tabs = _('Comments');
			
			//($existingReff || $_REQUEST['new_incident']!=true)	
			if($_REQUEST['servicefunction'] != 'add_incident_ref')
			{
				echo PopTable('header',$tabs,$width,0);
				
				/*
					will display the Title in the first category. This field will be used on the 
					search screen
				
				if($_REQUEST['category_id'] == $first_category['ID'])
				{
					if($_REQUEST['new_incident']==true)
						$div = '';
					else 
					{
						$incidentTitle = db_request(db_execute("SELECT TITLE FROM STUDENT_DISCIPLINE_INCIDENTS WHERE ID='".UserIncidentID()."'"));
						$div = 'force';	
					}
					echo '<TABLE cellpadding="10" border="0" width="300px"; style="padding:20px 0px 0px 210px;"><TR>';
					echo '<TD align="left">';
					echo TextInput($incidentTitle[1]['TITLE'],'incident[TITLE]',_('Title'),'size=30',$div);
					echo '</TD></TR></TABLE>';
				}
				*/	
				include($staticpath.'modules/mod_students/includes/'.$_REQUEST['include'].'.inc.php');
			
				if($_REQUEST['new_incident']!=true && UserIncidentID())
					echo '<DIV align="center">'."<A HREF=# onclick='window.open(\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=add_incident_ref&incident_id=$_REQUEST[incident_id]&useontop=false\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'><DIV id=choose_course_div>"._('Add a Rule-breaker')."</DIV></A></DIV>";
			
				//show the referrals block
				//_showIncidentReferrals($_REQUEST['new_incident']);
                                if($_REQUEST['new_incident']==123)
                                {
                                $addition['SELECT'] = ",s.STUDENT_ID AS CHECKBOX";
                                $addition['functions'] = array('CHECKBOX'=>'_makeChooseCheckboxStud');
                                $addition['columns_before'] = array('CHECKBOX'=>'</A><INPUT type=checkbox value=Y name=controller onclick="checkAll(this.form,this.form.controller.checked,\'student\');CheckAll_hilite(this.form,this.form.controller.checked,\'student\')"><A>');
                                $addition['new'] = true;
                                $addition['options']['onclick']="check_clicked(this);";
                                Search('student_id',$addition);
                                }
                                else
                                    _showIncidentReferrals($_REQUEST['new_incident']);
			
				echo '<BR><CENTER>'.$submitButton->createSButton(_('Save')).'</CENTER>';//2
				echo PopTable('footer');
				echo '</FORM>';
			}
			/*elseif(!$existingReff && $_REQUEST['new_incident']==true && $_REQUEST['servicefunction'] != 'add_incident_ref')
			{
				$message = '<IMG SRC=assets/x.gif> '._('Please, choose at least one referral.').'<BR><BR>';
				DisplayBlock('',$message);
			}*/
		} 
		else
			include($staticpath.'modules/mod_students/includes/stuaddlinfo.inc.php');
	}
	elseif($_REQUEST['servicefunction'] == 'add_incident_ref' && UserIncidentID())
	{
		if(!$_REQUEST['refAdded'])
		{
			if($_REQUEST['search_servicefunction']!='search')
			{
				echo "<FORM name=incident action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=add_incident_ref&incident_id=$_REQUEST[incident_id]&refAdded=true id=incident method=POST>";
				DisplayHeader(null,'<INPUT type="submit" value="'._('Add Student(s) to the List of Discipline Incidents').'">');
			}
			_showIncidentReferrals(true, true);

			if($_REQUEST['search_servicefunction']!='search')
			{
				echo '<DIV align="center"><INPUT type="submit" value="'._('Add Student(s) to the List of Discipline Incidents').'"></DIV>';
				echo '</FORM>';
			}
		}
		else 
		{	
			//save the referrals
			if($_REQUEST['student'])
			{	
				foreach($_REQUEST['student'] as $ref_id_key => $value)
				{ 
					$refSql = "INSERT INTO DISCIPLINE_INCIDENTS_ASG_REPORTS VALUES ('".UserIncidentID()."','".$ref_id_key."')";
					db_execute($refSql);
				}
			}
		
			unset($_REQUEST['servicefunction']);	
			
			//echo "<script language=javascript>opener.document.location.reload();";
			echo "<script language=javascript>opener.document.location.href='modloader.php?servicemod=mod_discipline/DisIncidentList.php&incident_id=$_REQUEST[incident_id]';";
			echo "window.close();</script>";
		}
	}
	
	
	if($_REQUEST['servicefunction']=='delete' && basename($_SERVER['PHP_SELF'])!='index.php' && AllowEdit() && UserIncidentID())
	{
		if(DeletePrompt(_('incident')))
		{
			db_execute("DELETE FROM STUDENT_DISCIPLINE_INCIDENTS WHERE ID='".UserIncidentID()."'");
			db_execute("DELETE FROM DISCIPLINE_INCIDENTS_ASG_REPORTS WHERE INCIDENT_ID='".UserIncidentID()."'");
		
			unset($_SESSION['incident_id']);
			unset($_REQUEST);
			
			if(Preferences('MENU')=='Side')
				echo '<script language=JavaScript>parent.side.location="'.$_SESSION['Side_PHP_SELF'].'?modcat="+parent.side.document.forms[0].modcat.value;</script>';
			
			Widgets('all');
			$addition['options']['wrap'] = true;
			Search('incident_id',$addition);
		}
	}
}
function _makeChooseCheckboxStud($value,$title)
{	global $THIS_array;
	return "<INPUT onchange='hl_cb(this)' type=checkbox name=student[".$THIS_array['STUDENT_ID']."] value=Y>";
}
?>