#!/usr/bin/perl
#  Copyright 2001-2023 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.

my %lex = ('Error' => 'Error',
	   'Main' => 'Main',
	   'Attendance' => 'Attendance',
	   'Attendance Date' => 'Attendance Date',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Attendance Entry' => 'Attendance Entry',
	   'Periods per Day' => 'Periods per Day',
	   'Submit Attendance' => 'Submit Attendance',
	   'Reason' => 'Reason',	   
	   'Student' => 'Student',
	   'Per' => 'Per',
	   'Period(s)' => 'Period(s)',
	   'Period' => 'Period',
	   'Late' => 'Late',
	   'None' => 'None',
	   'More' => 'More',
	   'Records Stored' => 'Records Stored',
	   'Attendance Reasons' => 'Attendance Reasons',
	   'Skipping' => 'Skipping',
	   'Not Found' => 'Not Found',
	   'Missing' => 'Missing',
	   'Today' => 'Today',
	   'Day In Cycle' => 'Day In Cycle',

	   );

my $self = 'attaddall.pl';
my $adminuser = 'admin';

use DBI;
use CGI;
use Time::JulianDay;

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

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

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




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


my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);


# Set Date
my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
my $day = @tim[3];
my $currdate = "$year-$month-$day";
my $currjd = julian_day(split('-',$currdate));
my $dow = day_of_week($currjd);
if ( $dow == 6 ) { # Saturday
    $currjd = $currjd - 1; # make it Friday.
    my ($year,$month,$day) = inverse_julian_day($currjd);
    $currdate = "$year-$month-$day";
}
if ( $dow == 0 ) { # Sunday
    $currjd = $currjd - 2; # make it Friday.
    my ($year,$month,$day) = inverse_julian_day($currjd);
    $currdate = "$year-$month-$day";
}

$dow = day_of_week($currjd); # just in case it was updated.
my $currdate1 = "$month[$month] $day, $year";


my $title = $lex{'Attendance Entry'};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{<style>span.bcn {text-align:center;font-weight:bold;}</style>\n};

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="margin:1em 3em;">\n};

print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{ <a href="$attpage">$lex{Attendance}</a> ] $currdate1\n};
print qq{<h1>$title</h1>\n};


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

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

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    doCourseAttendance();

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    writeRecords();
}


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

    # Select distinct homerooms and then find teachers for those homerooms (and do homeroom attendance)
    my %hroom;
    my $sth = $dbh->prepare("select distinct homeroom, grade from student");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($hr, $gr) = $sth->fetchrow ) {
	if ( not $hr ) { next; }
	# skip any homerooms that do subject attendance, anyway.
	if ( $g_AttendanceEntryMethod{$gr} eq 'subject' ) { next; }
	$hroom{$hr}{$gr} = 1;
    }

    my %homeroomteacher, %teacherHR;
    my $sth = $dbh->prepare("select userid from staff_multi where field_name = 'homeroom'
			    and field_value = ?"); 
    
    foreach my $hr ( keys %hroom ) {
	$sth->execute($hr);
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $userid = $sth->fetchrow; # only one teacher per homeroom.
	$homeroomteacher{$hr} = $userid; # teachers per homeroom are unique.
	$teacherHR{$userid} = 1; # just that they teach a homeroom for duplicate checking below
    }

    
    # Find subject/course teachers
    my %teacherCRS;
    my $sth = $dbh->prepare("select distinct teacher, subjsec, grade from subject");
    my $sth1 = $dbh->prepare("select count(*) from eval where subjcode = ?");

    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while (my ($userid, $subjsec, $grade) = $sth->fetchrow ) {

	# Skip, if course is a grade with homeroom attendance
	if ( $g_AttendanceEntryMethod{$grade} eq 'homeroom' ) { next; }
	
	# check for any course enrollments;
	$sth1->execute( $subjsec );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $enrolcount = $sth1->fetchrow;

	# Skip, if no enrollments
	if (not $enrolcount ) { next; }

	$teacherCRS{$userid} = 1;
    }


    
    # Get Teachers Name, setup sorting.
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    my (%tchName, %sortCRS, %sortHR);
    foreach my $userid ( keys %teacherCRS ) {
	$sth->execute( $userid );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;
	$tchname{$userid} = qq{$lastname, $firstname};
	$sortCRS{"$lastname$firstname$userid"} = $userid;
    }

    foreach my $userid ( keys %teacherHR ) {
	$sth->execute( $userid );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;
	$tchname{$userid} = qq{$lastname, $firstname};
	$sortHR{"$lastname$firstname$userid"} = $userid;
    }

    
    
    # Teacher Homeroom Entry    
    # Start Homeroom Form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    
    # Table and Heading
    print qq{<table cellpadding="3" border="0" cellspacing="0" };
    print qq{style="float:left;border:1px solid gray;margin:0.5em;padding:0.5em;">\n\n};
    print qq{<tr><th colspan="3">$lex{'Homeroom'} $lex{'Attendance Entry'}</th></tr>\n};
    my $count = 0;

    if ( not %homeroomteacher ) {
	print qq{<tr><td style="font-size:120%;font-weight:bold;">};
	print qq{No Homeroom Teacher Entry</td></tr>\n};
	print qq{</table></form>\n};
	
    } else {
    
	# Show Date
	print qq{<tr><td colspan="3" style="font-size:120%;">$lex{'Attendance Date'} };
	print qq{<input type="text" name="date" id="HRdate" style="width:10ch;" value="$currdate">\n};
	print qq{<button type="reset" id="HRstart_trigger">...</button> $dowstd[$dow]</td></tr>\n\n};

	# Loop over teachers.
	foreach my $homeroom ( sort {$a <=> $b} keys %homeroomteacher ) {
	    my $userid = $homeroomteacher{$homeroom};
	    my $name = $tchname{$userid};

	    print qq{<tr><td><input type="submit" name="$userid" };
	    print qq{value="$homeroom - $name"></td></tr>\n};

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

	print qq{<script type="text/javascript">
         Calendar.setup({
        inputField     :    "HRdate", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "HRstart_trigger", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // show all years in drop-down boxes 
         })};

	print qq{</script>\n};
	print qq{</form>\n\n};
    }

    
    # Course Entry
    if ( not %teacherCRS ) {

	# Start Table
	print qq{<br clear="left">\n};
	print qq{<table cellpadding="3" border="0" cellspacing="0" };
	print qq{style="float:left;border:1px solid gray;margin:0.5em;padding:0.5em;">\n\n};
	print qq{<tr><th colspan="3">Course $lex{'Attendance Entry'}</th></tr>\n\n};
	print qq{<tr><td style="font-size:120%;font-weight:bold;">No Course Teacher Entry</td></tr>\n};
	print qq{</table>\n};
    
	print qq{</body></html>\n};
	exit;
	
    } # otherwise go on....
    
    
    # Start Form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};


    # Start Table
    print qq{<table cellpadding="3" border="0" cellspacing="0" };
    print qq{style="float:left;border:1px solid gray;margin:0.5em;padding:0.5em;">\n\n};
    print qq{<tr><th colspan="3">Course $lex{'Attendance Entry'}</th></tr>\n\n};

    # Date
    print qq{<tr><td colspan="3" style="font-size:120%;">$lex{'Attendance Date'} };
    print qq{<input type="text" name="date" id="date" style="width:10ch;" value="$currdate">\n};
    print qq{<button type="reset" id="start_trigger">...</button> $dowstd[$dow]</td></tr>\n\n};

    
    foreach my $key ( sort keys %sortCRS ) {
	my $userid = $sortCRS{$key};
	my $name = $tchname{$userid};
	
	print qq{<tr><td><input type="submit" name="$userid" };
	print qq{value="$name ($userid)"></td></tr>\n};

    }

    print qq{</table></form>\n\n};
    # End of course Attendance Entry


    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "date", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "start_trigger", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // show all years in drop-down boxes 
    })};

    print qq{</script>\n};

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

}



#-----------------------
sub doHomeroomAttendance {
#-----------------------

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

    my $date = $arr{date};
    delete $arr{date};
    my @tmp = keys %arr;
    my $userid = $tmp[0]; # yes, it's ugly...
    
#    print "Date:$date Userid:$userid<br>\n";

    # Calculate DOW (Day of Week)
#    use Time::JulianDay;  # already loaded above
    my $jd = julian_day( split('-', $date));
    my $dow = day_of_week($jd);
    # used next line with @dowstd array (0 is Sunday).

    
    # Check for date within school year; vars are global from admin.conf
    my $startjd = julian_day( split('-', $schoolstart));
    my $endjd = julian_day( split('-', $schoolend));
    if ( $jd > $endjd or $jd < $startjd ) {
	print qq{<h3>Error: Date is outside the school year!</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    print qq{<div style="font-size:140%;">$lex{'Attendance Date'} <b>$dowstd[$dow], $date</b></div>\n};


    # Check for Full Day School Closure
    my $sth = $dbh->prepare("select id, dayfraction, type from dates where date = ?");
    $sth->execute( $date );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ( $id, $dayfraction, $type ) = $sth->fetchrow; # type may be 'onlinelearning';
    if ( $id and $dayfraction > 0.99 ) { # closed all day.
	print qq{<h3 style="color:#C00;">School is closed all day!</h3>\n};
	print qq{</html></body>\n};
	exit;
    }

    # GRADE Periods Closed from dates_periods table.
    my %pclosed;
    if ( $type ne 'onlinelearning' ) {
	my $ref = parseGradesPeriod( $date, $dbh);
	%pclosed = %$ref;
    }
    
    # $pclosed{grade}{period} load from dates_period

    # print "pclosed<br>";
    #foreach my $grade ( sort {$a <=> $b} keys %pclosed ) {
    #	foreach my $period ( sort keys %{ $pclosed{$grade} } ) {
    #	    print qq{Grade:$grade Period:$period<br>\n};
    #} }
    
    
    # Load homeroom values for days/part days closed for this date.
    my %closedHR; # homeroom
    my $sth = $dbh->prepare("select * from dates_homeroom where date = ?");
    $sth->execute( $date );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;
	$closedHR{ $r{homeroom} }{ $r{period }} = $r{closuretype};
    }

    
    # Start of Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="hidden" name="mode" value="homeroom">\n};
    print qq{<input type="hidden" name="userid" value="$userid">\n};
    print qq{<input type="hidden" name="date" value="$date">\n};

    
    # Get homerooms! for this userid
    my $sth = $dbh->prepare("select field_value from staff_multi as sm, staff as s
      where sm.field_name = 'homeroom' and sm.userid = s.userid and s.userid = ?
      order by sm.field_value");
    $sth->execute( $userid );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my @homerooms;

    
    while ( my $homeroom = $sth->fetchrow ) {
	push @homerooms, $homeroom;

	# Find largest PPD for this homeroom
	my ($maxppd, @grades); # @grades only needed for perfect attendance line.
	my $sth1 = $dbh->prepare("select distinct grade from student where homeroom = ?");
	$sth1->execute( $homeroom );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $grade = $sth1->fetchrow ) {
	    push @grades, $grade;
	    if ( $g_ppd{$grade} > $maxppd ) {
		$maxppd = $g_ppd{$grade};
	    }
	}
	if ( not $maxppd ) {
	    print qq{<h3>$lex{'Periods per Day'} $lex{'Not Found'} - $lex{Homeroom}: $homeroom</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
	#print qq{Maxppd: $maxppd<br>\n};


	# Select students from homeroom
	$sth1 = $dbh->prepare("select lastname, firstname, studnum, grade from student 
          where homeroom = ? order by lastname, firstname");
	$sth1->execute( $homeroom );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }


	print qq{<h1>$lex{Homeroom} $homeroom</h1>\n};
	print qq{<p><input type="submit" value="$lex{'Submit Attendance'}"></p>\n};
	print qq{<table cellpadding="3" cellspacing="0" border="1">\n};  

	print qq{<tr><th>$lex{Student}</th><th>};
	for my $p ( 1..$maxppd ) {
	    print qq{$lex{Per} $p</th><th>};
	}
	print qq{$lex{Reason}</th><th>$lex{Late}</th></tr>\n};

	# Perfect Attendance Line.
	print qq{<tr style="background-color:#DDD;">};
	print qq{<td style="background-color:#DDD;font-weight:bold;font-size:120%;">};
	print qq{Perfect Attendance</td>\n};
	for my $p ( 1..$maxppd ) {
#	    print qq{HR: $closedHR{$homeroom}{$p} PCLOSED $pclosed{$grades[0]}{$p}<br>\n};
	    
	    if ( $closedHR{$homeroom}{$p} eq 'closed' or $pclosed{$grades[0]}{$p} ) { 
		print qq{<td>C</td>\n}; 
	    } else {
		print qq{<td><input type="checkbox" name="PA:$homeroom:$p" value="1"></td>\n};
	    }
	}
	print qq{<td></td><td></td></tr>\n};

	
	while ( my ( $lastname, $firstname, $studnum, $grade ) = $sth1->fetchrow ){

	    print qq{<tr><td><b>$lastname</b>, $firstname</td>\n};
	    for my $p ( 1..$maxppd ) {
		if ( $closedHR{$homeroom}{$p} eq 'closed' or $pclosed{$grade}{$p} ) { 
		    print qq{<td>C</td>\n}; 
		} else {
		    print qq{<td><input type="checkbox" name="$studnum:$homeroom:$p" value="1"></td>\n};
		}
	    }
	    print qq{<td><select name="$studnum:Reason"><option value=""></option>\n};
	    
	    foreach my $reason ( @attend ) {
		print qq{<option>$reason</option>\n};
	    }
	    print qq{<option value=""></option></select></td>\n<td>};
	    print qq{<input type="text" name="$studnum:Late" size="4"></td></tr>\n};

	}

	print qq{</table>\n};


    } # end of homeroom loop

    print qq{<p><input type="submit" value="$lex{'Submit Attendance'}"></p>\n};
    print qq{</form>\n};

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

    exit;

}


#----------------------
sub doCourseAttendance {
#----------------------

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

    my ( $date, $userid ); # only 2 values passed BUT NOT $arr{userid}, thus gunk below
    foreach my $key ( keys %arr ) {
	if ( $key eq 'date' ) {
	    $date = $arr{$key};
	} else {
	    $userid = $key;
	}
    }
     
        
    # Find Day in Cycle
    my $day = findDayInCycle( $date, $dbh );

    # Calculate DOW (Day of Week)
    use Time::JulianDay;
    my $jd = julian_day( split('-', $date));
    my $dow = day_of_week($jd);
    # used next line with @dowstd array (0 is Sunday).
    
    # show Date
    print qq{<div style="font-size:130%;padding:0 0 0 1em;">};
    print qq{<b>$lex{'Attendance Date'}:</b> $date <i>$dowstd[$dow]</i>};
    print qq{<br><b>$lex{'Day In Cycle'}:</b> $day</div>\n};


    # Check for Full Day School Closure
    my $sth = $dbh->prepare("select id, dayfraction, type from dates where date = ?");
    $sth->execute( $date );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ( $id, $dayfraction, $type ) = $sth->fetchrow; # type may be 'onlinelearning';
    if ( $id and $dayfraction > 0.99 ) { # closed all day.
	print qq{<h3 style="color:#C00;">School is closed all day!</h3>\n};
	print qq{</html></body>\n};
	exit;
    }

    # GRADE periods Closed from dates_periods table.
    my %pclosed;
    if ( $type ne 'onlinelearning' ) {
	my $ref = parseGradesPeriod( $date, $dbh);
	%pclosed = %$ref;
    }

    # $pclosed{grade}{period} load from dates_period

#    print "pclosed<br>";
#    foreach my $grade ( sort {$a <=> $b} keys %pclosed ) {
#	foreach my $period ( sort keys %{ $pclosed{$grade} } ) {
#	    print qq{Grade:$grade Period:$period<br>\n};
#	}
#    }

    
    # Start of Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="hidden" name="mode" value="subject">\n};
    print qq{<input type="hidden" name="date" value="$date">\n};
    print qq{<input type="hidden" name="userid" value="$userid">\n};
    
    
    # Find Current courses for this teacher.
    my %subjects = findCurrentSubjects( $userid, $date, $dbh );

    my %sort;
#    print qq{Courses:<br>\n}; # %subjects{subjsec} = space separated periods.
    foreach my $key ( sort keys %subjects ) {
#	print "K:$key VAL:$subjects{$key}<br>\n";
	
	my @periods = sort {$a <=> $b} split(/\s+/, $subjects{$key});
	my $startperiod = $periods[0];

	$sort{"$startperiod/$key"} = $key;
	
    }


    my $sth= $dbh->prepare("select description, smdesc, grade from subject where subjsec = ?");
    my $subjcount;

    my $first = 1;
    foreach my $key ( sort keys %sort ) {

	my $subjsec = $sort{$key};

	# print qq{Period: $subjects{$subjsec}<br>\n};
	
	if ( $first ) {
	    print qq{<div style="margin:1em 0 0 1em;">};
	    print qq{<input type="submit" value="$lex{'Submit Attendance'}"></div>\n};
	    $first = 0;
	}
	
	# Get Course Information
	$sth->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ( $description, $smdesc, $grade ) = $sth->fetchrow;

	if ( not $subjects{$subjsec} ) { # no periods today
	    print qq{<h3>$description ($subjsec) $lex{Today}: $lex{'Not Found'}</h3>\n};
	    next;
	}


	# Get PPD for this subject based on grade value in subject.
	my $ppd = $g_ppd{ $grade };
	if ( not $ppd ) { 
	    print qq{<br clear="left">\n<h3>$lex{Missing} $lex{Grade}: $description ($subjsec)</h3>\n};
	}

	# Get the Kids first... studnums.
	$sth1 = $dbh->prepare("select distinct s.studnum, s.lastname, s.firstname, s.homeroom
          from eval as e, student as s where  subjcode = ? and e.studnum = s.studnum
          order by s.lastname, s.firstname");
	$sth1->execute( $subjsec );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	# Print Start of Course Entry Table
	$subjcount++;
	if ( $subjcount % 2 ) { print qq{<br clear="left">\n}; }

	print qq{<table cellpadding="3" border="1" cellspacing="0" };
	print qq{style="float:left; margin:0 1em 1em 1em;vertical-align:top;">\n};
	print qq{<tr><th colspan="4" style="font-size:130%;">$description ($subjsec)</th></tr>\n};
	print qq{<tr><th>$lex{Student}</th><th>$lex{'Period(s)'}};
	print qq{</th><th>$lex{Reason}</th><th>$lex{Late}</th></tr>\n};


	# return values in %subjects is periods
	my @periods = sort {$a <=> $b} split(/\s/, $subjects{$subjsec} );

	
	# Perfect Attendance Line.
	print qq{<tr style="background-color:#DDD;">};
	print qq{<td style="background-color:#DDD;font-weight:bold;font-size:120%;">};
	print qq{Perfect Attendance</td><td>\n};
	foreach my $p ( @periods ) {
	    print qq{$lex{Per}$p };
	    if ( $pclosed{$grade}{$p} ) { 
		print qq{<span title="Closed" class="bcn">CL</span>\n};

	    } else {
		print qq{<input type="checkbox" name="PA:$subjsec:$p" value="1">\n};
	    }
	}
	print qq{</td><td></td><td></td></tr>\n};

	# Loop Through Students
	while ( my ( $studnum, $lastname, $firstname, $homeroom ) = $sth1->fetchrow ) {

	    if ( not $lastname ){  # student name not found.
		$lastname = qq{<span style="color:red;">$lex{Student} $lex{'Not Found'}</span>};
	    }

	    # Name
	    print qq{<tr><td><b>$lastname</b>, $firstname };
	    if ( $homeroom ) { print qq{($homeroom)}; }
	    print qq{</td><td>\n};

	    # Periods
	    if ( @periods ) {
		for my $p ( @periods ) {
		    print qq{$lex{Per} $p };
		    if ( $pclosed{$grade}{$p} ) { 
			print qq{<span title="Closed" class="bcn">CL</span>\n};
		    } else {
			print qq{<input type="checkbox" name="$studnum:$subjsec:$p" value="1">};
		    } 
		}
	    } else { # not scheduled, so let them pick a period to do.
		for my $p ( 1..$ppd ){
		    print qq{$lex{Per} $p };
		    if ( $pclosed{$grade}{$p} ) { 
			print qq{<span title="Closed" class="bcn">CL</span>\n};
		    } else {
			print qq{<input type="checkbox" name="$studnum:$subjsec:$p" value="1">};
		    }
		}
	    }

	    # Show Reason
	    print qq{</td><td><select name="$studnum:$subjsec:Reason"><option value=""></option>\n};
    	    foreach my $reason ( @attend ){
		print qq{<option>$reason</option>\n};
	    }
	    print qq{</select></td>};
	    print qq{<td><input type="text" name="$studnum:$subjsec:Late" size="4"></td></tr>\n};

	}

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


    } # Outer Loop here for each subject.

    print qq{<br clear="left">\n};
    print qq{<div style="margin:0 1em;"><input type="submit" value="$lex{'Submit Attendance'}"></div>\n};
    print qq{</form>\n}; # end the form.

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

    exit;

}


#------------------
sub writeRecords {
#------------------

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

    my $mode = $arr{mode};  # subject or homeroom attendance
    delete $arr{mode};
    my $date = $arr{date};
    delete $arr{date};
    my $userid = $arr{userid};
    delete $arr{userid};
    
    # Calculate DOW (Day of Week)
    my $jd = julian_day( split('-', $date));
    my $dow = day_of_week($jd);
    # used next line with @dowstd array (0 is Sunday).

    print qq{<div style="font-size:140%;">$lex{'Attendance Date'} $date  <b>$dowstd[$dow]</b></div>\n};

    # Check for any Perfect Attendance Records;
    my %patt; # perfect attendance  $patt{period}{hr/subj}
    foreach my $key ( keys %arr ) {
	if ( $arr{$key} ) { # we have to have a value.
	    my ($type,$hr,$p) = split(':', $key);  # hr may also be subjsec.
	    if ( $type eq 'PA' ) {
		$patt{$p}{$hr} = 1;
		delete $arr{$key}; # remove PA entries.
	    }
	}
    }

#    foreach my $p ( sort keys %patt ) {
#	foreach my $hr ( sort keys %{ $patt{$p} } ) {
#	    print qq{P:$p HR/SUB:$hr<br>\n}; }  }

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

    my $sth1 = $dbh->prepare("select lastname, firstname from student where studnum = ?");
    my $sth2 = $dbh->prepare("select description from subject where subjsec = ?");
    my $sth3 = $dbh->prepare("select count(*) from attend 
      where absdate = ? and studentid = ? and period = ?"); # attendance  duplicate check.
    my $sth6 = $dbh->prepare("select count(*) from tattend 
      where attdate = ? and subjects = ? and periods = ?"); # teacher attendance duplicate check.


    # Attendance Insert
    my $sth4 = $dbh->prepare("insert into attend (studentid, absdate, reason, period, subjsec, late)
      values ( ?,?,?,?,?,? )");


    my $first = 1;
	    
    if ( $mode eq 'subject' ) {

	my %subjperiods; # subjperiods{subjsec}{period}

	foreach my $key ( sort keys %arr ) {

	    

	    if ( $arr{$key} ) {  # if we have a value

		if ( $first ) {
		    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
		    print qq{<tr><th>$lex{Student}</th><th>Course</th><th>$lex{Period}</th><th>};
		    print qq{$lex{Reason}</th><th>$lex{Late}</th></tr>\n};
		    $first = 0;
		}

		
		my ( $studnum, $subjsec, $period );
		( $studnum, $subjsec, $period ) = split(':', $key );
		if ( not $period or $period =~ m/\D/ ) { next; } # skip if blank, or has text value

		# Capture Teacher periods and subjects.
		$subjperiods{$subjsec}{$period} = 1;

		my $reason = $arr{ "$studnum:$subjsec:Reason" };
		my $late = $arr{ "$studnum:$subjsec:Late" };

		# Get Student Name 
		$sth1->execute( $studnum );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		my ( $lastname, $firstname ) = $sth1->fetchrow;

		# Get Description
		$sth2->execute( $subjsec );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		my $description = $sth2->fetchrow;

		if ( not $reason ) {
		    print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>};
		    print qq{$description ($subjsec)</td><td>$period</td><td colspan="2"};
		    print qq{ style="color:red;">$lex{'Attendance Reasons'} $lex{'Not Found'}};
		    print qq{ $lex{'Skipping'}</td></tr>\n};
		    next;
		}


		# Check for an existing record for this date, student, period.
		$sth3->execute( $studnum, $date, $period );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		my $count = $sth3->fetchrow;
		if ( $count ) {
		    print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>};
		    print qq{$description ($subjsec)</td><td>$period</td><td colspan="2"};
		    print qq{ style="color:red;">A Record already exists!\n};
		    print qq{ $lex{'Skipping'}</td></tr>\n};
		    next;
		}

		if ( not $late ) { undef $late; }
		
		# Insert the Record
		$sth4->execute( $studnum, $date , $reason, $period, $subjsec,$late );
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

		# Show Result
		print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>};
		print qq{$description ($subjsec)</td><td>$period</td><td>$reason</td>};
		print qq{<td>$late</td></tr>\n};

	    } # end, if we have a value
	} # end of for loop for each key


	if ( %subjperiods or %patt ) { # Insert tattend record

	    my $sth5 = $dbh->prepare("insert into tattend 
             ( userid, attdate, currdate, subjects, periods )
              values ( ?,?,now(),?,? )");

	    foreach my $subjsec ( keys %subjperiods ) {
		foreach my $period ( keys %{ $subjperiods{$subjsec} } ) {
		    # check for duplicates
		    $sth6->execute( $date, $subjsec, $period);
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		    my $count = $sth6->fetchrow;
		    if ( $count ) { next; }
		    # Insert record.
		    $sth5->execute( $userid, $date, $subjsec, $period);
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		} # period loop
	    } # course loop

	    foreach my $period ( keys %patt ) {
		foreach my $subjsec ( keys %{ $patt{$period} } ) {
		    # check for duplicates
		    $sth6->execute( $date, $subjsec, $period);
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		    my $count = $sth6->fetchrow;
		    if ( $count ) { next; }
		    # Insert record
		    $sth5->execute( $userid, $date, $subjsec, $period);
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		}
	    }
	    
	}


    } elsif ( $mode eq 'homeroom' ) {  # homeroom method

	my %periods;

	foreach my $key ( sort keys %arr ) {

	    if ( $arr{$key} ) {

		if ( $first ) {
		    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
		    print qq{<tr><th>$lex{Student}</th><th>Course</th><th>$lex{Period}</th><th>};
		    print qq{$lex{Reason}</th><th>$lex{Late}</th></tr>\n};
		    $first = 0;
		}


		my ( $studnum, $subjsec, $period, $reason, $late );
		( $studnum, $hr, $period ) = split(':', $key );
		# skip if any text value or no value in $period fld.
		if ( not $period or $period =~ m/\D/ ) { next; } 

		if ( $patt{$period}{$hr} ) { # Error!
		    print qq{<tr><td colspan="6">Error: Absence attempted for Perfect Attendance };
		    print qq{Period: $period</td></tr>\n};
		    next;
		}

		my $reason = $arr{ "$studnum:Reason" };
		my $late = $arr{ "$studnum:Late" };

		# Get Student Name
		$sth1->execute( $studnum );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		my ( $lastname, $firstname ) = $sth1->fetchrow;

		
		if ( not $reason ) {
		    print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>};
		    print qq{$description ($subjsec)</td><td>$period</td><td colspan="2"};
		    print qq{ style="color:red;">$lex{'Attendance Reasons'} $lex{'Not Found'}};
		    print qq{ $lex{'Skipping'}</td></tr>\n};
		    next;
		}

		# Check for an existing record for this date, student, period.
		$sth3->execute( $studnum, $date, $period );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		my $count = $sth3->fetchrow;
		if ( $count ) {
		    print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>};
		    print qq{$description ($subjsec)</td><td>$period</td><td colspan="2"};
		    print qq{ style="color:red;">A Record already exists!\n};
		    print qq{ $lex{'Skipping'}</td></tr>\n};
		    next;
		}

		
		# Capture Teacher periods
		$periods{$period}{$hr} = 1;

		
		# Insert the Record
		my $subjsec = qq{HR:$hr}; # just a homeroom code value
		$sth4->execute( $studnum, $date, $reason, $period, $subjsec, $late );
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

		# Show Result
		print qq{<tr><td class="la">$lastname</b>, $firstname ($studnum)</td>};
		print qq{<td>$lex{None}</td><td>$period</td><td>$reason</td><td>$late</td></tr>\n};

	    } # end, if value
	} # end, for loop for each key

	if ( %periods or %patt ) { # Insert tattend record (subject, homeroom done above)
	    my $sth5 = $dbh->prepare("insert into tattend 
             ( userid, attdate, currdate, subjects, periods )
               values ( ?,?,now(),?,? )");

	    foreach my $period ( sort keys %periods ) {
		foreach my $hr ( sort keys %{ $periods{$period} } ) {
		    my $subject = "HR:$hr";

		    # check for duplicates
		    $sth6->execute( $date, $subject, $period);
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		    my $count = $sth6->fetchrow;
		    if ( $count ) { next; }
		    
		    $sth5->execute( $userid, $date, $subject, $period);
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		}
	    }

	    foreach my $period ( keys %patt ) {
		foreach my $hr ( keys %{ $patt{$period} } ) {
		    my $subject = "HR:$hr";

		    # check for duplicates
		    $sth6->execute( $date, $subject, $period);
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		    my $count = $sth6->fetchrow;
		    if ( $count ) { next; }
		    
		    $sth5->execute( $userid, $date, $subject, $period);
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		}
	    }

	} # tattentry end
	# end homeroom method
	
    } # end of homeroom method.
    
    print qq{</table>\n};

    print qq{<h1>$lex{'Records Stored'}</h1>\n};

    print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
    print qq{ <a href="$attpage">$lex{Attendance}</a> |\n};
    print qq{ <a href="$self">$lex{More}</a> ]\n};

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

    exit;

}


#----------------
sub dateNormalize {
#----------------
    my $date = shift;
    my ($year,$month,$day) = split /-/, $date;
    if ( length( $month ) == 1 ) { $month = '0'. $month; } # prepend 0
    if ( length( $day ) == 1 ) { $day = '0'. $day; } # prepend 0
    $date = "$year$month$day";

    return $date;

}
