#! /usr/bin/perl
#  Copyright 2001-2022 Leslie Richardson

#  This file is part of Open Admin for Schools.

# Absent strings for matching set in admin.conf; Comparison at line
# 305 in this file.

my $self = 'rptattmonth.pl';

my %lex = ('Monthly Attendance Report' => 'Monthly Attendance Report',
	   'Missing' => 'Missing',
	   'Date' => 'Date',
	   'Main' => 'Main',
	   'Attendance' => 'Attendance',
	   'Schooldays' => 'Schooldays',
	   'Weekdays' => 'Weekdays',
	   'Hols/Inserv' => 'Hols/Inserv',
	   'Red = Withdrawn' => 'Red = Withdrawn',
	   'Grand Totals' => 'Grand Totals',
	   'Periods Per Day' => 'Periods Per Day',
	   'Not Defined' => 'Not Defined',
	   'Name' => 'Name',
	   'Enrolled' => 'Enrolled',
	   'Attended' => 'Attended',
	   'Days' => 'Days',
	   'Absent' => 'Absent',
	   'Unexec' => 'Unexec',
	   'Excuse' => 'Excuse',
	   'Other' => 'Other',
	   'Total' => 'Total',
	   'Late' => 'Late',
	   'Times' => 'Times',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Band' => 'Band',
	   'Total School Days not calculated' => 'Total School Days not calculated',
	   'Student-Days' => 'Student-Days',
	   'Pg' => 'Pg',
	   'Top' => 'Top',
	   'View Log File' => 'View Log File',
	   'Error' => 'Error',
	   'View/Download' => 'View/Download',
	   'Report Type' => 'Report Type',
	   'Group by' => 'Group by',
	   'Continue' => 'Continue',
	   'End' => 'End',
	   'Font Size' => 'Font Size',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Records per Page' => 'Records per Page',
	   'Month' => 'Month',
	   'Group' => 'Group',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Enrol' => 'Enrol',
	   'Active' => 'Active',
	   'Type' => 'Type',
	   'Open' => 'Open',
	   
	   'or' => 'or',
	   'Blank=All' => 'Blank=All',
	   'Select' => 'Select',
	   'Show Withdrawn' => 'Show Withdrawn',
	   

	   );


use DBI;
use CGI;
use Number::Format qw(:all);
use Cwd;

my $defmaxrecords = 24; # Default maximum records per PDF page.


# Get current dir so know what path for config files.
my $configpath;
my $teachermode;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.
} else {
    $configpath = '../..'; # go back two to get to etc.
}

# only load passwords and users
eval require "$configpath/etc/admin.conf.root";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

eval require "$configpath/lib/libattend.pl";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

# for parseGradesPeriod function
eval require "$configpath/lib/libDate.pl";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}


my $dbtype = 'mysql';
my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;


# Load Configuration Variables;
my $sth = $dbh->prepare("select id, datavalue from conf_system where filename = 'admin'");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while (	my ($id, $datavalue) = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}


my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
my $day = @tim[3];
if (length($month) == 1){ $month = "0".$month;}
if (length($day) == 1){ $day = "0".$day;}
my $currdate = "$year-$month-$day";


# Teachermode
if ( $teachermode ) { # running on teacher site
    $css = $tchcss;
    $homepage = $tchpage;
    $downloaddir = $tchdownloaddir;
    $webdownloaddir = $tchwebdownloaddir;
}




my $q = new CGI;
print $q->header( -charset, $charset );
my %arr = $q->Vars;



# Page Header
my $title = "$lex{'Monthly Attendance Report'} 1";

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

print qq{$chartype\n</head><body style="padding:1em;"><a name="top"></a>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> \n};
if ( not $teachermode ) {
    print qq{| <a href="$attpage">$lex{Attendance}</a> };
}
print qq{]\n};

print qq{<h1>$title</h1>\n};


# Show Start Page, if necessary.
if ( not $arr{page} ) {
    showStartPage();
} else {
    delete $arr{page};
}


# foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }


# Setup the TYPE of report, HTML or PDF.
my ( $html, $pdf );
if ( $arr{reporttype} eq 'HTML' ) {
    $html = 1;
} else {
    $pdf = 1;
}

if ( not $arr{month} ) {
    print qq{<h3>$lex{Missing} $lex{Month}</h3>\n};
    print qq{</body></html>\n};
    exit;
}

my ( $year, $month ) = split('-', $arr{month} );
my $yearmonth = $arr{month};


# if ( not $arr{grade} and not $arr{homeroom} ) { # everyone....
#    print qq{<h3>$lex{Missing} $lex{Grade} $lex{or} $lex{Homeroom}</h3>\n};
#    print qq{</body></html>\n};
#    exit;
# }


my  %groups;  # will be: groups{group}{subgroup} for report ordering of students.
# This is the 'container' for the other subgroupings. 
my $group = $arr{group}; # grade, homeroom, band?
if ( $arr{grade} ) { # if we have a grade value, we group by grade.
    $group = 'grade';
} elsif ( $arr{homeroom} ) {
    $group = 'homeroom';
}

    
my $subgroup;
if ( $group eq 'grade' ) { 
    $subgroup = 'grade';
    # WAS $subgroup = 'homeroom';
} else { # group is homeroom
    $subgroup = 'grade';
}


my $sth = $dbh->prepare("select distinct $group, $subgroup from studentall order by $group");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
while ( my ($grp,$subgrp) = $sth->fetchrow ) {
    $groups{$grp}{$subgrp} = 1;
    push @groups, $grp
}


if ( $arr{grade} ) {
    # @groups = ($arr{grade});
    foreach my $g ( keys %groups ) {
	if ( $g ne $arr{grade} ) { delete $groups{$g}; }
    }
    
} elsif ( $arr{homeroom} ) {
    foreach my $g ( keys %groups ) {
	if ( $g ne $arr{homeroom} ) { delete $groups{$g}; }
    }
}



# Check to make sure start date can really be the first of month.
my ($startyear, $startmonth, $startday) = split '-', $schoolstart;
if ( $month == $startmonth and $year == $startyear ) {
    $startdate = $schoolstart;
} else {
    $startdate = "$year-$month-01";
}


# End Date ; Can't just use sql month() function due to August starts.
my ($nextmonth, $nextyear);
if ( $month == 12 ) {
    $nextmonth = 1;
    $nextyear = $year + 1;
} else {
    $nextmonth = $month + 1;
    $nextyear = $year;
}
my $nextstartjd = julian_day($nextyear,$nextmonth,'1');
my $monthendjd = $nextstartjd - 1;
my @tmp = inverse_julian_day($monthendjd);
my $endday = $tmp[2];
my $enddate = qq{$year-$month-$endday};
# print qq{Start:$startdate End:$enddate<br>\n};

=head
#--------------------------------
my $schooldaysopen = calcDaysOpen($startdate, $enddate, $dbh);
# NOTE: one could pass a homeroom (4th arg) and get those counted
# also. It uses dates_homeroom. This function already reads dates table
# and uses non-zero day fractions.


# Find number of days additional school closed this month (partial closures via dates_period table)
# from dates_periods (ie. grades closed).
my $sth = $dbh->prepare("select date from dates_periods where month(date) = ? and year(date) = ?");
$sth->execute($month,$year);
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
my %pclosed; # pclosed{date}{grade} = periodcount; one or more periods.
while ( my $date = $sth->fetchrow ) { # there may be more than one record per date.
    my $ref = parseGradesPeriod($date,$dbh);
    my %per = %$ref;
    foreach my $grade ( sort keys %per ) {
	$pclosed{$date}{$grade}++;
    }
}

my %openfrac; # openfrac{$date} = fraction of day open (ie. less than 1).
foreach my $date ( keys %pclosed ) {
    
    my $closedfrac;
    # there may be more than one grade grouping both with periods
    # closed. We have to find which one is larger in terms of periods
    # closed / ppd for that grade grouping.
    
    foreach my $grade ( sort keys %{ $pclosed{$date}} ) {
	if ( $pclosed{$date}{$grade} / $ppd{$grade} > $closedfrac ) {
	    $closedfrac = $pclosed{$date}{$grade} / $ppd{$grade};
	}
	$openfrac{$date} = 1 - $closedfrac;
    }
}

# we have the fractions of the day open for any day in the month. We
# ignore the values for PK, K since they are just here partially
# anyway....
#-------------------------------
=cut

#=========================================
my $schooldaysopen = calcDaysOpen($startdate, $enddate, $dbh);
# NOTE: one could pass a homeroom (4th arg) and get those counted
# also. It uses dates_homeroom. This function already reads dates table
# and uses non-zero day fractions.


# Find number of days additional school closed this month (partial closures via dates_period table)
# from dates_periods (ie. grades closed).
my $sth = $dbh->prepare("select date from dates_periods where month(date) = ? and year(date) = ?");
$sth->execute($month,$year);
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
my %pclosed; # pclosed{date}{grade} = periodcount; one or more periods.
while ( my $date = $sth->fetchrow ) { # there may be more than one record per date.
    my $ref = parseGradesPeriod($date,$dbh);
    my %per = %$ref;
    foreach my $grade ( sort keys %per ) {
	$pclosed{$date}{$grade}++;
    }
}

my %closedfrac; # stores partial day closed $closedfrac{date} = fraction closed (value between 0 and1)
my $totalpartclosed; # total days equivalent this month partly closed.
foreach my $date ( keys %pclosed ) {
    my $cfrac;
    foreach my $grade ( keys %{ $pclosed{$date}} ) { # go over grades to find largest closed value
	if ( not $g_ppd{$grade} ) {
	    print qq{Missing Att Periods per day for Grade $grade<br>\n};
	    exit;
	}
	my $gradefrac = $pclosed{$date}{$grade} / $g_ppd{$grade}; # fraction closed for this grade.
	if (  $gradefrac > $cfrac ) {
	    $cfrac = $gradefrac; # get largest closed value for this date
	}
    }
    $closedfrac{$date} = round($cfrac, 1);
    $totalpartclosed += round($cfrac, 1);
}

# Adjust value of schools day open based on partial days closure.
$schooldaysopen = $schooldaysopen - $totalpartclosed;
#==================================================



	
if ( $pdf ) { # Open TEX file, and print header.
    $shortname = "monthatt$$";
    $fileName = "$shortname.tex";
    open(TEX,">$fileName") || die "Can't open tex file";
    print_tex_doc_start(); # Setup the start of the file.
}


if ( $html ) { # print top of page

    print qq{<h3>$month[$month] $year / \n};
    print qq{$lex{Days} $lex{Open}: $schooldaysopen </h3>\n};

    print qq{<p>[ <a href="#grandtotal">$lex{'Grand Totals'}</a> ] \n};
    print qq{<span style="color:red;">$lex{'Red = Withdrawn'}</span></p>\n};
}


my $sth = $dbh->prepare("select lastname, firstname, initial, studnum, homeroom, grade, band 
  from studentall where $group = ? and $subgroup = ? order by lastname, firstname");


# Current or Withdrawn?
my $sth5 = $dbh->prepare("select count(*) from studentwd where studnum = ?");


my $curroom = -1; # Watch! Not a value entered for a reason...hopefully.
my $firstflag = 1;  # Flag to watch for first "real" person (not withdrawn)
my ($studentname, $gr, $hr); # global grade, homeroom


# *********** Start of Main Student Loop ***********
foreach my $grp ( sort {$a <=> $b} keys %groups ) {
    foreach my $subgrp ( sort keys %{ $groups{$grp}} ) {

#	print qq{<br><b>GRP:$grp SUB:$subgrp</b><br>\n};
	
	$sth->execute( $grp, $subgrp );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}

	while ( my ( $lastname, $firstname, $middlename, $studnum, $homeroom, $grade, $band )
		= $sth->fetchrow ) {

	    $studentname = qq{<b>$lastname</b>, $firstname $middlename};
	    $gr = $grade;  # for printing in other function
	    $hr = $homeroom; 

	    # Now let's find which table student from: student or studentwd
	    $sth5->execute( $studnum );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $wd = $sth5->fetchrow;  # returns 1 if withdrawn, 0 if not.
	    if ( $wd and $html ){
		$studentname = qq{<span style="color:red;">$studentname</span>};
	    }

	    # Calculate the days enrolled for this student
	    my $ref = calcMonthlyEnrollment( $studnum, $startdate, $enddate, $dbh);
	    if ( not $ref ) { next; } #student

	    my $schooldays = $ref->{$yearmonth}->{'days'};
	    if ( not $schooldays ) { next; } #student


	    # Header printing Section  since we have to skip some students ====

	    $oldroom = $curroom;
	    if ( $group eq 'homeroom' ){
		$curroom = $homeroom; # homeroom field.

		# Get Teacher Name for the room.
		$sth1 = $dbh->prepare("select s.lastname, s.firstname from staff as s, 
				      staff_multi as sm where sm.userid = s.userid and 
				      field_name = 'homeroom' and field_value = ? ");
		$sth1->execute( $curroom );
		if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
		my ($fn, $ln) = $sth1->fetchrow;
		$teachername = '$fn $ln';

	    } elsif ( $group eq 'band' ) {
		$curroom = $band; # band
	    } else {
		$curroom = $grade; # grade field.
	    }
	    
	    if ( $curroom ne $oldroom ) {
		if (not $firstflag) {
		    if ($html){ 
			print_html_class_totals(); 
		    } else { 
			print_tex_class_totals(); 
			$linecount=0; 
		    } 
		    $totschooldays = 0; $totattended = 0;
		    $totlatedayun = 0; $totlatedayex = 0;
		    $totabsentdayun = 0; $totabsentdayex = 0;
		    $totother = 0; $totabsenttot = 0;
		}
		if ($html){ 
		    print qq{<p></p>}; 
		    print_html_header();
		    
		} else { 
		    print_tex_header();
		}

		# Reset the number of periods per day when class changes.
		$periods = $g_ppd{ $grade };  # grade.

		if ( not $periods ){
		    if ( not $grade ){ $grade = 'Undefined!';}
		    print qq{<h1>$lex{'Periods Per Day'} $lex{'Not Defined'}- $lex{Grade}:$grade\n};
		    print qq{$firstname $lastname</h1>\n};
		    print qq{</body></html>\n};
		    exit qq{No grade for: $firstname $lastname ($studnum)\n};
		}
	    }
	    # End of Header printing section ===========
 
	    # Note: this can use startdate and $enddate since we only track absences
	    # Get attendance records for this student and loop through adding up.
	    $sth1 = $dbh->prepare("select * from attend 
             where studentid = ? and 
             to_days(absdate) >= to_days('$startdate') and 
             to_days(absdate) <= to_days('$enddate') 
             order by absdate,period");
	    $sth1->execute( $studnum );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	    $absentex = 0;$absentun = 0;
	    $lateex = 0;$lateun = 0;
	    $other = 0;

	    # Track 5 groups of attendance: Absent Unexcused, Absent (any
	    # other; presumed excused), Late Unexcused, Late (any other;
	    # presumed excused), Other (which should be 0).

	    while ( my @absence = $sth1->fetchrow ) {
		my $reason = $absence[3];
		# These string values set in the admin.conf file and match reasons
		if ($reason =~ /$absentUnexcused/) { $absentun++; }
		elsif ($reason =~ /$absentString/){ $absentex++;}
		elsif ($reason =~ /$lateUnexcused/) { $lateun++; }
		elsif ($reason =~ /$lateString/) { $lateex++; }
		else { $other++;}
	    }

	    if ( not $periods ) {
		if ( not $grade ){ $grade = 'Undefined';}
		print qq{<h1>$lex{'Periods Per Day'} $lex{'Not Defined'}- $lex{Grade}:$grade\n};
		print qq{$firstname $lastname.</h1>\n};
		print qq{</body></html>\n};
		exit;
	    }

	    if ( not $schooldays or $schooldays == 0 ) {
		print qq{<h1>$lex{Schooldays} $lex{Missing} - };
		print qq{$firstname $lastname ($studnum)</h1>\n};
		print qq{</body></html>\n};
		exit;
	    }

	    $absentdayun = $absentun/$periods; # convert from periods into days
	    $absentdayex = $absentex/$periods;
	    $otherday = $other/$periods;

	    $absentperun = ($absentdayun/$schooldays) * 100;
	    $absentperex = ($absentdayex/$schooldays) * 100;
	    $otherper = ($otherday/$schooldays) * 100;

	    $absentdaytot = $absentdayun + $absentdayex + $otherday; 
	    $absentpertot = ($absentdaytot/$schooldays) * 100;

	    $latedayun = $lateun/$periods;
	    $latedayex = $lateex/$periods;
	    $lateperun = ($latedayun/$schooldays) * 100;
	    $lateperex = ($latedayex/$schooldays) * 100;

	    $schooldays -= $totalpartclosed; # partial days closed
	    $attended = $schooldays - $absentdaytot;
	    if ( $attended < 0 ) {
		$schooldays += $totalpartclosed; # put this value back since WD was before this day.
		$attended = 0;
	    }

	    # For Class/Grade Summary
	    $totschooldays = $schooldays + $totschooldays;
	    $totattended = $attended + $totattended;

	    $totabsentdayun = $absentdayun + $totabsentdayun;
	    $totabsentdayex = $absentdayex + $totabsentdayex;
	    $totother = $otherday + $totother;
	    $totabsenttot = $absentdaytot + $totabsenttot;

	    $totlatedayun = $latedayun + $totlatedayun;
	    $totlatedayex = $latedayex + $totlatedayex;

	    # For School Summary at Bottom
	    $grtotschooldays += $schooldays; $grtotattended += $attended;
	    $grtotabsentdayun += $absentdayun; $grtotabsentdayex += $absentdayex;
	    $grtotother += $otherday; $grtotabsenttot += $absentdaytot;
	    $grtotlatedayun += $latedayun; $grtotlatedayex += $latedayex;

	    $firstflag = 0;  # Not first person to run through.

	    # Print this student's record
	    if ( $html ){ 
		print_html_record( $studnum, $schooldays ); 
	    } else { 
		print_tex_record( $lastname, $firstname, $middlename, $studnum, $schooldays );
	    }

	    $linecount++;
	    if ( $pdf and $linecount >= $arr{maxrecords} ) { # New page.
		print TEX "\\end{tabular}\\newpage\n\n";
		print_tex_header();
		$linecount = 0;
	    }

	} # End of main studentloop
	
    } # end of subgroup loop
} # end of group loop


# print out stats for the last class
if ($html){ 
    print_html_class_totals(); 
} else { 
    print_tex_class_totals();
}


# Grand totals
if ($html){ 
    print_html_grandtotals(); 

} else { 
    print_tex_grandtotals();
    print_tex_end();
}



#----------------
sub showStartPage {
#----------------

    # Setup Year-Months.
    my @months;
    my %months;


    my ($sy, $sm, $sd) = split('-', $schoolstart); # schoolstart is global var from config.
    my $yrmo = "$sy-$sm";
    push @months, $yrmo;
    $months{$yrmo} = "$s_month[$sm]-$sy";

    for my $i (1..10) {
	my $mo = $sm + $i;
	my $yr = $sy;
	if ( $mo > 12 ) {
	    $mo = $mo - 12;
	    $yr++;
	}

	if ( $yr == $cyear and $mo == $cmonth ) { # done
	    last;
	}
	
	if ( length $mo == 1 ) { $mo = '0'. $mo; }
	my $yrmo = "$yr-$mo";
	push @months, $yrmo;
	$months{$yrmo} = "$s_month[$mo]-$yr";
    }


    # Get the grades
    my @grades;
    my $sth = $dbh->prepare("select distinct grade from student 
      where grade is not NULL and grade != ''");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $gr = $sth->fetchrow ) {
	push @grades, $gr;
    }


    # Get the homerooms.
    my @homerooms;

    my $sth1 = $dbh->prepare("select distinct grade from student where homeroom = ? 
      and grade != '' and grade is not NULL");

    my $sth = $dbh->prepare("select distinct homeroom from student where 
     homeroom is not NULL and homeroom != ''");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {

	push @homerooms, $hr; # removed checking below
	# Now check for the grade level in this homeroom
#	$sth1->execute($hr);
#	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
#	while ( my $gr = $sth1->fetchrow ) {
#	    if ( $g_AttendanceEntryMethod{$gr} eq 'homeroom' ) {
#		push @homerooms, $hr;
#		last;
#	    }
#	}
    }


=head   
    my ($cyear,$cmonth, $cday) = split('-', $currdate);
    # Get Previous month end.
    my $startdayjd = julian_day($cyear, $cmonth, '1');
    my $prevendjd = $startdayjd - 1; # end of previous month.
    my @prev = inverse_julian_day( $prevendjd );
    my $prevdate = join('-', @prev);
=cut


    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<table cellpadding="3" border="0" cellspacing="0">\n};

    # Report Type
    print qq{<tr><td class="bra">$lex{'Report Type'}</td><td>};
    print qq{<select name="reporttype"><option>HTML</option><option>PDF</option>\n};
    print qq{</select></td></tr>\n};

    # Month
    print qq{<tr><td class="bra">$lex{Select} $lex{Month}</td>};
    print qq{<td class="la"><select name="month"><option></option>\n}; 

    foreach my $mo ( @months ) {
	print qq{<option value="$mo">$months{$mo}</option>\n};
    }
    print qq{</select></td></tr>\n};

    print qq{<tr><td colspan="2"><hr></td></tr>\n};

    
    # Homerooms
    print qq{<tr><td class="bra">$lex{Homeroom}</td>};
    print qq{<td class="la"><select name="homeroom"><option></option>\n}; 

    foreach my $hr ( sort {$a <=> $b} @homerooms ) {
	print qq{<option>$hr</option>\n};
    }
    print qq{</select> $lex{'Blank=All'}</td></tr>\n};


    # Grades
    print qq{<tr><td class="bra"><span style="font-weight:normal;">$lex{or}</span> };
    print qq{$lex{Grade}</td>};
    print qq{<td class="la"><select name="grade"><option></option>\n}; 

    foreach my $gr ( sort {$a <=> $b} @grades ) {
	print qq{<option>$gr</option>\n};
    }
    print qq{</select> $lex{'Blank=All'}</td></tr>\n};

    
    # Spacer
    print qq{<tr><td colspan="2"><hr></td></tr>\n};

    
    # Group
    print qq{<tr><td class="bra">$lex{'Group by'}</td><td><select name="group">};
    print qq{<option value="grade">$lex{Grade}</option>\n};
    print qq{<option value="homeroom">$lex{Homeroom}</option>};
    # print qq{<option value="band">$lex{Band}</option>}
    print qq{</select></td></tr>\n};


    # Show Withdrawn
#    print qq{<tr><td class="bra">$lex{'Show Withdrawn'}</td>\n};
#    print qq{<td><input type="checkbox" name="showwithdrawn" value="1"></td></tr>\n};

    # Spacer
    print qq{<tr><td colspan="2"><hr></td></tr>\n};        
    print qq{<tr><td colspan="2" class="bcn">PDF Options</td></tr>\n};        
    
    # Paper Size
    $defaultpapersize =~ s/paper//; # strip out word paper so lex works; from admin.conf
    my $defpaper = ucfirst( $defaultpapersize );

    print qq{<tr><td class="bra">$lex{'Paper Size'}</td>\n<td>};
    print qq{<select name="papersize">};
    if ( $lex{$defpaper} ) { print qq{<option>$lex{$defpaper}</option>\n}; }
    my @sizes = qw(Letter A4 Legal);
    foreach my $size ( @sizes ) {
	if ( $size eq $defpaper ) { next; }
	print qq{<option>$lex{$size}</option>};
    }
    print qq{</select></td></tr>\n};

    # Font Size
    print qq{<tr><td class="bra">$lex{'Font Size'}</td>\n<td>};
    print qq{<select name="fontsize"><option>10pt</option><option>11pt</option>\n};
    print qq{<option>12pt</option></select></td></tr>\n};

    # Records per page
    print qq{<tr><td class="bra">$lex{'Records per Page'}</td>\n<td>};
    print qq{<input type="text" name="maxrecords" size="4" value="$defmaxrecords"></td></tr>\n};

    # Spacer
    print qq{<tr><td colspan="2"><hr></td></tr>\n};        

    print qq{<tr><td></td>};
    print qq{<td class="la"><input type="submit" value="$lex{Continue}">\n};
    print qq{</td></tr>\n};

    print qq{</table></form>\n};
    print qq{</body></html>\n};

    exit;
}



# Print Table header at top of each table.
#--------------------
sub print_html_header {
#--------------------

    my $heading = "\L\u$group";
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th colspan="10" style="font-size:130%;font-weight:bold;">};
    print qq{$heading: $curroom</th></tr>};

    print qq{<tr><th>$lex{Name}</th><th>$lex{Grade}<br>$lex{Homeroom}</th><th>$lex{Enrolled}</th>\n};
    print qq{<th>$lex{Attended}<br>($lex{Days})</th>\n};

    print qq{<th>$lex{Absent}<br>$lex{Unexec}<br>($lex{Days})</th>};
    print qq{<th>$lex{Absent}<br>$lex{Excuse}<br>($lex{Days})</th>\n};

    print qq{<th>$lex{Absent}<br>$lex{Other}<br>($lex{Days})</th>};
    print qq{<th>$lex{Absent}<br>$lex{Total}<br>($lex{Days})</th>\n};

    print qq{<th>$lex{Late}<br>$lex{Unexec}<br>($lex{Times})</th>};
    print qq{<th>$lex{Late}<br>$lex{Excuse}<br>($lex{Times})</th></tr>\n};

}


#-------------------
sub print_tex_header {
#-------------------

    my $heading = "\L\u$group";
    print TEX "\\begin{tabular}{|p{5cm}";
    for (1..8){ print TEX "|p{1.4cm}";}
    print TEX "|}\n\\hline\\rowcolor[gray]{0.85}{\\it $heading:} ";
    print TEX "{\\bf\\large $curroom} \n";
    print TEX "& {\\bf ". $lex{Enrolled}. ' ('. $lex{Days}. ")} & {\\bf ";
    print TEX $lex{Attended}. ' ('. $lex{Days}. ")} & ";
    print TEX "{\\bf ". $lex{Absent}. ' '. $lex{Unexec}. ' ('. $lex{Days};
    print TEX ")} &{\\bf ". $lex{Absent}. ' '. $lex{Excuse}. ' ('. $lex{Days}. ")} & ";

    print TEX "{\\bf ". $lex{Absent}. ' '. $lex{Other}. ' ('. $lex{Days}. ")} &{\\bf ";
    print TEX $lex{Absent}. ' '. $lex{Total}. ' ('. $lex{Days}. ")} & \n";
    print TEX "{\\bf ". $lex{Late}. ' '. $lex{Unexec}. ' ('. $lex{Times}. ")} &{\\bf ";
    print TEX $lex{Late}. ' '. $lex{Excuse}. ' ('. $lex{Times}. ")}\\\\ \\hline\n";
}


#--------------------------
sub print_html_class_totals {
#--------------------------

    if ( not $totschooldays ) { 
	print qq{$lex{Error}: $lex{'Total School Days not calculated'}!\n}; 
	return;
    }

    $totpercent = ($totattended/$totschooldays) * 100;

    $totabsentperun = ($totabsentdayun/$totschooldays) * 100;
    $totabsentperex = ($totabsentdayex/$totschooldays) * 100;
    $tototherper = ($totother/$totschooldays) * 100;
    $totabsentpertot = ($totabsenttot/$totschooldays) * 100;

    $totlateperun = ($totlatedayun/$totschooldays) * 100;
    $totlateperex = ($totlatedayex/$totschooldays) * 100;

    # print out stats for this class
    print qq{<tr class="gray"><td class="bra">$lex{Total} - ($lex{'Student-Days'})</td><td></td>\n};

    print qq{<td>}. format_number($totschooldays,2,2). qq{</td>};
    print qq{<td>}. format_number($totattended,2,2). qq{<br> (}; 
    print format_number( $totpercent, 2,2 );
    print qq{%)</td>\n};

    print qq{<td>}. format_number($totabsentdayun,2,2). qq{<br>(}; 
    print format_number( $totabsentperun, 2, 2);
    print qq{%)</td>\n};

    print qq{<td>}. format_number($totabsentdayex,2,2). qq{<br>(}; 
    print format_number( $totabsentperex, 2,2);
    print qq{%)</td>\n};

    print qq{<td>}. format_number($totother,2,2). qq{<br>(}; 
    print format_number( $tototherper, 2, 2 );
    print qq{%)</td>\n};

    print qq{<td>}. format_number($totabsenttot,2,2). qq{<br>(}; 
    print format_number( $totabsentpertot, 2,2);
    print qq{%)</td>\n};

    print qq{<td>}. format_number($totlatedayun,2,2). qq{ $lex{Days}<br>(}; 
    print format_number( $totlateperun, 2,2);
    print qq{%)</td>\n};

    print qq{<td>}. format_number($totlatedayex,2,2). qq{ $lex{Days}<br>(}; 
    print format_number( $totlateperex, 2);
    print qq{%)</td>\n};

    print qq{</tr></table>\n};

}


#-------------------------
sub print_tex_class_totals {
#-------------------------
    if ( not $totschooldays ){
	print qq{$lex{Error}! $lex{'Total School Days not calculated'}};
	return;
    }

    $totpercent = ($totattended/$totschooldays) * 100;

    $totabsentperun = ($totabsentdayun/$totschooldays) * 100;
    $totabsentperex = ($totabsentdayex/$totschooldays) * 100;
    $tototherper = ($totother/$totschooldays) * 100;
    $totabsentpertot = ($totabsenttot/$totschooldays) * 100;

    $totlateperun = ($totlatedayun/$totschooldays) * 100;
    $totlateperex = ($totlatedayex/$totschooldays) * 100;


    # print out stats for this class
    print TEX "\\rowcolor[gray]{0.90}";
    print TEX "{\\bf Totals (Student-Days)} & ". format_number($totschooldays,2,2). " &\n";
    print TEX format_number($totattended,2,2). " (", format_number( $totpercent, 2,2),"\\%)& \n";
    print TEX format_number($totabsentdayun,2,2). " (", format_number( $totabsentperun, 2,2),"\\%)&\n";
    print TEX format_number($totabsentdayex,2,2). " (", format_number( $totabsentperex, 2,2),"\\%)&\n";
    print TEX format_number($totother,2,2). " (", format_number( $tototherper, 2,2),"\\%)&\n";
    print TEX format_number($totabsenttot,2,2). " (", format_number( $totabsentpertot, 2,2),"\\%)&\n";

    print TEX format_number($totlatedayun,2,2). ' '. $lex{Days}. " (";
    print TEX format_number( $totlateperun, 2,2),"\\%)&\n";

    print TEX format_number($totlatedayex,2,2). ' '. $lex{Days}. " (";
    print TEX format_number( $totlateperex, 2,2),"\\%)\\\\";
    print TEX "\\hline\\end{tabular}\n\n\\bigskip\n\\bigskip\n";

    print TEX "\\underline{\\hspace{2.5in}} \n\n";
    print TEX "{\\small Teacher}\n";

    print TEX "\\newpage\n\n";

}


#----------------------
sub print_tex_doc_start {
#----------------------

    # Set Paper Size, text width and height
    my ( $papersize, $textwidth, $textheight );

    if ( $arr{papersize} eq $lex{Letter} ) {
	$papersize = 'letterpaper';
	$textwidth = $g_letterpaper_textwidth;
	$textheight = $g_letterpaper_textheight;
    } elsif ( $arr{papersize} eq $lex{Legal} ) {
	$papersize = 'legalpaper';
	$textwidth = $g_legalpaper_textwidth;
	$textheight = $g_legalpaper_textheight;
    } elsif ( $arr{papersize} eq $lex{A4} ) {
	$papersize = 'a4paper';
	$textwidth = $g_a4paper_textwidth;
	$textheight = $g_a4paper_textheight;
    }


    print TEX "\\documentclass[$arr{fontsize}, $papersize, oneside]{article}
\\usepackage{array,colortbl,inputenc}
$a_latex_header
%\\renewcommand{\\familydefault}{\\sfdefault}
\\pagestyle{empty}
\\setlength{\\textwidth}{$textwidth}
\\setlength{\\textheight}{$textheight}
\\setlength{\\hoffset}{-38mm}
\\setlength{\\voffset}{-20mm}
\\setlength{\\headsep}{10pt}
\\setlength{\\headheight}{14pt}
\\setlength{\\topmargin}{0pt}
\\setlength{\\parindent}{0pt}
\\setlength{\\tabcolsep}{5pt}
\\setlength{\\extrarowheight}{3pt}
\\pagestyle{headings}
\\markright{$schoolname \\hfill ". $lex{'Monthly Attendance Report'}.
" -- $month[$month] $year -- ". $lex{Pg}. "  }
\n\n
\\begin{document}\n";
} # End of Print Tex Doc Start


#----------------
sub print_tex_end {
#----------------
    print TEX "\\hline\\end{tabular}\n\n\\end{document}\n";
    close TEX;

    system("$pdflatex $fileName > pdflog$$.txt");
    system("mv $shortname.pdf $downloaddir");
    system("mv pdflog$$.txt $downloaddir");
    system("rm $shortname.*");
    
    print qq{<h1><a href="$webdownloaddir/$shortname.pdf">\n};
    print qq{$lex{'View/Download'} $lex{'Monthly Attendance Report'}</a></h1>\n};
    
    print qq{<p>[ \n};
    if ( not $teachermode ) {
	print qq{ <a href="$attpage">$lex{Attendance}</a> | \n};
    }
    
    print qq{ <a href="$webdownloaddir/pdflog$$.txt">};
    print qq{$lex{'View Log File'}</a> ]</p>\n};
    print qq{</body></html>\n};

} # Print Tex End



#--------------------
sub print_html_record {
#--------------------

    my ( $studnum, $schooldays ) = @_;

    print qq{<tr><td>$studentname ($studnum) $withdrawdate</td><td>$gr/$hr</td>\n};
    print qq{<td class="bcn">}. format_number($schooldays, 2,2). qq{</td>\n};

    my $att = format_number($attended, 2,2);
    
    if ( $attended < 0 ) {
	$att = qq{<span style="color:red;font-size:140%">$att</span>};
    } else {
	$att = qq{<b>$att</b>};
    }
    print qq{<td>$att</td>\n};

    
    print qq{<td><b>}. format_number($absentdayun, 2,2). qq{</b> (}; 
    print format_number( $absentperun,2,2);
    print qq{%)</td>};

    print qq{<td><b>}. format_number($absentdayex,2,2). qq{</b> (}; 
    print format_number( $absentperex, 2,2);
    print qq{%)</td>\n};

    print qq{<td><b>}. format_number($otherday,2,2). qq{</b> (};
    print format_number( $otherper, 2,2); 
    print qq{%)</td>};

    print qq{<td><b>}. format_number($absentdaytot,2,2). qq{</b> (}; 
    print format_number( $absentpertot, 2,2 ); 
    print qq{%)</td>};

    print qq{<td><b>}. format_number($lateun,2,2). qq{</b> (}; 
    print format_number( $lateperun, 2,2 );
    print qq{%)</td>};

    print qq{<td><b>}. format_number($lateex, 2,2). qq{</b> (}; 
    print format_number( $lateperex, 2,2);
    print qq{%)</td>};
    print qq{</tr>\n};


} # End of Print HTML Record


#-------------------
sub print_tex_record {
#-------------------

    my ( $lastname, $firstname, $middlename, $studnum, $schooldays ) = @_;

    print TEX "{\\bf $lastname}, $firstname $middlename ($studnum) $withdrawdate & ";
    print TEX format_number($schooldays,2,2). " & ". format_number($attended,2,2). " & ";
    print TEX format_number($absentdayun,2,2). " (", format_number( $absentperun, 2,2), "\\%)& ";
    print TEX format_number($absentdayex,2,2). " (", format_number( $absentperex, 2,2), "\\%) & ";
    print TEX format_number($otherday,2,2). " (", format_number( $otherper, 2,2), "\\%) & ";
    print TEX format_number($absentdaytot,2,2). " (", format_number( $absentpertot, 2,2),"\\%) & ";
    print TEX format_number($lateun,2,2). " (", format_number( $lateperun, 2,2), "\\%) & ";
    print TEX format_number($lateex,2,2). " (", format_number( $lateperex, 2,2), "\\%) \\\\ \\hline\n\n";

}


#-------------------------
sub print_html_grandtotals {
#-------------------------

    
    # Print Grand Totals
    print qq{<a style="margin:1em;" name="grandtotal"></a>\n};
    
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    
    print qq{<tr><th colspan="9" style="font-size:130%;font-weight:bold;">};
    print qq{$lex{'Grand Totals'}</th></tr>\n};
    print qq{<tr><th></th><th>$lex{Enrolled}</th><th>$lex{Attended} };
    print qq{<br>($lex{Days})</th>\n};

    print qq{<th>$lex{Absent}<br>$lex{Unexec}<br>($lex{Days})</th>\n};
    print qq{<th>$lex{Absent}<br>$lex{Excuse}<br>($lex{Days})</th>\n};
    print qq{<th>$lex{Absent}<br>$lex{Other}<br>($lex{Days})</th>\n};
    print qq{<th>$lex{Absent}<br>$lex{Total}<br>($lex{Days})</th>\n};
    print qq{<th>$lex{Late}<br>$lex{Unexec}<br>($lex{Times})</th>\n};
    print qq{<th>$lex{Late}<br>$lex{Excuse}<br>($lex{Times})</th></tr>\n};

    $grtotpercent = ($grtotattended/$grtotschooldays) * 100;

    $grtotabsentperun = ($grtotabsentdayun/$grtotschooldays) * 100;
    $grtotabsentperex = ($grtotabsentdayex/$grtotschooldays) * 100;
    $grtototherper = ($grtotother/$grtotschooldays) * 100;
    $grtotabsentpertot = ($grtotabsenttot/$grtotschooldays) * 100;
    
    $grtotlateperun = ($grtotlatedayun/$grtotschooldays) * 100;
    $grtotlateperex = ($grtotlatedayex/$grtotschooldays) * 100;

    # print out grand totals
    print qq{<tr class="gray"><td class="bra">$lex{'Grand Totals'} (Student-Days)</td>\n};

    print qq{<td>}. format_number($grtotschooldays,2,2). qq{</td>};
    print qq{<td>}. format_number($grtotattended,2,2). qq{$lex{Days}<br>(}; 
    print format_number( $grtotpercent, 2,2 );
    print qq{%)</td>\n};

    print qq{<td>}. format_number($grtotabsentdayun,2,2). qq{$lex{Days}<br>(}; 
    print format_number( $grtotabsentperun, 2,2 ); 
    print qq{%)</td>\n};
    
    print qq{<td>}. format_number($grtotabsentdayex,2,2). qq{$lex{Days}<br>(}; 
    print format_number( $grtotabsentperex, 2,2 );
    print qq{%)</td>\n};

    print qq{<td>}. format_number($grtotother,2,2). qq{$lex{Days}<br>(}; 
    print format_number( $grtototherper, 2,2 ); 
    print qq{%)</td>\n};
    
    print qq{<td>}. format_number($grtotabsenttot,2,2). qq{$lex{Days}<br>(}; 
    print format_number( $grtotabsentpertot, 2,2 ); 
    print qq{%)</td>\n};
    
    print qq{<td>}. format_number($grtotlatedayun,2,2). qq{<br>(}; 
    print format_number( $grtotlateperun, 2,2 ); 
    print qq{%)</td>\n};

    print qq{<td>}. format_number($grtotlatedayex,2,2). qq{<br>(}; 
    print format_number( $grtotlateperex, 2,2 ); 
    print qq{%)</td>\n};

    print qq{</tr></table>\n};
    
    print qq{<p>[ <a href="$homepage">$lex{Main}</a> |\n};
    print qq{<a href="$attpage">$lex{Attendance}</a> |\n};
    print qq{<a href="#top">$lex{Top}</a> ]</p></body></html>\n};

}


#------------------------
sub print_tex_grandtotals {
#------------------------

    print TEX "\\begin{tabular}{|p{4cm}";
    for (1..8){ print TEX "|p{1.5cm}";}
    print TEX "|}\n\\hline\\rowcolor[gray]{0.85}". $lex{'Grand Totals'}. " &";
    print TEX $lex{Enrolled}. " & ". $lex{Attended}. " (". $lex{Days}. ") &";
    print TEX $lex{Absent}. ' '. $lex{Unexec}. " (". $lex{Days}. ") & ". $lex{Absent};
    print TEX ' '. $lex{Excuse}. " (". $lex{Days}. ") &";
    print TEX $lex{Absent}. ' '. $lex{Other}. " (". $lex{Days}. ") & ". $lex{Absent};
    print TEX ' '. $lex{Total}. " (". $lex{Days}. ") &";
    print TEX $lex{Late}. ' '. $lex{Unexec}. " (". $lex{Times}. ") & ". $lex{Late};
    print TEX ' '. $lex{Excuse}. " (". $lex{Times}. ")\\\\ \\hline\n";

    $grtotpercent = ($grtotattended/$grtotschooldays) * 100;

    $grtotabsentperun = ($grtotabsentdayun/$grtotschooldays) * 100;
    $grtotabsentperex = ($grtotabsentdayex/$grtotschooldays) * 100;
    $grtototherper = ($grtotother/$grtotschooldays) * 100;
    $grtotabsentpertot = ($grtotabsenttot/$grtotschooldays) * 100;
    
    $grtotlateperun = ($grtotlatedayun/$grtotschooldays) * 100;
    $grtotlateperex = ($grtotlatedayex/$grtotschooldays) * 100;


    # print out grand totals
    print TEX $lex{'Grand Totals'}. " (". $lex{'Student-Days'}. ") & ";
    print TEX format_number($grtotschooldays,2,2). " &";

    print TEX format_number( $grtotattended,2,2). q{ }. $lex{Days}. " (";
    print TEX format_number( $grtotpercent, 2,2 ). "\\%)&\n";

    print TEX format_number( $grtotabsentdayun,2,2). q{ }. $lex{Days}. " (";
    print TEX format_number( $grtotabsentperun, 2,2 ). "\\%)&\n";

    print TEX format_number($grtotabsentdayex,2,2). q{ }. $lex{Days}. " (";
    print TEX  format_number( $grtotabsentperex, 2,2 ),"\\%)&\n";

    print TEX format_number($grtotother,2,2). q{ }. $lex{Days}. " (";
    print TEX format_number( $grtototherper, 2),"\\%)&\n";

    print TEX format_number($grtotabsenttot,2,2). q{ }. $lex{Days}. " (";
    print TEX format_number( $grtotabsentpertot, 2,2),"\\%)&\n";

    print TEX format_number($grtotlatedayun,2,2). q{ }. " (";
    print TEX format_number( $grtotlateperun, 2,2),"\\%)&\n";

    print TEX format_number($grtotlatedayex,2,2). q{ }. " (";
    print TEX format_number( $grtotlateperex, 2,2),"\\%)\\\\ \n";


} # End of Print_tex_grandtotals

