<?php

// THIS PROGRAM RELIES ON fckEditor
//	- editor/dialog/fck_template.php

if($_REQUEST['servicemod']=='mod_users/UsrLetterWorkspace.php')
{
	//	$custom_fields_table = 'USER_FIELDS';
	//	$categories_table = 'USER_FIELD_CATEGORIES';
	$students_table = 'USERS';
	$student_id_field = 'USER_ID';
	$log_student_id_field = 'USER_ID';
	
	$singular = _('Users');
	$plural = _('Amount of Users');
	$search_function_parameter = 'user_id';
	$get_student_list = 'get_user_list';
	
	$get_student_id = get_user_id();
	$log_table = 'USER_LF_DATA';
	//	$student_field_id_field = 'USER_FIELD_ID';
	$html_field_title = 'user';
	$singular_student_field = _('user field');
	$_SESSION['user_search'] = true;
	$email_field = 'CFIELD_40001';
}
else
{
	//$custom_fields_table = 'STUDENT_FIELDS';
	//$categories_table = 'STUDENT_FIELD_CATEGORIES';
	$students_table = 'STUDENTS';
	$student_id_field = 'STUDENT_ID';
	$log_student_id_field = 'STUDENT_ID';
	
	$singular = _('Students');
	$plural = _('Amount of Students');
	$search_function_parameter = 'student_id';
	$get_student_list = 'get_student_list';
	
	$get_student_id = get_student_id();
	$log_table = 'STUDENT_LF_DATA';
	$student_field_id_field = 'STUDENT_FIELD_ID';
	$html_field_title = 'students';
	$singular_student_field = _('student field');
	$_SESSION['user_search'] = false;
	$email_field = 'CFIELD_50012';
}

function _makeName($value,$name)
{
	global $_SYSTEM, $THIS_array;

	if($_SYSTEM['options']['STUDENT_ID'][$value])
		return $_SYSTEM['options']['STUDENT_ID'][$value];
}

function _makeget_user($value,$name)
{
	global $_SYSTEM;
	
	if($_SYSTEM['options']['USER_ID'][$value])
		return $_SYSTEM['options']['USER_ID'][$value];
	else 
		return "";
}

function _makeTemplate($tid, $name)
{
	global $_SYSTEM;
	
	if($_SYSTEM['options']['LETTER_ID'][$tid])
		return $_SYSTEM['options']['LETTER_ID'][$tid];	
}

function _makeChooseCheckbox1($value,$title='')
{	global $THIS_array, $html_field_name;

	$student_id_field="LETTER_ID";
	
	return "<INPUT onchange='hl_cb(this)' type=checkbox name=".$html_field_name."[".$THIS_array[$student_id_field]."] value=Y>";
}

$html_field_name="letterid";

if(!$_REQUEST['servicefunction'])
{
	DisplayHeader(".:".ProgramTitle().":.");
	
	Widgets('document_template');
	Widgets('all');
	
	echo "<style>.hilite{background-color:".Preferences('ROLLOVER_HIGHLIGHT').";}</style>";
	echo "<script>";
	echo "function hilite_checked(cb, row){if(cb.checked){row.className+=' hilite'}else{row.className=row.className.replace(/hilite/g,'')};}; function check_clicked(row){var cb=row.firstChild.firstChild; cb.checked=!cb.checked; hilite_checked(cb, row); }; function CheckAll_hilite(form,value,name_like){for(i=0;i<form.elements.length;i++){	if(form.elements[i].type=='checkbox' && form.elements[i].name!='controller' && form.elements[i].name.substr(0,name_like.length)==name_like){hilite_checked(form.elements[i], form.elements[i].parentNode.parentNode);}}}";
	echo "function checkAll(form,value,name_like){if(value==true)checked = true;else checked = false;for(i=0;i<form.elements.length;i++){if(form.elements[i].type=='checkbox' && form.elements[i].name!='controller' && form.elements[i].name.substr(0,name_like.length)==name_like)form.elements[i].checked = checked;}}";
	echo "</script>";

	echo "<FORM name=letters_form action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=save&include_inactive=$_REQUEST[include_inactive]&_search_all_schools=$_REQUEST[_search_all_schools]&search_servicefunction=list&CREATEPDF=true&_template_id=$_REQUEST[_template_id] method=POST>";

	$buttons = '<INPUT TYPE=button value="'._('Preview').'" onclick="this.form.target=\'_blank\';this.form.preview.value=\'true\';this.form.submit();">'.' &nbsp; <INPUT type=submit value="'._('Print Without Adding Log Entries').'" id="top_submit_button" onclick="this.form.target=\'\';this.form.preview.value=\'false\';"">'.' &nbsp; <INPUT type=submit name=printandlog value="'._("Print Letters & Add Log Entries").'" id="top_submit_button_1" onclick="this.form.target=\'\';this.form.preview.value=\'false\';"">';

	DisplayHeader('', $buttons);
	
	echo '<INPUT type=hidden name=preview value="false">';
	
	$students_array = db_request(db_execute("SELECT STUDENT_ID,LAST_NAME,FIRST_NAME FROM STUDENTS"));
	foreach($students_array as $student)
		$_SYSTEM['options']['STUDENT_ID'][$student['STUDENT_ID']] = $student['LAST_NAME']." ".$student['FIRST_NAME'];
	
	$users_array = db_request(db_execute("SELECT USER_ID,LAST_NAME,FIRST_NAME FROM USERS"));
	foreach($users_array as $user)
		$_SYSTEM['options']['USER_ID'][$user['USER_ID']] = $user['LAST_NAME']." ".$user['FIRST_NAME'];
	
	$letters_array = db_request(db_execute("SELECT ID,TITLE FROM STUDENT_EMAILS"));
	foreach($letters_array as $letter)
		$_SYSTEM['options']['LETTER_ID'][$letter['ID']] = $letter['TITLE'];
	
	$group = array();
	$functions = array('CHECKBOX'=>'_makeChooseCheckbox1', "SID"=>"_makeName", "USER_ADDED"=>"_makeUser", "USER_PRINTED"=>"_makeUser", "TEMPLATE_ID"=>"_makeTemplate");
	
	$sections_array = db_request(db_execute("SELECT '' as CHECKBOX,LETTER_ID,SID,STYPE,TEMPLATE_ID,DT_ADDED,USER_ADDED,DT_PRINTED,USER_PRINTED FROM STUDENT_EMAILS_ORDER WHERE STYPE=1 AND DT_PRINTED IS NULL"), $functions, $group);//,$functions,$group);
	$columns = array(/**/'CHECKBOX'=>'</A><INPUT type=checkbox value=Y name=controller onclick="checkAll(this.form,this.checked,\''.$html_field_name.'\');CheckAll_hilite(this.form,this.form.controller.checked,\''.$html_field_name.'\');"><A>', /**/ 'SID'=>_('Recipient'), 'TEMPLATE_ID'=>_('Letter Template'), 'DT_ADDED'=>_('Added'), 'USER_ADDED'=>_('Added By'));

	$addition['onclick']="check_clicked(this);";
	
	Gridoutput($sections_array, $columns, '', '', false, false, $addition);

	DisplayHeader('', $buttons);
	
	echo "</FORM>";
}
else
{
	if(count($_REQUEST[$html_field_name]))
	{
		$to_address = $_REQUEST['to_address'] = 'student';
		$letter_log_students = array();
		$letters = $_REQUEST[$html_field_name];
		
		if($to_address=='student' && $_REQUEST['preview']!='true')
			$handle = PDFStart();
		else
		{
			Basic('header');
			echo "<BODY marginwidth=0 leftmargin=0 topmargin=$topmargin border=0 onload='doOnload();' onclick='doOnBodyClick();' ".($_REQUEST['servicemod']=='mod_savedinfo/Equations.php'?'onkeypress="doOnKeyPress(window.event.keyCode);" ':'').'>';
		}
	
		//-- Loop through letters
		foreach($letters as $k=>$v)
		{
			//-- Getting letter data from database
			$letter_id = addslashes($k);
			$result = db_request(db_execute("SELECT * FROM STUDENT_EMAILS_ORDER WHERE LETTER_ID={$letter_id} LIMIT 1"));
			$template_id = $result[1]['TEMPLATE_ID'];
			$student_id = $result[1]['SID'];
			
			//looking for fields
			$letter_text_temp = GetLetterTemplateText($template_id);
			while(ereg('<_field\[([^]]+)\] />',$letter_text_temp,$regs))
			{
				$_REQUEST['fields'][$regs[1]] = true;
				$letter_text_temp = str_replace($regs[0],'',$letter_text_temp);
				$count++;
			}

			$addition['WHERE'] = " AND s.".$student_id_field." IN ($student_id)";
					
			switch($to_address) //to address goes here
			{
				case 'student':
					$_REQUEST['fields']['MAIL_ADDRESS'] = true;
					break;
				
				case 'family':
					$_REQUEST['fields']['MAIL_ADDRESS'] = true;
					$addition['group'] = 'ADDRESS_ID';
					break;
			}
			
			$addition['dont_print_array'] = true;
			$_REQUEST['search_servicefunction'] = 'list';
			$_REQUEST['Gridoutput_store'] = true;
			$addition['functions'] = array(
				'NEXT_SCHOOL'=>'_makeNextSchool',
				'CALENDAR_ID'=>'_makeCalendar',
				'SCHOOL_ID'=>'get_school',
				'PARENTS'=>'makeParents',
				'START_DATE'=>'ProperDate',
				'END_DATE'=>'ProperDate',
				'ENROLLMENT_CODE'=>'_getRegistrationCode',
				'DROP_CODE'=>'_getRegistrationCode',
				'CONTACT_INFO'=>'makeContactInfo',
				'MAILTO_LABEL'=>'MailToLabel',
				'CLASSLEVEL_ID'=>'get_classlevel');
			
			foreach($_REQUEST['fields'] as $column=>$true)
			{
				if(strpos($addition['SELECT'],$column)===false && substr($column,0,7)!='CFIELD_' && !in_array($column,array('FIRST_NAME','LAST_NAME','MIDDLE_NAME','ADDRESS','CITY','STATE','ZIPCODE',$student_id_field,'CLASSLEVEL_ID','SCHOOL_ID','START_DATE','DROP_CODE','END_DATE','DATE_ENTERED','MAILTO_LABEL','FULL_NAME')))
					$addition['SELECT'] .= ',NULL AS '.ereg_replace('[^A-Za-z_0-9]','',$column);
			}
			
			if($_REQUEST['fields'])
			{
				if($students_table=='USERS')
				{
					$_SYSTEM['user_search'] = true;
					$_REQUEST['users_search_servicefunction'] = 'list';
				}
				
				include($staticpath.'modules/mod_portal/ExternalLinker.php');

				//need to unset these variables to avoid DB errors
				unset($addition);
				unset($_REQUEST['fields_order']);
				
				if($to_address=='family')
				{
					$array_old = $array;
					$array = array(0=>false);
					foreach($array_old as $address_id=>$students)
					{
						$count_students = count($students);
						if($count_students > 1)
						{
							for($i=2;$i<=$count_students;$i++)
							{
								$students[1]['FIRST_NAME'] .= ' & ' . $students[$i]['FIRST_NAME'];
								$students[1]['LAST_NAME'] .= ' & ' . $students[$i]['LAST_NAME'];
								$students[1]['FULL_NAME'] .= ' & ' . $students[$i]['FULL_NAME'];
							}
						}
						$array[] = $students[1];
					}
					unset($array[0]);
				}
			}
			
			$student_points = $total_points = 0;
			unset($_SYSTEM['DisplayHeader']);
			DisplayHeader('');
			
			$letter_log = false;
			$letter_log_recipient = "";
		
			//-- Store the template
			$letter_text_template = $letter_text;
			
			//-- Loop through all student addresses
			foreach($array as $student)
			{
				$letter_text = $letter_text_template;
				
				foreach($_REQUEST['fields'] as $column=>$true)
					$letter_text = str_replace('<_field['.$column.'] />',$student[$column],$letter_text);
				
				if(get_user('EMAIL'))
					$from_address = get_user('EMAIL');
				else
					$from_address = $_Mail['from'];
				if(get_user('PROFILE')=='teacher' || get_user('PROFILE')=='admin')
					$from_name = get_user('NAME').' - '.$GeneralTitle;
				else
					$from_name = get_school(get_school_id());
				
				//-- Printing letters or preview	
				if($_REQUEST['preview']=='true')
				{
					switch($to_address)
					{
						case 'student':
						case 'family':
							echo $letter_text;
							DrawTemplateHeaders($student_id,'footer');
							echo '<!-- NEW PAGE -->';
							break;
					}				
				}
				else
				{
					switch($to_address)
					{
						case 'family':
						case 'student':
							echo $letter_text;
							DrawTemplateHeaders($student_id,'footer');
							echo '<!-- NEW PAGE -->';
							$letter_log = true;
							$letter_log_recipient = "Student";
							break;
					}
				}
			}
			
			if(isset($_REQUEST['printandlog']))
			{
				//-- Mark as printed
				$printed_date = get_db_date($DBType);
				$user_printed = get_user('USER_ID');
				db_execute("UPDATE STUDENT_EMAILS_ORDER SET DT_PRINTED='$printed_date', USER_PRINTED='$user_printed' WHERE LETTER_ID={$letter_id}");
				
				//-- Letter logging
				if($letter_log)
				{
					$letter_log_students[] = $student_id;
					$subject = $_REQUEST['email_subject']?$_REQUEST['email_subject']:_("Letter");
					$id = db_request(db_execute("SELECT ".db_seq_nextval('student_lf_data_seq')));
					$id = $id[1]['NEXTVAL'];
					$text = str_replace("'","''",$letter_text);
					$date = get_db_date($DBType);
					$time = date("g:i A");
					db_execute("INSERT INTO STUDENT_LF_DATA(
									id,
									student_field_id,
									student_id,
									modified_date,
									log_field1,
									log_field2,
									log_field3,
									log_field4,
									log_field5,
									log_field6
								) 
								VALUES(
								'$id',
								'50014',
								'$student_id',
								'$date',
								'$letter_log_recipient',
								'$date',
								'$subject',
								'$text',
								'".get_user('NAME')."',
								'$time')"
							);
				} //if($letter_log)
			} //if(isset($_REQUEST['printandlog']))
		} //foreach($_REQUEST[$html_field_name] as $k=>$v)
		
		if($to_address=='student' && $_REQUEST['preview']!='true')
			PDFStop($handle);
		elseif($errors)
		{
			$log =& Swift_LogContainer::getLog();
			Basic('header');
			DisplayBlock(_('Errors'),ErrorMessage($errors),'error');
			Basic('footer');
			exit;
		}
		elseif($_REQUEST['preview']!='true' && $_REQUEST['servicemod'])
			echo '<script language=javascript>document.location.href="modloader.php?servicemod='.$_REQUEST['servicemod'].'&sent=true"</script>';
	} //if count
	else
		BackPrompt(_('No Letters were found.'));
}

function _makeChooseCheckbox($value,$title)
{
	return '<INPUT type=checkbox name=student[] value='.$value.' checked>';
}

function _makePhone($value,$column)
{	global $THIS_array,$contacts_array;
	
	if(count($contacts_array[$THIS_array['STUDENT_ID']]))
	{
		if(!$THIS_array['EMAIL'])
			$email = _('No Email Address');
		else
			$email = $THIS_array['EMAIL'];
		
		$tipmessage .= '<B>'.$THIS_array['FULL_NAME'].':</B> '.$email.'<BR>';
		foreach($contacts_array[$THIS_array['STUDENT_ID']] as $person)
		{
			if($person[1]['FIRST_NAME'] || $person[1]['LAST_NAME'])
				$tipmessage .= '<B>'.$person[1]['STUDENT_RELATION'].': '.$person[1]['FIRST_NAME'].' '.$person[1]['LAST_NAME'].'</B><BR>';
			$tipmessage .= '<TABLE>';
			if($person[1]['ADDRESS'])
				$tipmessage .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray size=1 face=Verdana,Arial,Helvetica>'._('Address').'</font> </TD><TD><font size=1 face=Verdana,Arial,Helvetica>'.$person[1]['ADDRESS'].'<BR>'.$person[1]['CITY'].', '.$person[1]['STATE'].' '.$person[1]['ZIPCODE'].'</font></TD></TR>';
			if($person[1]['EMAIL'])
				$tipmessage .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray size=1 face=Verdana,Arial,Helvetica>'._('Email').'</font> </TD><TD><font size=1 face=Verdana,Arial,Helvetica>'.$person[1]['EMAIL'].'</font></TD></TR>';
			$tipmessage .= '</TABLE>';
		}
	}
	elseif($THIS_array['EMAIL'])
		$tipmessage = '<B>'.$THIS_array['FULL_NAME'].':</B> '.$THIS_array['EMAIL'];
	else
		$tipmessage = _('This student has no contact information.');
//	return button('phone','','# onMouseOver=\'stm(["'._('Contact Information').'","'.str_replace("'","&rsquo;",$tipmessage).'"],["white","#'.Preferences('HIGHLIGHT').'","","","",,"black","#'.Preferences('COLOR').'","","","",,300,,2,"#'.Preferences('HIGHLIGHT').'",2,,,,,"",,,,]);\' onMouseOut=\'htm()\'',20);
}

?>