#!/usr/bin/perl
#  Copyright 2001-2018 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; version 2 of 
#  the License, only.


my %lex = ('Periods per Day' => 'Periods per Day',
	   'Not Found' => 'Not Found',
	   'Student Attendance' => 'Student Attendance',
	   'Main' => 'Main',
	   'Date' => 'Date',
	   'Next Week' => 'Next Week',
	   'Previous Week' => 'Previous Week',
	   'User Id' => 'User Id',
	   'Continue' => 'Continue',
	   'Cookie Duration' => 'Cookie Duration',
	   'Password' => 'Password',
	   'Please Log In' => 'Please Log In',
	   'Clear Prev Attendance' => 'Clear Prev Attendance',
	   'Entry' => 'Entry',
	   'Subject' => 'Subject',
	   'Student' => 'Student',
	   'AM' => 'AM',
	   'PM' => 'PM',
	   'Reason' => 'Reason',
	   'Edit' => 'Edit',
	   'Period' => 'Period',
	   'Teacher' => 'Teacher',
	   'Room' => 'Room',
	   'Day In Cycle' => 'Day In Cycle',
	   'Period(s)' => 'Period(s)',
	   'Method' => 'Method',
	   'Name' => 'Name',
	   'Error' => 'Error',
	   'Multiday' => 'Multiday',
	   'Late' => 'Late',
	   'Alternate' => 'Alternate',
	   'Add' => 'Add',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Attendance' => 'Attendance',
	   'Record' => 'Record',
	   'Exists' => 'Exists',
	   'Select' => 'Select',
	   'Go' => 'Go',
	   'No Subjects Found' => 'No Subjects Found',
	   'School Closed' => 'School Closed',
	   'Perfect Attendance' => 'Perfect Attendance',
	   'Previous' => 'Previous',
	   'Term' => 'Term',
	   'Attendance Entry' => 'Attendance Entry',
	   'not allowed' => 'not allowed',
	   'Course' => 'Course',
	   'No Timetable Entry' => 'No Timetable Entry',
	   'Track' => 'Track',
	   'Minutes' => 'Minutes',

	   'Save' => 'Save',
	   'Not Saved' => 'Not Saved',
	   'Duplicate' => 'Duplicate',
	   'Missing' => 'Missing',
	   'More' => 'More',
	   'New' => 'New',
	   'Skipping' => 'Skipping',
	   'No Absences Found' => 'No Absences Found',
	   'Contact' => 'Contact',
	   'Saved' => 'Saved',
	   'Type' => 'Type',
	   'Reasons' => 'Reasons',
	   'Not Found' => 'Not Found',
	   'Homeroom' => 'Homeroom',
	   'Weekly' => 'Weekly',
	   'Previously' => 'Previously',

	   'Non-School Day' => 'Non-School Day',
	   
	   );

my $self = 'tattentry.pl';
my $weekcount = 1; # Number of weeks to do for entry. (normally 1 or 2)
my $g_maxterms = 12; # not global, etc.

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


# my $attendview = 16; # Number of previous attendance records to see;
if (not defined $g_attendview ) { $g_attendview = 16; }

# my $teachview = 12; # Number of teacher attendance records to see.
if (not defined $g_teachview ) { $g_teachview = 12; }

# my $allowedit = 1;  # Comment out to disable teacher editing of att records.
if ( not defined $g_allowedit ) { $g_allowedit = 1; }

my $q = new CGI;
my %arr = $q->Vars;


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


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


# Get Session
my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

# Get/Set  Session Values (a defined userid means it was passed)
if ( $arr{userid} ){ # we want to login, passed userid/password pair.

    # Check password/userid against database (-1 no user, -2 wrong password);
    my $error = checkPassword($arr{userid}, $arr{password});
    if ($error == -1){ 
	print $q->header( -charset, $charset ); 
	login("$lex{'User Id'} $lex{'Not Found'}");
	
    } elsif ($error == -2){ 
	print $q->header( -charset, $charset ); 
	login("$lex{Password} $lex{'Not Found'}"); 
    }

    $cookietime = checkCookieTime( $arr{duration} );

    # Set values for userid and logged_in in session
    $session->param('logged_in','1');
    $session->expire('logged_in', $cookietime);
    $session->param('userid', $arr{userid});
    $session->param('duration', $cookietime);

    $userid = $arr{userid};


} else { # check logged_in value in session

    if ( not $session->param('logged_in') ){

	$userid = $session->param('userid');
        print $session->header( -charset, $charset );

        login( $lex{'Please Log In'}, $userid ); 
    }
    # Ok, we have a login. Values below we have in environment.

    $userid = $session->param('userid');
    $duration = $session->param('duration');

    if ( not ($duration =~ m/\+/)) { # if not in +20m format, do so.
	$duration = checkCookieTime( $duration );
    }

    $session->expire('logged_in', $duration );


} # End of check for logged_in value

$session->flush();
print $session->header( -charset, $charset );


# Print HTML Page Header....
my $title = qq{$lex{Attendance} $lex{Entry}};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};

# Setup for Calendar popup.
print qq{<link rel="stylesheet" type="text/css" media="all" 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{<style type="text/css">.flt { float:left; }</style>\n};
print qq{$chartype\n</head><body>\n};

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

print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};


if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    enterAttendance();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};

    if ( $arr{latemode} ) {
	delete $arr{latemode};
	addLates();
    }
    
    confirmAttendance();
    
} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    writeAttendance();
}



#------------------
sub writeAttendance {
#------------------

    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    
    # Is used below, now
    my $date = $arr{date};
    delete $arr{date};
    my $method = $arr{method};
    delete $arr{method};


    # reference values
    my @fields = qw(studentid period reason absdate ); 

    my %homeroomdates;
    my %subjectdates;

#    my %teacherdata;

    my $first = 1;

    my $sth1 = $dbh->prepare("select count(*) from attend where studentid = ? and absdate = ? and period = ?");

    foreach my $key ( keys %arr ) {

	my ( $studnum,$subjsec,$period, $reason, $late, $date ) = split(':',$key);
	if ( $studnum eq 'PA' ) { next; } # skip PA records.
	
	$first = 0;
	my @values;
	my @fieldnames = @fields; # vary with each loop depending on values passed.
	my @qst = qw(? ? ? ?); # 4 fields to start.


	push @values, $studnum, $period, $reason, $date; # required fields.

	# Put in the colon after HR, can't earlier since used as field separator.
	if ( $subjsec =~ m/^HR/ ) {
	    my $temp = $subjsec;
	    $temp = substr($temp, 2);
	    $subjsec = 'HR:'. $temp;
	}

	push @values, $subjsec;
	push @fieldnames, 'subjsec';
	push @qst, '?';

	# print qq{Starting Teacher Data: Date:$date Subjsec:$subjsec Period:$period<br>\n};


	if ( $late ) {
	    push @values, $late;
	    push @fieldnames, 'late';
	    push @qst, '?';
	}

	my $fieldnames = join(',', @fieldnames);
	my $qst = join(',', @qst);

	
	# Check for a matching record, skip if so. (same student, date, period).
	$sth1->execute( $studnum, $date, $period );
	if ( $DBI::errstr ) { print $DBI::errstr;die $DBI::errstr; }
	my $count = $sth1->fetchrow;
	if ( $count ) {
	    print qq{<h4>$lex{Attendance} $lex{Record} $lex{Exists}! $lex{Skipping}</h4>\n};
	    next;
	    
	} # else insert the record

	my $sth = $dbh->prepare("insert into attend ( $fieldnames ) values ( $qst )");
#	print "Insert Attendance Records: $fieldnames ", @values, "<br>\n";
	
	$sth->execute( @values );
	if ( $DBI::errstr ) { print $DBI::errstr;die $DBI::errstr; }

	
    } # End of ForEach loop


    if ( $first ) { # no attendance entries done; perfect attendance.
	print qq{<h3>$lex{'No Absences Found'}</h3>\n};

    } elsif ( not $DBI::errstr ) {
	print qq{<h3>$lex{Student} $lex{Attendance} $lex{Saved}</h3>\n};

    } else {
	print qq{<h3>$lex{Error} \n};
	print qq{$lex{Contact} $adminname \n};
	print qq{<a href="mailto:$adminemail">$adminemail</a>\n};
	print qq{$lex{Error}: $DBI::errstr</h3>\n};
    }


    
    # Now do teacher attendance entries, including perfect att.

    # Insert the teacher attendance record
    my $sth = $dbh->prepare("insert into tattend ( userid, attdate, currdate, subjects, periods ) 
      values ( ?,?, now(),?,? )");

    my $sth1 = $dbh->prepare("select count(*) from tattend where userid = ? and attdate = ? 
      and subjects = ? and periods = ?");

    
    # Teacher Attendance Entry; loop through all passed values.
    foreach my $key ( keys %arr ) {

	# find out the kind of entry: PA or not.
	my @temp = split(':', $key);
	if ( $temp[0] eq 'PA' ) { # perfect attendance record
	    
	    my ( $txt,$subjsec,$date,$period ) = split(':',$key);
	    if ( $method ne 'subject' ) { # munge the subjsec
		my $tempsubj = $subjsec;
		$tempsubj =~ s/^HR//; # strip leading HR
		$subjsec = qq{HR:$tempsubj};  # put in HR with colon
	    }

	    # Check if added already
	    $sth1->execute( $userid, $date, $subjsec,$period );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $count = $sth1->fetchrow; 

	    # Otherwise, add the record
	    if ( not $count ) { # Insert tattend records
#		print qq{Insert: PA rec: User:$userid Date:$date Subjsec:$subjsec Period:$period<br>\n};
		$sth->execute( $userid, $date, $subjsec, $period );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    }

	} else { # a normal teacher attendance record
	    
	    my ( $studnum,$subjsec,$period, $reason, $late, $date ) = split(':',$key);
    
	    if ( $method ne 'subject' ) { # munge the subjsec
		my $tempsubj = $subjsec;
		$tempsubj =~ s/^HR//; # strip leading HR
		$subjsec = qq{HR:$tempsubj};  # put in HR with colon
	    }

	    # Check if added already
	    $sth1->execute( $userid, $date, $subjsec,$period );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $count = $sth1->fetchrow; 

	    # Otherwise, add the record
	    if ( not $count ) { # Insert tattend records
		# print qq{Insert Normal rec: User:$userid Date:$date Subjsec:$subjsec Period:$period<br>\n};
		$sth->execute( $userid, $date, $subjsec, $period );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    }
	}

    } # end of %arr loop


    # Add more Attendance Records
    print qq{<h3>$lex{Add} $lex{More} $lex{Attendance}</h3>\n};
    
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<select name="method"><option>$method</option>\n};
    print qq{<option value="homeroom">$lex{Homeroom}</option><option value="subject">$lex{Subject}</option>};
    print qq{<option value="multiday">$lex{Weekly}</option></select>\n};
    print qq{<input type="submit" value="$lex{Add} $lex{Attendance}"></form>\n};

    print qq{<p>[ <a href="$tchpage">$lex{Main}</a> ]</p>\n};
    
    print qq{</body></html>\n};

    exit;

} # end of writeAttendance



#-----------
sub addLates {
#-----------

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

    # if coming from multiday, there will be no date value
    # passed. Homeroom method pass a date, but there will be blanks in
    # the keys coming from the enterAttendance function. They both
    # will have values of studnum:subjsec:date:period and reason and
    # late values will have a 5th field of Reason (no Late value
    # passed into addLates of course).
   
    
    my $method = $arr{method};
    delete $arr{method};
    my $date = $arr{date};
    delete $arr{date};

    print qq{<h3>$lex{Add} $lex{Reasons} / $lex{Minutes} $lex{Late}</h3>\n};

    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="method" value="$method">\n};
    if ( $date ) {  # only pass date if it has a value; multiday will not.
	print qq{<input type="hidden" name="date" value="$date">\n};
    }
    print qq{<input type="hidden" name="page" value="2">\n};

    
    # Handle any passed PA values. Do not insert a date value into the blank, since we do in confirm.
    foreach my $key ( sort keys %arr ) {
	if ( $arr{$key} ) { # if we have a value
	    my ($val,@tmp) = split(':', $key);
	    if ( $val eq 'PA' ) { # perfect attendance value
		print qq{<input type="hidden" name="$key" value="1">\n};
		delete $arr{$key};
	    }
	}
    }


    # Handle any reasons passed from enterAttendance that don't have any period values.
    my %reasons; # store passed reasons by studnum, since some keys have no period
    foreach my $key ( sort keys %arr ) {
	if ( $arr{$key} ) {
	    my ( $studnum, $subjsec, $dt, $period, $val ) = split(':', $key);
	    if ( $val eq 'Reason' ) {
		if ( not $period ) { # put into reasons hash for entry below.
		    $reasons{$studnum} = $arr{$key};
		}
	    }
	}
    }

    #foreach my $sn ( sort keys %reasons ) {
    #  print qq{SN:$sn V:$reasons{$sn}<br>\n};
    #}
    

    my $sth = $dbh->prepare("select lastname,firstname from student where studnum = ?");
    my $sth1 = $dbh->prepare("select description from subject where subjsec = ? ");


    my $first = 1;

    
    # Format: $studnum:$subjsec:date:$period -- we append the late or
    # alt reason, date may be blank if date passed and we must add the
    # date value

    foreach my $key ( sort keys %arr ) {

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

	    if ( $first ) {
		# Print Table Header.
		print qq{<table border="1" cellspacing="0" cellpadding="5">\n};
		print qq{<tr><th>$lex{Student}</th><th>$lex{Subject}<br>$lex{Homeroom}</th>\n}; 
		print qq{<th>$lex{Reason}</th><th>$lex{Period}</th>};
		print qq{<th>$lex{Date}</th><th>$lex{Minutes}<br>$lex{Late}</th></tr>\n};
		$first = 0;
	    }
	    
	    # Get Variables, skip any reason values
	    my ( $studnum, $subjsec, $dt, $period, $val ) = split(':', $key);
	    if ( $val eq 'Reason' ) { next; }
	    my $reasonkey = qq{$studnum:$subjsec:$dt:$period:Reason};
	    my $latekey = qq{$studnum:$subjsec:$dt:$period:Late};

	    
	    # Get student name
	    my $studname;
	    $sth->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname, $firstname) = $sth->fetchrow;
	    if ( not $lastname ) { # No student found....
		$studname = qq{<span style="color:red;">$lex{'No Student(s) Found'}</span>};
	    } else { # we have a student
		$studname = qq{<b>$lastname</b>, $firstname ($studnum)};
	    }

	    # Now find the subject description
	    my $description = $subjsec;
	    if ( $subjsec !~ m/HR.*/) {
		$sth1->execute( $subjsec );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		$description = $sth1->fetchrow;
	    }


	    # all passed values will not have any period associated with reasons.
	    my $reason = $reasons{$studnum};
	    
	    print qq{<tr><td>$studname</td><td>$description</td>\n};
	    print qq{<td><select name="$reasonkey">};
	    print qq{<option>$reason</option>\n};
	    foreach my $rsn ( @attend ) { 
		if ( $rsn ne $reason ) { print qq{<option>$rsn</option>};}
	    }
	    print qq{</select></td><td class="cn">$period</td><td>$date</td>\n};
	    
	    # print original record, w/o change.
	    print qq{<td><input type="hidden" name="$key" value="$arr{$key}">\n};
	    # then add in the late key value
	    print qq{<input type="text" name="$latekey" size="6"></td></tr>\n};
	    # In summary, 3 keys will be passed to confirm: original (possibly no date), then reason,late recs.
	    
	} # if a value
    } # end of %arr loop.

    if ( $first ) { # no recs.
	print qq{</table></form><h3>No Values</h3>\n};
	
    } else {
	print qq{<tr><td colspan="6" style="text-align:center;">\n};
	print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
	print qq{</table></form>\n};
    }

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

    exit;
    
} # end of addLates
 

#--------------------
sub confirmAttendance {
#--------------------

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

    
    my $date = $arr{date};
    delete $arr{date};
    
    my $method = $arr{method};
    delete $arr{method};

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


    # Handle any passed PA values.
    my $first = 1;
    foreach my $key ( sort keys %arr ) {
	if ( $arr{$key} ) { # if we have a value
	    my ($val, $subjsec, $dt, $period) = split(':', $key);
	    if ( $val eq 'PA' ) { # perfect attendance value
		if ( not $dt ) { $dt = $date; }  # $dt is local date value passed, hr method doesn't pass
		
		$masterdate{$dt}{$period} = 1;
		$pa{$dt}{$period}{$subjsec} = 1;

		delete $arr{$key};
	    } # if PA
	} # if we have a value
    }



    # Handle any reasons, lates without an associated period.
    my (%reasons, %lates);
    foreach my $key ( sort keys %arr ) {
	if ( $arr{$key} ) { # if we have a value
	    my ($studnum, $subjsec, $dt, $period, $val) = split(':', $key);
	    if ( not $dt ) { $dt = $date; }
	    if ( $val eq 'Reason' and not $period ) { # if no period we apply to all periods for this student
		$reasons{$studnum} = $arr{$key};  # $arr{$key} has the absence/late reason
		delete $arr{$key};
		
	    } elsif ( $val eq 'Late' and not $period ) { # if no period we apply to all periods for this student
		$lates{$studnum} = $arr{$key};  # $arr{$key} has the absence/late reason
		delete $arr{$key};
	    }
	} # if we have a value
    }


    # Populate any passed values missing a date, with a date value.
    if ( $date ) { # we have a passed date, so there are passed values without that date.
	foreach my $key ( sort keys %arr ) {
	    if ( $arr{$key} ) { # if we have a value
		my ($studnum, $subjsec, $dt, $period, $val) = split(':', $key);
		if ( not $dt ) {
		    # add a new value to the hash, delete the old one.
		    if ( $val ) {
			$arr{"$studnum:$subjsec:$date:$period:$val"} = $arr{$key};
		    } else {
			$arr{"$studnum:$subjsec:$date:$period"} = $arr{$key};
		    }
		    delete $arr{$key};
		}
	    }
	}
    }

=head
    # show what we have left in %arr;
    print qq{NEW %ARR VALUES<br>\n};
    foreach my $key ( sort keys %arr ) {
	if ( $arr{$key} ) {
	    print qq{K:$key V:$arr{$key}<br>\n};
	}
    }
=cut

   
    my $noReasonFlag;
    my $duplicateRecordFlag;
#    my $first = 0;
    

    my $sth1 = $dbh->prepare("select attid from attend where studentid = ? and absdate = ? and period = ?");

    my %attdata; # attdata{date}{period}{studnum} = (subjsec => $subjsec, reason,late)

    foreach my $key ( sort keys %arr) {
	if ( $arr{$key} ) { # if we have a value

	    my ( $studnum, $subjsec, $date, $period, $val ) = split(':',$key);
#	    print "SN:$studnum SUB:$subjsec Date:$date Period:$period VAL:$val<br>\n";
		
	    if ( $val ) { next; } # skip any Reason or Late records
		
	    my $late = $arr{"$key:Late"};
	    my $reason = $arr{"$key:Reason"};
	    if ( not $reason ) {
		$reason = $reasons{$studnum};
	    }

#	    print "Reason:$reason Late:$late<br>\n";
		
	    if ( not $reason ) {
		$noReasonFlag = 1;
		push @noReason, "$studnum:$subjsec:$period:$date";  # studnum:subjsec:period:$date
	    }
	    
	    # Check for an existing attendance record.
	    $sth1->execute( $studnum, $date, $period ); 
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; } 
	    my $attid = $sth1->fetchrow;
	    # print qq{ATTID: $attid  SN:$studnum D:$date  P:$period<br>\n};

	    if ( $attid  ) { # we have an existing record...  
		$duplicateRecordFlag = 1; 
		push @duplicateRecords, "$attid:$studnum:$period:$date:$subjsec:$reason"; 
	    }

	    if ( $attid or not $reason ) {
		next;
	    }

	    # put values into hash
	    $attdata{$date}{$period}{$studnum} = {'subjsec' => $subjsec, 'reason' => $reason, 'late' => $late };
	    $masterdate{$date}{$period} = 1;
	    
=head	    
	    my $sth = $dbh->prepare("select lastname, firstname, homeroom from student where studnum = ?");
	    $sth->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname,$homeroom ) = $sth->fetchrow;

	    if ( not $lastname ) { # No student found....
		$studname = qq{<span style="color:red;">$lex{Student} $lex{'Not Found'}</span>};
	    } else { # we have a student
		$studname = qq{$lastname, $firstname ($studnum)};
	    }

#	    print qq{<tr><td>$studname };
#	    print qq{<input type="hidden" name="$studnum:$subjsec:$period:$reason:$late:$date" value="1"></td>\n};
#	    print qq{<td>$subjsec</td><td>$reason</td><td>$period</td>};
#	    print qq{<td>$date</td><td>$late</td></tr>\n};
=cut


	} # End of If
    } # End of %arr Loop


    # Missing reason fail.
    if ( $noReasonFlag ) {

	print qq{<tr><td colspan="6" class="cn" style="color:red;"><b>};
	print qq{$lex{Missing} $lex{Attendance} $lex{Reason}</b><br>};
	print qq{$lex{Attendance} <b>$lex{'Not Saved'}</b></td></tr>\n};


	my $sth = $dbh->prepare("select lastname,firstname from student where studnum = ?");
	my $sth1 = $dbh->prepare("select description from subject where subjsec = ?");

	foreach my $rec ( @noReason ) {
	    my ($studnum, $subjsec, $period, $date) = split(':', $rec);

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

	    # Now find the subject name ( if subjsec exists )
	    my $description;
	    if ( $subjsec ) {
		$sth1->execute( $subjsec );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		$description = $sth1->fetchrow;
	    }

	    print qq{<tr><td>$firstname $lastname ($studnum)</td>\n};
	    print qq{<td>$description ($subjsec)</td>\n}; 
	    print qq{<td></td><td>$period</td><td>$date</td><td>$late</td></tr>\n};
	
	}

    } # End of noReasonFlag


    if ( $duplicateRecordFlag ) {

	print qq{<tr><td colspan="6" class="cn" style="color:red;"><b>};
	print qq{$lex{Duplicate} $lex{Attendance} $lex{Record}</b><br>\n};
	print qq{$lex{Attendance} <b>$lex{'Not Saved'}</b></td></tr>\n};

	my $sth = $dbh->prepare("select lastname,firstname from student where studnum = ?");
	my $sth1 = $dbh->prepare("select description from subject where subjsec = ?");
	my $sth2 = $dbh->prepare("select * from attend where attid = ?");

	foreach my $rec ( @duplicateRecords ) {
	    my ($attid, $studnum, $period, $date, $subjsec, $reason) = split(':', $rec);

	    # print qq{ATTID:$attid SN:$studnum P:$period D:$date S:$subjsec<br>\n};

	    # load Attendance Record
	    $sth2->execute( $attid );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $aref = $sth2->fetchrow_hashref;
	    my %ar = %$aref;

	    # Now find the student name
	    $sth->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname, $firstname) = $sth->fetchrow;

	    # Now find the subject name (if subjsec exists)
	    my $description;
	    if ( $subjsec ) {
		$sth1->execute( $subjsec );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		$description = $sth1->fetchrow;
		if ( not $description ) { $description = $subjsec; } else { $description .= " ($subjsec)"; }
	    }

	    # New Record
	    print qq{<tr  style="background-color:#FCC;"><td style="color:red;font-weight:bold;">};
	    print qq{$lex{New} $lex{Attendance} - $firstname $lastname ($studnum)</td><td>$description</td>\n}; 
	    print qq{<td>$reason</td><td>$period</td><td>$date</td><td>$late</td></tr>\n};

	    # Previously Stored
	    my $newdesc;
	    if ( $ar{subjsec} ) {
		$sth1->execute( $ar{subjsec} );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		$newdesc = $sth1->fetchrow;
		if ( not $newdesc ) { $newdesc = $ar{subjsec}; } else { $newdesc .= " ($ar{subjsec})"; }
	    }
	
	    print qq{<tr><td style="color:red;font-weight:bold;">};
	    print qq{$lex{Previously} $lex{Saved} - $firstname $lastname ($studnum)</td>\n};
	    print qq{<td>$newdesc</td>\n}; 
	    print qq{<td>$ar{reason}</td><td>$ar{period}</td><td>$ar{absdate}</td><td>$ar{late}</td></tr>\n};
	
	} # duplicate records loop
    } # End of duplicateRecords

    # If we have one or both above.... close forms and finish page
    if ( $duplicateRecordFlag or $noReasonFlag ) {
	print qq{</table></form></body></html>\n};
	exit;
    }

    
    # Store days of the week.
    my %weekdays;
    foreach my $date ( keys %masterdate ) {
	if ( not $weekdays{$date} ) {
	    my $jd = julian_day( split('-',$date));
	    $weekdays{$date} = day_of_week($jd);
	}
    }

    
    # Otherwise show values to pass on.
    my $sth2 = $dbh->prepare("select lastname, firstname, homeroom from student where studnum = ?");

    my $first = 1;
    foreach my $date ( sort keys %masterdate ) {
	foreach my $period ( sort keys %{ $masterdate{$date} } ) {
	    
	    my (%sort, %name);
	    foreach my $studnum ( keys %{ $attdata{$date}{$period} } ) {
		$sth2->execute( $studnum );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		my ( $lastname, $firstname,$homeroom ) = $sth2->fetchrow;
		$sort{"$lastname$firstname$studnum"} = $studnum;
		$name{$studnum} = qq{<b>$lastname</b>, $firstname};
	    }

	    if ( $first ) { 
		print qq{<table border="1" cellspacing="0" cellpadding="5" style="margin-bottom:1em;">\n};
		print qq{<caption style="font-weight:bold;font-size:120%;">Student Absence</caption>\n};
		print qq{<tr><th>$lex{Date}</th><th>$lex{Period}</th><th>$lex{Student}</th>};
		print qq{<th>$lex{Reason}</th><th>$lex{Subject}/<br>$lex{Homeroom}</th><th>$lex{Late}</th></tr>\n};
		$first = 0;
	    }

	
	    # Perfect Attendance, if any
	    foreach my $subjsec  ( keys %{ $pa{$date}{$period} } ) {
		print qq{<tr><td>$dow[$weekdays{$date} + 1] $date</td><td class="cn">$period</td>};
		print qq{<td colspan="2" style="background-color:#DDD;font-weight:bold;">Perfect Attendance \n};
		print qq{<input type="hidden" name="PA:$subjsec:$date:$period" value="1"></td>\n};
		print qq{<td>$subjsec</td><td></td></tr>\n};
	    }
	
	    foreach my $key ( sort keys %sort ) {
		my $studnum = $sort{$key};
		my $name = $name{$studnum};
		print qq{<tr><td>$dow[$weekdays{$date} + 1] $date</td>};
		print qq{<td class="cn">$period</td><td>$name ($studnum)</td>\n};
		my %r = %{ $attdata{$date}{$period}{$studnum} };
		print qq{<td>$r{reason}</td><td>$r{subjsec}</td><td>$r{late} \n};
		print qq{<input type="hidden" name="$studnum:$r{subjsec}:$period:$r{reason}:$r{late}:$date" };
		print qq{value="1"></td></tr>\n};
	    }
	} # end of this period

	print qq{<tr><td colspan="6" style="background-color:#DDD;"></td></tr>\n};

    }

    print qq{<tr><td colspan ="6" style="text-align:center;">\n};
    print qq{<input type="submit" class="btn-grn" value="$lex{Save} $lex{Attendance}"></td></tr>\n};
    print qq{</table></form></body></html>\n};

    exit;

}
# end of confirmAttendance



#------------------
sub enterAttendance {
#------------------

    #foreach my $key ( sort keys %arr ) { print qq{K:$key Val:$arr{$key}<br>\n}; }
    #exit;
    
    # attendance entry 'method'
    my $method = $arr{method};
    delete $arr{method};

    print qq{<b>$lex{Method}</b> $method\n};


    # Date Functions - current date, date data structures.
    # First days of year, teacher days, mess this up.
    # so set first day of first term to schoolstart. 
    my $schoolstart = $g_MTrackTerm{1}{1}{'start'}; # use first track, first term 
    my ($styear,$stmonth,$stday) = split('-',$schoolstart);
    my ($endyear,$endmonth,$endday) = split('-',$schoolend);
    my $startjd = julian_day($styear,$stmonth,$stday);
    my $endjd = julian_day($endyear,$endmonth,$endday);
    my ( $year, $month, $day ); # now global for homeroom entry method

    
    my ($currdate,$currsdate, $mondayjd, $currjd, $dow );
    if ( $arr{date} ) {

	# Generate a list from those dates.
	($year,$month,$day) = split('-',$arr{date});

	$currjd = julian_day($year,$month,$day);

	# Make sure date is within the current school year.
	if ( $currjd < $startjd or $currjd > $endjd ) {
	    print qq{<h3>Date is outside of current school year: $arr{date} - Y:$year M:$month D:$day</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}

	
	$dow = day_of_week($currjd); # for use below in subject att entry
	$mondayjd = $currjd - ($dow-1);

	if (length($month) == 1){ $month = "0".$month;}
	if (length($day) == 1){ $day = "0".$day;}
	$currsdate = "$year$month$day"; 
	$currdate = "$year-$month-$day";

    } else { # use current date

	@tim = localtime(time);
	$year = $tim[5] + 1900;
	$month = $tim[4] + 1;
	$day = $tim[3];

	$currjd = julian_day($year,$month,$day);
	$dow = day_of_week($currjd); # for consumption below also; subj att entry
	$mondayjd = $currjd - ($tim[6]-1); #This will now give Monday of that week.
	if (length($month) == 1){ $month = "0".$month;}
	if (length($day) == 1){ $day = "0".$day;}
	$currdate = "$year-$month-$day";
	$currsdate = "$year$month$day";

    } 


    # Figure out the current term(s) for each track.
    my ($currterm, %terms, %grade2terms );

    foreach my $trk ( sort {$a <=> $b} keys %g_MTrackTerm ) {
	for my $trm ( sort {$a <=> $b} keys %{ $g_MTrackTerm{$trk}} ) {

	    my $startjd = julian_day( split(/-/, $g_MTrackTerm{$trk}{$trm}{start}) );
	    my $endjd =  julian_day( split(/-/, $g_MTrackTerm{$trk}{$trm}{end}) );
	    if ( $currjd >= $startjd and $currjd <= $endjd ) { # we have the term.
		$terms{$trk} = $trm;
		last; # done with this track.
	    }
	}
    }

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

    foreach my $gr ( keys %g_MTrackTermType ) {
	my $track = $g_MTrackTermType{$gr};
	$grade2terms{$gr} = $terms{$track};
    }

    # Testing: foreach my $key ( sort keys %grade2terms ) { print "Grade:$key Term:$grade2terms{$key}<br>\n"; }


    # Set Maximum periods per day; (Used by Subject entry and MultiDay)
    my $maxppd = 0;  # Maximum periods per day
    if ( not %g_ppd ){ 
	print $q->header( -charset, $charset );
	print qq{<h3>$lex{'Periods per Day'} - $lex{'Not Found'}!</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    foreach my $key (keys %g_ppd){  # Get the Largest PPD.
	if ($g_ppd{$key} > $maxppd){ $maxppd = $g_ppd{$key};}
    }

    
    # Setup Array and Hash to hold Dates and DOW Dates (Multi-Day Method)
    my ($ddref, $dayref) = mkDateData($mondayjd,$weekcount);
    my @days = @$dayref;
    my %datedata = %$ddref;
    

    # Push Rooms into array
    $sth = $dbh->prepare("select field_value from staff as s, staff_multi as sm
       where s.userid = sm.userid and s.userid = ? and field_name = 'homeroom'");
    $sth->execute( $userid );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $homeroom = $sth->fetchrow ) {
	push @hroom, $homeroom;
    }

    # daily, weekly homeroom attendance entry but no homerooms.
    if ( $method ne 'subject' and not @hroom ) {
	print qq{<h3>$lex{Homeroom} $lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Load non-school days, if any for these homerooms.
    my %nonschoolday;
    my $sth = $dbh->prepare("select date, period from dates_nonschool where homeroom = ?");
    foreach my $hr ( @hroom ) {
	$sth->execute( $hr );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my ($date,$period) = $sth->fetchrow ) {
	    $nonschoolday{$hr}{$date}{$period} = 1;
#	    print "HR:$hr Date:$date Period:$period<br>\n";
	}
    }

    
    # Rest of Top of Page...
    print qq{<h1 style="display:inline;padding:0.5em 0 0.5em 3em;">\n};
    print qq{$lex{'Student Attendance'} $lex{Entry} - <i>};
    my $firstview = 1;
    foreach my $trk ( sort keys %terms ) { 
	my $trm = $terms{$trk};
	if ( not $firstview ) { print qq{ | }; }
	print qq{<b>$lex{Track}</b> $trk <b>$lex{Term}</b> $trm};
	$firstview = 0;
    }
    print qq{</i></h1>\n};
    
#    print qq{<br clear="left">\n\n};
#    print qq{<div style="float:left;padding-right:1em;">\n\n};

    
    # Weekly Date Calcs - Previous Week / Next Week.
    my $prevjd = $mondayjd - 7;
    if ( $prevjd < $startjd ){ $prevjd = $startjd;}
    my ($prevyear, $prevmonth, $prevday) = inverse_julian_day($prevjd);
    my $prevdate = "$prevyear-$prevmonth-$prevday";

    print qq{<div style="padding:0.5em;">\n};
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="date" value="$prevdate">\n};
    print qq{<input type="hidden" name="method" value="$method">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" value="<= $lex{'Previous Week'}"></form>\n};

    my $nextjd = $mondayjd + 7; 
    if ($nextjd > $endjd){ $nextjd = $endjd;}
    my ($nextyear, $nextmonth, $nextday) = inverse_julian_day($nextjd);
    my $nextdate = "$nextyear-$nextmonth-$nextday";

    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="method" value="$method">\n};
    print qq{<input type="hidden" name="date" value="$nextdate">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" value="$lex{'Next Week'} =>"></form>\n\n};


    # Pop Up Calendar Date Selector
    print qq{<form action="$self" method="post" };
    print qq{style="display:inline;background-color:yellow;padding:0.3em 0.5em;border:1px solid gray;">\n};
    print qq{<input type="hidden" name="method" value="$method">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<button type="reset" id="date_trigger">$lex{Select} $lex{Date}</button>\n};
    print qq{<input type="text" name="date" id="date" size="10">\n};
    print qq{<input type="submit" value="$lex{Go}">\n};
    print qq{</form>\n};
    print qq{</div>\n\n};

    if ( $method ne 'multiday' ) { # no need for a date selector for one day this week in multiday
	
	my $sth = $dbh->prepare("select id, dayfraction from dates where date = ?");

	for my $i ( 1..5 ) { # five days of this week.

	    my ($wkyear, $wkmonth, $wkday) = inverse_julian_day($mondayjd);
	    my $dow = day_of_week($mondayjd) + 1;
	    my $tmpdate = qq{$wkyear-$wkmonth-$wkday};

	    # Check for date being fully closed or not (ie ALL DAy).
	    # Skip if closed all day.
	    $sth->execute( $tmpdate );
	    my ( $id, $dayfrac ) = $sth->fetchrow;
	    # Logic: Skip for attendance if closed all day.
	    if ( $dayfrac > 0.99 ) { # ie. only 1.000, closed all day, skip
		$mondayjd++;
		next;
	    }

	    if ( $i == 4 ) { print qq{<br>\n}; }
	    print qq{<form action="$self" method="post" style="display:inline;">\n};
	    print qq{<input type="hidden" name="date" value="$tmpdate">\n};
	    print qq{<input type="hidden" name="method" value="$method">\n};
	    print qq{<input type="hidden" name="page" value="1">\n};
	    print qq{<input type="submit" value="$dow[$dow] $month[$wkmonth] $wkday"></form>\n};
	    $mondayjd++;
	}

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

	print qq{<div style="padding:0.4em;">$lex{Date} };
	my $localdow = $dow + 1;
	print qq{<span style="font-weight:bold;font-size:120%;">$dow[$localdow], $currdate</span>\n};
	print qq{</div>\n};
    }
	


    # Entry Methods Start Here.
    # ==== Subject Method =======
    if ( $method eq 'subject' ) {

	require "../lib/libschedule.pl" or die qq{Cannot open libschedule.pl!\n};

	# Get Subjects on currdate;
	my %subjects = findCurrentSubjects( $userid, $currdate, $dbh );
	if ( not %subjects ) {
	    print qq{<h1>$lex{'No Subjects Found'}</h1>\n};
	    print qq{</form></body></html>\n};
	    exit;
	}

	# Check for School Closed.
	$sth->execute( $currdate );
	if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ( $tmp, $dayfraction ) = $sth->fetchrow;
	if ( $dayfraction > 0.999 ) {
	    print qq{<h1>$lex{'School Closed'}</h1>\n};
	    print qq{</body></html>\n};
	    exit;
	}


	# Get the current DayInCycle, if set.
	my $dayInCycle = findDayInCycle( $currdate, $dbh );
	if ($dayInCycle) {
	    print qq{<div style="padding:0.4em;">};
	    print qq{$lex{'Day In Cycle'} <span style="font-weight:bold;">$dayInCycle</span></div>};
	}

	# Late / Alternate Reasons Box
	print qq{<div style="margin:0.4em;font-weight:bold;">};
	print qq{<input type="checkbox" name="latemode" value="1">};
	print qq{ $lex{Add} $lex{Late} / $lex{Alternate} $lex{Reason}</div>\n};


	# print hyperlink row
	print qq{<div style="padding:0.5em;">[ };
	my $sth2 = $dbh->prepare("select smdesc, section from subject where subjsec = ?");
	foreach my $subjsec ( sort keys %subjects ) {
	    $sth2->execute($subjsec);
	    if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ($smdesc,$section) = $sth2->fetchrow;
	    
	    print qq{<a href="#$subjsec">$smdesc-$section</a> };
	}
	print qq{]</div>\n};

	# Prep - Subject Name
	my $sth2 = $dbh->prepare("select description, grade from subject where subjsec = ?");

	# Timetable entries?
	my $sth3 = $dbh->prepare("select count(*) from schedat where subjsec = ? and term = ? ");

	# Existing Attendance Entry: student, date, subject, period;
	my $sth4 = $dbh->prepare("select count(*) from attend 
          where studentid = ? and absdate = ? and subjsec = ? and period = ?");

	my %sortedsubjects;
	foreach my $key ( keys %subjects ) {
	    my $per = $subjects{$key};
	    if (not $per) { $per = '00'; } # high enough to be at the end;
	    $per =~ s/\s+//g; # strip spaces.
	    $sortedsubjects{"$per$key"} = $key;
	}


	# Loop Through Subjects
	foreach my $key ( sort keys %sortedsubjects ) {

	    my $subjsec = $sortedsubjects{$key};

	    # Get the description, grade for the subject
	    $sth2->execute($subjsec);
	    if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ($description, $grade) = $sth2->fetchrow;
	    
	    # Get the term, based on the grade of the subject
	    my $currterm = $grade2terms{$grade};


	    # Do we have a timetable for this subject?
	    $sth3->execute( $subjsec, $currterm );
	    if ($DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $ttblcount = $sth3->fetchrow;  # timetable count


	    # Set Periods for this subject, today.
	    my @periods;
	    if ( $subjects{$subjsec} ) { # we have a space separated period value
		@periods = split(/\s/, $subjects{$subjsec} );
		@periods = sort {$a <=> $b} @periods; # get them in the right order.
	    } elsif ( $ttblcount ) { # we have timetable entries, but no value today, so skip.
		next;
	    } else { # no timetable entry and no periods, display warning
		print qq{<h3 style="color:red;">$description ($subjsec) - $lex{'No Timetable Entry'}</h3>\n};
		next;
	    }

	    # Check for entry method for this grade
	    if ( $g_AttendanceEntryMethod{$grade} eq 'homeroom' ) { # Error
		print qq{<h3>$lex{Subject} $lex{'Attendance Entry'} $lex{'not allowed'}. };
		print qq{$lex{Grade}:$grade $lex{Course}: $description ($subjsec)</h3>\n};
		next;
	    }


	    # Get the students enrolled in this course
	    $sth = $dbh->prepare("select distinct e.studnum from eval e,student s 
              where  e.subjcode = ? and e.studnum = s.studnum
              order by s.lastname,s.firstname");
	    $sth->execute($subjsec);
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	    my $rows = $sth->rows;
	    if ($rows < 1){  # No students registered.
		print qq{<h3>$description ($subjsec) - $lex{'No Student(s) Found'}</h3>\n};
		next;
	    }

	    print qq{<a name="$subjsec"></a>\n};
	    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};
	    print qq{<tr><th colspan="3"><span style="font-size:130%;">$description</span> ($subjsec)</th></tr>\n};

	    print qq{<tr><th>$lex{Student} ($lex{Homeroom})</th><th>$lex{'Period(s)'}</th>};
	    print qq{<th>$lex{Reason}</th></tr>\n};

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


	    # Perfect Attendance Row
	    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 ( @periods ) {
		print qq{<td>P$p<input type="checkbox" name="PA:$subjsec:$currdate:$p" value="1"></td>};
	    }
	    print qq{<td></td></tr>\n\n};
	    

	    # Loop Through Students
	    my $sth1 = $dbh->prepare("select lastname,firstname, homeroom from student where studnum = ?");

	    for ( 1 .. $rows ) {
		my $studnum = $sth->fetchrow;

		# Get Student Name
		$sth1->execute($studnum);
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		my ($lastname,$firstname, $homeroom) = $sth1->fetchrow;
		if ( not $lastname ){  # student name not found.
		    $lastname = qq{<span style="color:red;">$lex{Student} $lex{'Not Found'}</span>};
		}

		print qq{<tr><td><a href="tattsubjed0.pl?studnum=$studnum&subjsec=$subjsec" title="$studnum">\n};
		print qq{<b>$lastname</b>, $firstname</a>};
		if ( $homeroom ) { print qq{ ($homeroom)}; }
		print qq{</td><td>\n};

		foreach my $per ( @periods ) {

		    # Check for existing entry
		    $sth4->execute($studnum, $currdate, $subjsec, $per );
		    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		    my $count = $sth4->fetchrow;
		    if ( $count ) {
			#print qq{SN:$studnum D:$currdate S:$subjsec P:$per Count:$count<br>\n};
			print qq{<span style="color:green;background-color:#DDD">P$per}. q{E</span> };

		    } else {
			print qq{P$per<input type="checkbox" name="$studnum:$subjsec:$currdate:$per" value="1">\n};
		    }
		}

		
		# Reason Section (Field has studnum, subjsec, no period, and 'Reason'.
		print qq{</td><td><select name="$studnum:$subjsec:$currdate:\:Reason">}; # Watch! :: 
		print qq{<option></option>\n};

		foreach my $reason ( @attend ){
		    print qq{<option>$reason</option>\n};
		}
		print qq{</select></td></tr>\n};

	    }

	    print qq{<tr><td colspan="3" class="cn">\n};
	    # print qq{<input type="reset" value="$lex{'Clear Prev Attendance'}">\n};
	    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
	    print qq{</table><p style="color:green;">E = $lex{Attendance} $lex{Record} $lex{Exists}</p>\n};


	} # Outer Loop here for each subject.

    } # End of SUBJECT Method


    #==== MULTIDAY Method ==========
    elsif ($method eq 'multiday') {

	# Has it's own form start
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="hidden" name="method" value="$method">\n};
	print qq{<input type="hidden" name="latemode" value="1">\n};
	print qq{<input type="hidden" name="page" value="2">\n};
	
	# Find the kids' names, studnum, grade
	my $sth = $dbh->prepare("select lastname, firstname, studnum, grade from student 
         where homeroom = ? order by lastname, firstname");
	
	my $sth1 = $dbh->prepare("select distinct grade from student where homeroom = ?");

	print qq{<div><input type="submit" value="$lex{Continue}"></div>\n};
	
	# @hroom loaded at top of script for teacher.
	foreach my $hroom ( @hroom ) {
	    
	    # Get distinct grades for this homeroom and then find the
	    # max ppd value for this homeroom, and use that that for
	    # ppd for perfect attendance, just in case they vary.
	    my $pappd; # perfect attendance ppd value
	    $sth1->execute( $hroom );
	    if ($DBI::errstr){ print $DBI::errstr; die qq{$DBI::errstr\n};}    
	    while ( my $gr = $sth1->fetchrow ) {
		my $tempPPD = $g_ppd{$gr};
		if ( $tempPPD > $pappd ) { $pappd = $tempPPD; }
	    }

	    # Get the students in this homeroom
	    $sth->execute( $hroom );
	    if ($DBI::errstr){ print $DBI::errstr; die qq{$DBI::errstr\n};}    

	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<caption style="font-weight:bold;font-weight:120%;">$lex{Homeroom} $hroom</caption>\n};

	    # Print table headings.
	    print qq{<tr><th>$lex{Name}</th>};
	    foreach my $day (@days){ print qq{<th>$datedata{$day}</th>};}
	    print qq{</tr>\n\n};

	    
	    # Perfect Attendance Row
	    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};

	    foreach my $day (@days){


		print qq{<td style="font-size:80%;">};
		for my $p ( 1 .. $pappd ) {

		    if ( $nonschoolday{$hroom}{$day}{$p} ) {
			print qq{<span style="padding:0.5em;" title="$lex{'Non-School Day'}">N$p </span>\n};
		    } else {
			print qq{<span class="flt">P$p<input type="checkbox" };
			print qq{name="PA:HR$hroom:$day:$p" value="1"></span>\n};
		    }
		}
		print qq{</td>};
	    }
	    print qq{</tr>\n\n};

	    
	    
	    # Loop through kids displaying the values.
	    while ( my ( $lastname, $firstname, $studnum, $grade ) = $sth->fetchrow ) {

		# print Name.
		print qq{<tr><td>$lastname, $firstname</td>\n};

		# print the days for this mode:
		my $ppd = $g_ppd{$grade};
		if ( not $ppd ) { 
		    print qq{<h3>$lex{'Periods per Day'} $lex{'Not Found'}: };
		    print qq{$lex{Grade}: $grade</h3>\n}; 
		}
		foreach my $day (@days){
		    print qq{<td style="font-size:80%;">};
		    for my $p ( 1 .. $ppd ) {
			if ( $nonschoolday{$hroom}{$day}{$p} ) {
			    print qq{<span style="padding:0.5em;" title="$lex{'Non-School Day'}">N$p </span>\n};
			} else {
			    print qq{<span class="flt">P$p<input type="checkbox" };
			    print qq{name="$studnum:HR$hroom:$day:$p" value="1"></span>\n};
			}
		    }
		    print qq{</td>};
		}
		print qq{</tr>\n};
	    }

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

	} # End of This Homeroom (in case of multiple)
	
	print qq{</form>\n\n};

    } # End of Multi-Day Method


    
    #====== Homeroom Method =========
    else { # If not Subject, MultiDay, then use Homeroom (hroom)
	
	print qq{<div style="margin:0.25em;font-weight:bold;">};
	print qq{<input type="checkbox" name="latemode" value="1">};
	print qq{ $lex{Add} $lex{Late} / $lex{Alternate} $lex{Reason}</div>\n};
	
	# Get Teacher Name
	my $sth = $dbh->prepare("select sal, lastname, firstname from staff 
           where userid = ?");
	$sth->execute( $userid );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($tsal, $tlastname, $tfirstname) = $sth->fetchrow;
	my $teacher;
	if ($tsal) { 
	    $teacher = qq{$tsal $tfirstname $tlastname}; 
	} else {
	    $teacher = qq{$tfirstname $tlastname};
	}

	
	my $sth = $dbh->prepare("select lastname, firstname, studnum, grade from student 
          where homeroom = ? order by lastname, firstname");

	my $sth1 = $dbh->prepare("select distinct grade from student where homeroom = ?");

	foreach my $hroom ( @hroom ) {


	    # Check for a Non School Day (both period 1 and period 2)
	    if ( $nonschoolday{$hroom}{$currdate}{1} and $nonschoolday{$hroom}{$currdate}{2} ) {
		print qq{<h3>$lex{Homeroom} $hroom - $currdate<br>\n};
		print qq{<span style="font-size:80%;">$lex{'Non-School Day'}</span></h3>\n};
		next;
	    }

	    
	    # Check attendance entry method.
	    $sth1->execute( $hroom );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	    my ( $methodpass, $maxppd );  # maxppd is needed for header section.
	    if ( $hroom eq 'AE' ) { $methodpass = 1; }  # hack for Chief Napew
	    while ( my $grade = $sth1->fetchrow ) {
	    
		# if ANY grade has homeroom method set, then it's allowed for this homeroom
		if ( $g_AttendanceEntryMethod{$grade} eq 'homeroom' ) { 
		    $methodpass = 1; 
		}
		 
		if ( $g_ppd{$grade} > $maxppd ) { 
		    $maxppd = $g_ppd{$grade}; 
		}

	    }

	    if ( not $methodpass ) {
		print qq{<h3>Homeroom Attendance is not allowed</h3>\n};
		print qq{</body></html>\n};
		exit;
	    }


	    print qq{<div style="padding:0.5em;">$lex{Teacher} <b>$teacher</b>\n};
	    print qq{$lex{Room} <b>$hroom</b></div>\n\n};

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

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

	    
	    # Print Header Section
	    print qq{<tr><th>$lex{Student}</th>};
	    if ( $maxppd == 2 ) { # note maxppd is the actual # of periods for attendance
		print qq{<th>$lex{AM}</th><th>$lex{PM}</th>};
	    } else { # just print the periods
		for my $p ( 1..$maxppd ) {
		    print qq{<th>P$p</th>};
		}
	    }
	    print qq{<th>$lex{Reason}</th></tr>\n\n};

	    
	    # Perfect Attendance Row
	    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 ) {
		if ( $nonschoolday{$hroom}{$currdate}{$p} ) {
		    print qq{<td title="$lex{'Non-School Day'}">NSD</td>};
		} else {
		    print qq{<td><input type="checkbox" name="PA:HR$hroom:$currdate:$p" value="1"></td>};
		}
	    }
	    print qq{<td></td></tr>\n\n};

	    # Loop through all students;
	    $sth->execute($hroom);
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    
	    while ( my ( $lastname, $firstname, $studnum, $grade ) = $sth->fetchrow ){
		my $ppd = $g_ppd{$grade};
		my $extras = $maxppd - $ppd;

		print qq{<tr><td><b>$lastname</b>, $firstname</td>\n};
		foreach my $per ( 1..$ppd ) {
		    if ( $nonschoolday{$hroom}{$currdate}{$per} ) {
			print qq{<td title="$lex{'Non-School Day'}">NSD</td>};
		    } else {
			print qq{<td><input type="checkbox" name="$studnum:HR$hroom:$currdate:$per" value="1">};
			print qq{</td>\n};
		    }
		}
		foreach (1..$extras) { print qq{<td></td>\n}; }
		
		print qq{<td><select name="$studnum:HR$hroom:$currdate:\:Reason"><option></option>\n};
		# period is blank. AddLates will populate the period fields, if used.
		
		foreach $reason ( @attend ){
		    print qq{<option>$reason</option>};
		}
		print qq{</select></td></tr>\n};

	    }

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

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

	}  # Outer Loop here for each grade.

	print qq{</form>\n};
	
    } # End of Homeroom Method


    print qq{<script type="text/javascript">
 Calendar.setup({
   inputField  : "date",
   ifFormat    : "%Y-%m-%d",
   button      : "date_trigger",
   singleClick : false,
   step : 1
 });
 </script>\n};
    
    print qq{</body></html>\n};

} # end of enterAttendance

    


#-------------
sub mkDateData {
#-------------

    my ($jd, $weeks) = @_;
    my (%datedata, @days);
    
    # Build an array of ISO dates (YYYY-MM-DD) and a hash using them
    # as keys to hash values of 'Mon Jan 6' format.
    # If one week, then just 5 values, if two wk then 10, etc.
    my $counter = 7;
    if ( $weeks == 2 ) { $counter = 14; };

    
    for ( 1..$counter ){
	my ($yr,$mon,$day) = inverse_julian_day($jd);
	if ( length( $mon ) == 1 ) { $mon = '0'. $mon; }
	if ( length( $day ) == 1 ) { $day = '0'. $day; }
	
	my $dow = day_of_week($jd) + 1;
	if ( $dow == 1 or $dow == 7 ) {  # dow function returns 0 and 6
	    $jd++;
	    next; 
	} # skip Saturday, Sunday.
	my $date = qq{$yr-$mon-$day};
	    
	# Check if the school is closed.
	my $sth = $dbh->prepare("select id, dayfraction from dates where date = ?");
	$sth->execute( $date );
	my ( $id, $dayfrac ) = $sth->fetchrow;
	if ( $dayfrac > 0.99 ) {
	    $jd++;
	    next; 
	} # skip if closed all day
	    
	push @days, $date;
	$datedata{"$yr-$mon-$day"} = qq{$s_dow[$dow], $s_month[$mon] $day};
	$jd++;
    }

    # print "DAYS:", @days, "<br>\n";

    return \%datedata, \@days;
    
} # end of mkDateData


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

    print qq{<h1>$lex{'Student Attendance'} $lex{Entry}</h1>\n};

    print qq{<div style="margin:1em 2em;float:left;">\n};

    print qq{<form action="$self" method="post" style="margin:0.4em;">\n};
    print qq{<input type="hidden" name="method" value="homeroom">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" class="btn-grn" value="$lex{Homeroom} $lex{Attendance}"></form>\n};

    print qq{<form action="$self" method="post" style="margin:0.4em;">\n};
    print qq{<input type="hidden" name="method" value="multiday">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" class="btn-grn" value="$lex{Weekly} $lex{Attendance} HRm"></form>\n};
    
    print qq{<form action="$self" method="post" style="margin:1.6em 0 0 0.4em;">\n};
    print qq{<input type="hidden" name="method" value="subject">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" class="btn-grn" value="$lex{Subject} $lex{Attendance}"></form>\n};

    print qq{</div>\n};


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


    my %weekdays;
    
    if ( @hroom ) {  # this teacher is a homeroom teacher.

	
	if ( not $weekdays{$date} ) {
	    my $jd = julian_day( split('-',$date));
	    $weekdays{$date} = day_of_week($jd);
	}



	
	print qq{<div style="float:left;">\n};
	print qq{<h2>$lex{Previous} $lex{Attendance}</h2>\n};

	#    if ( $g_allowedit ){
	#	print qq{<form action="tattdeled.pl" method="post">\n};
	#	print qq{<input type="submit" value="$lex{Edit} $lex{Attendance}"></form>\n};
	#    }

	my $sth3 = $dbh->prepare("select a.*, s.lastname, s.firstname from attend a, student s 
          where a.studentid = s.studnum and s.homeroom = ? 
          order by a.absdate desc, s.lastname, s.firstname, a.period");

	foreach my $hroom ( @hroom ) {

	    my $counter;
	    $sth3->execute($hroom);
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	    while ( my $ref = $sth3->fetchrow_hashref ) {
		my %r = %$ref;

		# Update the weekday hash, if necessary.
		if ( not $weekdays{ $r{absdate} } ) {
		    my $jd = julian_day( split('-',$r{absdate}));
		    $weekdays{ $r{absdate} } = day_of_week($jd);
		}


		if ( not $counter ) {
		    print qq{<table cellpadding="4" cellspacing="0" border="1">\n};
		    print qq{<caption style="font-size:120%;font-weight:bold;">$lex{Homeroom} $hroom</caption>\n};
		    print qq{<tr><th>$lex{Name}</th><th>$lex{Date}</th><th>$lex{Period}</th></tr>\n};
		}
		
		if ( $g_allowedit ) {
		    my $id = $r{attid};
		    print qq{<tr><td><a href="tatted.pl?id=$id">\n};
		    print qq{<b>$r{lastname}</b>, $r{firstname}</a></td>\n};

		} else { # not allowed to edit
		    print qq{<tr><td><b>$r{lastname}</b>, $r{firstname}</td>\n};
		}

		print qq{<td>$dow[ $weekdays{ $r{absdate}} + 1], $r{absdate}</td>};
		print qq{<td class="cn">$r{period}</td></tr>\n};
		$counter++;
		if ( $counter > $g_attendview ) { last; }
	    }

	    if ( $counter ) { print qq{</table>\n}; }
	    
	} # end of this homeroom.

	print qq{</div>\n};
	
    } # end of homerooms
    
    print qq{</body></html>\n};

    exit;

} # end: showStartPage



#----------------
sub checkPassword {
#----------------

    my ($userid, $password) = @_;
    
    if (not $userid){ return -1;}
    if (not $password){ return -2;}

    #check for presence of userid
    my $sth = $dbh->prepare("select count(userid) from staff 
     where userid = ?");
    $sth->execute($userid);
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $count = $sth->fetchrow;
    if ($count < 1){ return -1;} # no userid

    #check for presence of correct password and userid
    my $sth = $dbh->prepare("select count(userid) from staff 
     where userid = ? and password = ? ");
    $sth->execute($userid, $password);
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $count = $sth->fetchrow;
    if ($count < 1){ return -2;} # not correct password

    return 0; # if all ok...

}


#------------------
sub checkCookieTime {
#------------------

    # Requires defaults of: $defaulttime, $maximumtime, $minimumtime
     $defaulttime = 20;
     $maximumtime = 60;
     $minimumtime = 3;

    my $duration = shift;

    if ($duration) { 
	$cookietime = $duration;
    } else { 
	$cookietime = $defaulttime;
    }  

    $cookietime = $minimumtime if $cookietime < $minimumtime; 
    $cookietime = $maximumtime if $cookietime > $maximumtime; 
    $cookietime = "+". $cookietime."m"; # set format
    
    return $cookietime;

}


#--------
sub login { # print error, login screen and die;
#--------

    # Requires $lex: Continue, UserId, Password, Cookie Duration, Please Log In

    my ( $error, $userid) = @_; # may not be present...

    if (not $error) { $error = $lex{'Please Log In'}; }
    print qq{$doctype\n<html><head><title>$error</title>\n};
    print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};
    print qq{$chartype\n</head>\n};
    print qq{<body onload="document.forms[0].elements[1].focus()">\n};
    print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};

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

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="method" value="$arr{method}">\n};
    print qq{<table cellpadding="4" cellspacing="1" border="0">\n};

    print qq{<tr><td class="bra">$lex{'User Id'}</td>\n};

    my $uservalue;
    if ( $userid ) {
	$uservalue = qq{value="$userid"};
    }

    print qq{<td><input type="text" name="userid" size="8" $uservalue></td></tr>\n};

    print qq{<tr><td class="bra">$lex{Password}</td>\n};
    print qq{<td><input type="password" name="password" size="8"></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Cookie Duration'}</td>\n};
    print qq{<td><input type="text" name="duration" size="4" value="20"></td></tr>\n};

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

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

    exit;

}
