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

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

# Monthly report for Enrollment change.
# PDF Output

my %lex = ('Monthly Enrollment' => 'Monthly Enrollment',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Main' => 'Main',
	   'Blank=Previous Month' => 'Blank=Previous Month',
	   'No Enrollment Changes' => 'No Enrollment Changes',
	   'Student' => 'Student',
	   'Reason' => 'Reason',
	   'Principal' => 'Principal',
	   'Grade' => 'Grade',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Month' => 'Month',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Font Size' => 'Font Size',
	   'Report' => 'Report',
	   'Days Open' => 'Days Open',
	   'Homeroom' => 'Homeroom',
	   'Missing' => 'Missing',
	   'Periods Per Day' => 'Periods Per Day',
	   
	   );

# show Principal Signature Line; set to 0 to turn off
my $principalSign = 1;

my $self = 'rptenrol1.pl';


use DBI;
use CGI;
use Time::JulianDay;
use Number::Format qw(:all);

eval require "../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

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

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


# Used for the category titles
my $shortname = "rptenrol1$$";
# my $shortname = "test";
my $fileName = "$shortname.tex";


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


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


# Set Dates
#my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday,
#    $iddst) = localtime(time);
#$year = $year + 1900;
#$mon++;
#$wday++;
#my $currdate = "$year-$mon-$mday";


# Set Date
my @tim = localtime(time);
my $cyear = @tim[5] + 1900;
my $cmonth = @tim[4] + 1;
my $cday = @tim[3];
my $currdate = "$cyear-$cmonth-$cday";
my $currjd = julian_day( split('-', $currdate) );
my $curryrmo = "$cyear-$cmonth";


# Print Page Head.
my $title = "$lex{'Monthly Enrollment'} $lex{Report}";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

if ( not $arr{page} ) {
    print qq{<link rel="stylesheet" type="text/css" media="all" };
    print qq{href="/js/calendar-blue.css" title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};
}

print qq{$chartype\n</head><body style="padding:1em 2em;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};

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

if ( not $arr{page} ) {
    showStartPage();

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    showReport();
}


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

    
    # Setup Year-Months.
    my (@months, %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 ( length $mo == 1 ) { $mo = '0'. $mo; }
	my $yrmo = "$yr-$mo";
	push @months, $yrmo;
	$months{$yrmo} = "$s_month[$mo]-$yr";

	if ( $yr == $cyear and $mo == $cmonth ) { # done
	    last;
	}
	
    }


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

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

    
    # Get Month
    print qq{<tr><td class="bra">$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};

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

    print qq{<tr><td class="bra">$lex{'Paper Size'}</td><td>};
    print qq{ <select name="papersize"><option>$lex{Letter}</option>\n};
    print qq{<option>$lex{Legal}</option><option>$lex{A4}</option>\n};
    print qq{</select></td></tr>\n};


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


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

    exit;

}


#--------------
sub showReport {
#--------------

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

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


    # Get the rooms: grade and room.
    my %grRooms;

    my $sth = $dbh->prepare("select distinct grade, homeroom from student");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    while ( my ($grade, $homeroom ) = $sth->fetchrow ) {
	if (not $homeroom) { $homeroom = 'none'; }
	if ( $grade eq 'P3' ) { next; } # skip P3
	$grRooms{$grade}{$homeroom} = '';
    }

    # Test
#    foreach my $gr ( sort {$a <=> $b} keys %grRooms ) {
#	foreach my $hr ( sort keys %{ $grRooms{$gr}} ) {
#	    print "Grade $gr Homeroom $hr Count:$grRooms{$gr}{$hr}<br>\n";
#	}
#    }

    # check for the month being the start month.
    my $startdate;
    my ($sy,$sm,$sd) = split('-', $schoolstart);
    my ($y,$m) = split('-', $arr{month});
    # print "Month:$m StartMonth:$sm<br>SchoolStart:$schoolstart - Month:$arr{month}<br>\n";
    if ($m eq $sm ) { # same month, use schoolstartdate
	$startdate = $schoolstart;
    } else {
	$startdate = $arr{month}. '-01'; # start of the month.
    }
    
    my $startjd = julian_day( split('-', $startdate ));
    my ($year,$month) = split('-', $arr{month});
    my $yearmonth = $arr{month}; # format YYYY-MM
    
    # Get end of month date, and then days open
    my @mdays = (0,31,28,31,30,31,30,31,31,30,31,30,31);
    if ($month == 2) {
	if ($year % 4 != 0) { $mdays[2] = 28; }
	elsif ($year % 400 == 0) { $mdays[2] = 29; }
	elsif ($year % 100 == 0) { $mdays[2] = 28; }
	else { $mdays[2] = 29; }
    }

    my $enddate = $arr{month}. qq{-$mdays[$month]}; # end of the month.

#    print "End Date:$enddate\n";

    # Do Days Open for both including the PK/K system.
    my $daysopen = calcDaysOpen($startdate,$enddate, $dbh);
    # print qq{<div> Days Open: $daysopen ($startdate / $enddate)</div>\n};
    
    # check for any nsd (non school days) for PK/K
    my %daysopennsd;
    my $sth = $dbh->prepare("select distinct homeroom from dates_homeroom 
       where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    while ( my $homeroom = $sth->fetchrow ) {
	$daysopennsd{$homeroom} = calcDaysOpen($startdate,$enddate, $dbh, $homeroom);
#	print qq{<div>Homeroom:$homeroom Open: $daysopennsd{$homeroom}</div>\n};
    }

    
    # Get Current Students and then move backwards to starting date to get students at that point.
    my %students;
    my $sth = $dbh->prepare("select studnum from student where studnum is not NULL and studnum != ''");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $studnum = $sth->fetchrow ) {
	$students{$studnum} = 1;
    }

    $sth = $dbh->prepare("select studnum, type from transfer where to_days(date) >= to_days('$startdate')
      order by date desc");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($studnum, $type) = $sth->fetchrow ) {
	if ( $type eq 'withdraw' ) { # add the student, since they must have been present earlier
	    $students{$studnum} = 1;
	} else { # since enrolling we must remove them, since were not there earlier.
	    delete $students{$studnum};
	}
    }
    # The %students hash should now have all students that were enrolled on the first of the month of interest.

#    print qq{Start:$startdate - Students<br>\n};
#    foreach my $studnum ( sort keys %students ) {
#	print qq{$studnum<br>\n};
#    }
    
    
    # Get the enrollment counts for these %students by grade and room.
    my $sth = $dbh->prepare("select grade, homeroom from studentall where studnum = ?");

    foreach my $studnum ( keys %students ) {
    
	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($grade, $homeroom ) = $sth->fetchrow;
	if (not $homeroom) { $homeroom = 'none'; }
	if ( $grade eq 'P3' ) { next; } # skip P3
	$grRooms{$grade}{$homeroom}++;
    }
    
    # Test
#    foreach my $gr ( sort {$a <=> $b} keys %grRooms ) {
#	foreach my $hr ( sort {$a <=> $b} keys %{ $grRooms{$gr}} ) {
#	    print "Grade $gr Homeroom $hr Count:$grRooms{$gr}{$hr}<br>\n";
#	}
#    }

    # We now have enrollment counts for the start of the month, along with those students.

   
    my @grades; # set @grades array with PK, K at start if they exist.
    if ( $grRooms{PK} ) {
	push @grades, 'PK';
    }
    if ( $grRooms{K} ) {
	push @grades, 'K';
    }
    foreach my $gr ( sort {$a <=> $b} keys %grRooms ) {
	if ( $gr eq 'PK' or $gr eq 'K' ) { next; }
	push @grades, $gr;
    }

#    my $grades = join(',',@grades);    
#    print qq{The Grades Are: $grades<br>\n};
#    exit;

    # single duplicate pair, so cleaner than using a hash, I guess!
    my @grhr;
    foreach my $grade ( @grades ) {
	foreach my $key ( sort keys %{ $grRooms{$grade} } ) {
	    push @grhr, "$grade:$key";
	}
    }
    
#    my $rooms = join(',',@grhr);    
#    print qq{The rooms Are: $rooms<br>\n};

    

    # Now find the enrollment changes for this month only.
    my (%changesMo, @addstud ); # addstud will update %student so we have students there at some time during month.

    my $sth1 = $dbh->prepare("select grade, homeroom from studentall where studnum = ?");
    
    my $sth = $dbh->prepare("select * from transfer 
     where month(date) = $month and year(date) = $year order by date desc");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $tref = $sth->fetchrow_hashref ) {
	my %t = %$tref;

	# Get Grade, Homeroom for this student
	$sth1->execute( $t{studnum} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ( $grade, $homeroom) = $sth1->fetchrow;
	if ( not $grade ) { next; } # skip if no grade found.
	if ( not $homeroom ) { 
	    $homeroom = 'none';
	    print "No Homeroom:$t{studnum} ID:$t{id}<br>\n";
	}

	if ( $t{type} eq 'withdraw' ) {
	    $changesMo{$grade}{$homeroom}{'wd'}++;
	} else {
	    $changesMo{$grade}{$homeroom}{'en'}++;
	    push @addstud, $t{studnum};
	}
    }
    # We now have all enrollment changes for the month 
    

    # Show Month
    print qq{<h1>$month[$month] $year</h>\n};

    # Show Days Open
    print qq{<h3>Global $lex{'Days Open'}:$daysopen };
    my %kdays;
    if ( %daysopennsd ) {
	# combine if possible
	foreach my $homeroom ( sort keys %daysopennsd ) {
	    my $dopen = $daysopennsd{$homeroom};
	    if ( $kdays{$dopen} ) { # append.
		$kdays{$dopen} .= ",$homeroom";
	    } else {
		$kdays{$dopen} = $homeroom;
	    }
	}
	print qq{<br>K/PK Days Open: };
	foreach my $dopen ( sort keys %kdays ) {
	    print "$kdays{$dopen} - $dopen Days<br>\n";
	}
	print qq{</h3>\n};
    }

    
    open(TEX,">$fileName") || die "Failed tex file open";

    # Set Sizes
    # Letter paper size is 279mm x 216mm
    # 200mm wide - 50mm name, 20mm extra fld, leaves 130mm for columns.
    # a4 paper is 297mm x 210mm; legal is 356mm x 216mm

    my $fontsize = $arr{fontsize}. 'pt';

    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;
    }
    delete $arr{papersize}; # no longer needed.

#    colortbl,helvet,
    print TEX "\\documentclass[$fontsize,$papersize,landscape]{article}
\\usepackage{array,inputenc,rotating,colortbl,helvet} 
\\usepackage[landscape]{geometry}
%$a_latex_header
\\renewcommand{\\familydefault}{\\sfdefault}
\\pagestyle{empty}
\\setlength{\\textwidth}{$textheight}
\\setlength{\\textheight}{$textwidth}
\\setlength{\\hoffset}{-25mm}
\\setlength{\\voffset}{-10mm}
\\setlength{\\parindent}{0pt}
\\setlength{\\tabcolsep}{5pt}
\\renewcommand{\\familydefault}{\\sfdefault}
\\setlength{\\extrarowheight}{6pt}\n";

    print TEX "\\begin{document}\n";
    print TEX "{\\LARGE\\sf $schoolname $title";
    print TEX "}\n\n\\medskip\n{\\Large\\sf  $month[$month] $year}\n\n";
    print TEX "\\hrulefill\n\\medskip\n\n";

    # Show Days Open
    print TEX "{\\bf Global $lex{'Days Open'}} $daysopen \\\\ \n";

    if ( %daysopennsd ) {
	print TEX "\\hspace{6mm}{\\bf K/PK Days Open} ";
	foreach my $dopen ( sort keys %kdays ) {
	    print TEX "$kdays{$dopen} - $dopen Days\\hspace{6mm}\n";
	}

	# foreach my $homeroom ( sort keys %daysopennsd ) {
	#    print TEX qq{\\hspace{6mm} {\\bf $homeroom}  $lex{'Days Open'} $daysopennsd{$homeroom}\n};
	#}
    }
    print TEX "\\\\\n\\hrulefill\\medskip\n\n";

    
    print TEX "\\begin{tabular}{|l";
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);
	print TEX "|c";
    }
    print TEX "|} \\hline\n\n";

    # Grade Headings
    print TEX qq{\\rowcolor[gray]{0.92} Grades };
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);
	print TEX "& $grade ";
    }
    print TEX "\\\\ \\hline\n\n";

    
    # Homeroom Headings
    print TEX qq{\\rowcolor[gray]{0.92} Homeroom };
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);
	if ( $homeroom eq 'none' ) { $homeroom = ' '; }
	print TEX "& $homeroom";
    }
    print TEX "\\\\ \\hline\n\n";

    
    # Start of Month enrollments
    my $totalstart;
    print TEX qq{Month Start };
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);
	print TEX "& $grRooms{$grade}{$homeroom} ";
	$totalstart += $grRooms{$grade}{$homeroom};
    }
    print TEX "\\\\ \\hline\n\n";


    # End of Month enrollments
    my $totalend;
    print TEX qq{Month End };
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);
	
	my $enrol = $changesMo{$grade}{$homeroom}{'en'};
	my $withdraw = $changesMo{$grade}{$homeroom}{'wd'};
	my $students = $grRooms{$grade}{$homeroom} + $enrol - $withdraw;
	$totalend += $students;
	print TEX "& $students ";
    }
    print TEX "\\\\ \\hline\n\n";


    # Additions
    my $totalenrol;
    print TEX qq{Enrolled};
    
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);

	my $enrol = $changesMo{$grade}{$homeroom}{'en'};
	my $withdraw = $changesMo{$grade}{$homeroom}{'wd'};
	my $students = $grRooms{$grade}{$homeroom} + $enrol - $withdraw;
	$totalenrol += $enrol;
	print TEX "& $enrol ";
    }
    print TEX "\\\\ \\hline\n\n";


    # Withdraw
    my $totalwd;
    print TEX qq{Withdraw};
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);
	
	my $enrol = $changesMo{$grade}{$homeroom}{'en'};
	my $withdraw = $changesMo{$grade}{$homeroom}{'wd'};
	my $students = $grRooms{$grade}{$homeroom} + $enrol - $withdraw;
	$totalwd += $withdraw;
	    
	print TEX "& $withdraw ";
    }
    print TEX "\\\\ \\hline\n\n";


    # Now do attendance rows. Total Pupil Days Attended / Total Pupil Days Enrolled.
    # Loop through all students, set enrolled and attended.
    my (%enrol, %attend); #  %enrol{grade}{homeroom} = count of total pupil days.
    foreach my $key ( keys %attend ) {
	delete $attend{$key};
    }

    # For finding attendance via calcMonthlyAttendance, below
    my %lexi = ('Absent' => 'Absent',
		'Late' => 'Late');

    
    my $sth = $dbh->prepare("select grade, homeroom from studentall where studnum = ?");

    my ($totaldayenrol, $totaldayattend);

    
    # Add to %students (which has studnums for students at start of
    # the month), for other students who enrolled at some time during
    # the month.
    foreach my $studnum ( @addstud ) {
	$students{$studnum} = 1;
    }
    # we now have all students in %students that were enrolled during the month.
    

    foreach my $studnum ( keys %students ) {

	# Get their grade and homeroom
	$sth->execute( $studnum ) ;
        if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($grade, $homeroom) = $sth->fetchrow;

	my $ppd = $g_ppd{ $grade };
	if ( not $ppd ) {
	    print qq{<h4>$lex{Missing} Attendance $lex{'Periods Per Day'} - };
	    print qq{$lex{Grade} $grade Student $studnum</h4>\n}; 
	}

	# get enrollment
	my $ref;
	if ( $grade eq 'K' or $grade eq 'PK' ) {
	    $ref = calcMonthlyEnrollment( $studnum, $startdate, $enddate, $dbh, $homeroom);

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

	# Check for attendance entry errors outside enrollments (ALL YEAR)
#	my $ret = checkAttendanceOutsideEnrollment( $studnum, $schoolstart, $schoolend, $dbh);

	
	my $schooldays = $ref->{$yearmonth}->{'days'};
#	print "Student:$studnum Enrolled Days:$schooldays Grade:$grade Homeroom:$homeroom<br>\n";
	
	if ( not $schooldays ) { next; } #student

	$enrol{$grade}{$homeroom} += $schooldays; # add days enrolled to this.
	$totaldayenrol += $schooldays; # total pupil-days enrolled

	# get attendance
	my $result = calcMonthlyAttendance( $studnum, $yearmonth, $ppd, '',\%lexi, $dbh ); # no end date req'd.
	my ($absent, $late) = split(':', $result);
	
	my $dayspresent = $schooldays - $absent;
	
	$attend{$grade}{$homeroom} += $dayspresent;
	$totaldayattend += $dayspresent;

#	if ( $homeroom eq '101' ) {
#	    print qq{SN:$studnum Homeroom:$homeroom Grade:$grade Enrolled:$schooldays \n};
#	    print qq{Present:$dayspresent Absent:$absent Totals: $attend{$grade}{$homeroom} - $enrol{$grade}{$homeroom}<br>\n};
#	}
	
    }
    # We now have total pupil-days enroll and pupil-days attended in %attend and %enrol for each room.

    
    # Pupil Days Enrolled
    print TEX qq{Days Enrolled};
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);
	print TEX "& $enrol{$grade}{$homeroom} ";
    }
    print TEX "\\\\ \\hline\n\n";
    

    # Pupil Days Attended
    print TEX qq{Days Attended};
    foreach my $val ( @grhr ) {
	my ($grade, $homeroom) = split(':', $val);
	    print TEX "& $attend{$grade}{$homeroom} ";
    }
    print TEX "\\\\ \\hline\n\n";

    
    # Percentage Attendance
    print TEX qq{\\rowcolor[gray]{0.92} Percent Attendance};
    foreach my $grade ( sort {$a <=> $b} keys %grRooms ) {
	foreach my $homeroom ( sort keys %{ $grRooms{$grade}} ) {

	    my $enrol = $enrol{$grade}{$homeroom};
	    my $attend = $attend{$grade}{$homeroom};
	    my $percent = 0;
	    if ( $enrol ) {
		$percent = round(100 * $attend / $enrol, 1);
	    }
	    
	    print TEX "& $percent\\% ";
	}
    }

    print TEX "\\\\ \\hline\n\n";
    print TEX "\\end{tabular}\n\n";
    print TEX "\\medskip\n\n";
    
    # Now do the total table.
    print TEX qq{\\begin{tabular}{|l|l|} \\hline\n};
    print TEX qq{Students at Start of Month&$totalstart \\\\ \\hline\n};
    print TEX qq{Students at End of Month & $totalend \\\\ \\hline\n};
    print TEX qq{Students Enrolled during Month & $totalenrol \\\\ \\hline\n};
    print TEX qq{Students Withdrawn during Month & $totalwd \\\\ \\hline\n};
    print TEX qq{Total Pupil Days Enrolled & $totaldayenrol \\\\ \\hline\n};
    print TEX qq{Total Pupil Days Attended & $totaldayattend \\\\ \\hline\n};

    my $percent = 0;
    if ( $totaldayenrol ) {
	$percent = round(100 * $totaldayattend / $totaldayenrol, 1);
    }

    print TEX qq{Percentage Attendance & $percent\\% \\\\ \\hline\n};
    print TEX qq{\\end{tabular}\n};

    if ( $principalSign ) {
	print TEX "\n\\vspace{10mm}\n\\medskip\n\\underline{\\hspace{3in}}\n\n";
	print TEX "{\\footnotesize $lex{Principal} }\n\n";
    }

    print TEX "\\end{document}\n";
    close TEX;

    system("$pdflatex $fileName >pdflog$$.txt");
    system("mv $shortname.pdf $downloaddir");
    system("mv pdflog$$.txt $downloaddir");
    system("rm -f $shortname.*");

    print qq{<h1><a href="$webdownloaddir/$shortname.pdf">\n};
    print qq{$lex{'View/Download'} $lex{'Monthly Enrollment'} $lex{Report}</a></h1>\n};
    print qq{[ <a href="$webdownloaddir/pdflog$$.txt">$lex{'View Log File'}</a> |\n};
    print qq{<a href="$homepage">$lex{Main}</a> ]\n};
    print qq{</body></html>\n};

    exit;
}
    

#-----------------------------------
sub checkAttendanceOutsideEnrollment {  # check errors in the current school year (schoolstart,schoolend)
#-----------------------------------

    use Time::JulianDay;

    # Passed: student number, start and end dates for period of interest.
    my ( $studnum, $startdate, $enddate, $dbh, $nsdhomeroom ) = @_; # same as findEnrollmentBlocks

    # find enrollment blocks for this time period
    my @enrolblocks = findEnrollmentBlocks( $studnum, $startdate,$enddate, $dbh );


    if ( not $enrolblocks[0] ) { # print "No Enrollment for $studnum<br>\n"; 
	return undef; 
    }

    # Loop through each enrollment block
    my @blockjd; 
    foreach my $ref ( @enrolblocks ) {
	my $startdate = $ref->{start};
	my $enddate = $ref->{end};

#	print "Studnum:$studnum Start:|$startdate| End:|$enddate|<br>\n";

	my $startjd = julian_day( split('-', $startdate) );
	my $endjd = julian_day( split('-', $enddate) );

	push @blockjd, "$startjd:$endjd";
    }

    my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    
    my $errorflag;
    # now loop through attendance for this student to see if any absences records outside enrollment blocks.
    my $sth = $dbh->prepare("select absdate from attend where studentid = ? and 
       absdate is not NULL and absdate != '0000-00-00' order by absdate");
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    while ( my $absdate = $sth->fetchrow ) {
	my $absjd = julian_day( split('-', $absdate) );
	
	foreach my $bval ( @blockjd ) {
	    my ($start,$end) = split(':', $bval);
	    if ( $absjd < $start or $absjd > $end ) { # error
		if ( $errorflag ) {
		    print qq{, $absdate };
		} else {

		    # Get Name;
		    $sth1->execute( $studnum );
		    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		    my ($lastname, $firstname) = $sth1->fetchrow;
		    
		    print qq{<div><b>Student $lastname $firstname ($studnum) Attendance Error -};
		    print qq{ Outside Enrollment</b> - $absdate\n};
		    $errorflag = 1;
		}
		
	    }
	}
    }
    
    print qq{</div>\n};
	
    return;

}
    
