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

# Update: March, 2010: Use $currterm for single track and %terms for
# multi-track. If terms are the same in multitrack, then collapsed
# into $currterm; subject entry rewritten as well.


my %lex = ('Term' => 'Term',
	   'Current Date' => 'Current Date',
	   'Periods per Day' => 'Periods per Day',
	   'Not Found' => 'Not Found',
	   'Student Attendance' => 'Student Attendance',
	   'Main' => 'Main',
	   'Enter Checks and Reasons for Students Missing ONLY' =>
	     'Enter Checks and Reasons for Students Missing ONLY',
	   'Date' => 'Date',
	   'Next Week' => 'Next Week',
	   'Previous Week' => 'Previous Week',
	   'Teacher' => 'Teacher',
	   'User Id' => 'User Id',
	   'Continue' => 'Continue',
	   'Cookie Duration' => 'Cookie Duration',
	   'Password' => 'Password',
	   'Please Log In' => 'Please Log In',
	   'Clear Prev Attendance' => 'Clear Prev Attendance',
	   'Submit Attendance' => 'Submit Attendance',
	   'Entry' => 'Entry',
	   'Subject' => 'Subject',
	   'Student' => 'Student',
	   'AM' => 'AM',
	   'PM' => 'PM',
	   'Reason' => 'Reason',
	   'Sel' => 'Sel',
	   'Edit' => 'Edit',
	   'Per' => 'Per',
	   'Name' => 'Name',
	   'Teacher' => 'Teacher',
	   'Room' => 'Room',
	   'Day In Cycle' => 'Day In Cycle',
	   'Period(s)' => 'Period(s)',
	   'Mode' => 'Mode',
	   'All Subjects Shown' => 'All Subjects Shown',
	   'Only Scheduled Subjects Shown' => 'Only Scheduled Subjects Shown',
	   'Method' => 'Method',
	   'Name' => 'Name',
	   'Error' => 'Error',
	   'Multiday' => 'Multiday',
	   'Late' => 'Late',
	   'Alt' => 'Alt',
	   'Add' => 'Add',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'Attendance' => 'Attendance',
	   'Record' => 'Record',
	   'Exists' => 'Exists',
	   'Select' => 'Select',
	   'Go' => 'Go',
	   'No Subjects Found' => 'No Subjects Found',
	   'School Closed' => 'School Closed',

	   );

my $self = 'tattentry0.pl';
my $weekcount = 1; # Number of weeks to do for entry. (normally 1 or 2)


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

# These 4 variables are now moved into admin.conf (2.40+)
# my $maxterms = 12; # maximum # of terms to search for.
if ( not $g_maxterms ) { $g_maxterms = 12 };

# 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";
}

#~~
# remove after version 5.00
if ( $multitrack or $multiTrack ) {
    $g_MultiTrack = 1;
}


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'}"); }
    if ($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') ){

	my $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 =~ /\+/)) { # if not in +20m format, do so.
	$duration = checkCookieTime( $duration );
    }

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


} # End of check for logged_in value

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


# Print HTML Page Header....
print "$doctype\n<html><head><title>$lex{'Student Attendance'}</title>
<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 "<style type=\"text/css\">.flt { float:left; }</style>\n";
print "$chartype\n</head><body>\n";

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

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

 
my $method;   # attendance entry 'method'
if ( $arr{method} ) {
    $method = $arr{method};
    delete $arr{method};

} else {
    showStartPage();
}


print "<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_termstart{1}; 
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 );
if ( $arr{date} ) {

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

    $currjd = julian_day($year,$month,$day);
    $dow = day_of_week($currjd);
    $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 {

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

    $currjd = julian_day($year,$month,$day);
    $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";

} 


if ( not %g_termstart ) {
    print "<h3>Starting Terms (g_termstart) $lex{'Not Found'}</h3>\n";
    print "</body><html>\n";
    exit;
}

# Figure out the current term(s).
my $currterm;
my %terms = ();

if ( %g_MTrackTerm ) {

    foreach my $trk ( 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.
	    }
	}
    }

    # now check if all those terms are the same, if so: set $currterm to that value.
    my $testterm;
    my $first = 1;
    my $flag = 1;
    foreach my $key ( keys %terms ) {
	if ( $first ) { $testterm = $terms{$key}; $first = 0; }
	if ( $testterm != $terms{$key} ) { $flag = 0; }
    }
    if ( $flag ) { 
	$currterm = $testterm;
	%terms = (); # not needed, since currterm is sufficient.
    }


} else { # use normal values.
    for my $term ( 1 .. $g_maxterms ) { # we now have a key and a term.
	if ( $g_termstart{$term} ) { # we have a value, create a matching one in jd.

	    my $startjd = julian_day( split /-/, $g_termstart{$term} );
	    my $endjd =  julian_day( split /-/, $g_termend{$term} );

	    if ( $currjd >= $startjd and $currjd <= $endjd ) { # we have the term.
		$currterm = $term;
		last;
	    }
	}
    }
}


# 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 "<h3>$lex{'Periods per Day'} &ndash; $lex{'Not Found'}!</h3>\n";
    print "</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)
mkDateData($mondayjd,$weekcount);


# 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;
}


# Rest of Top of Page...
print "<h1 style=\"display:inline;padding:0.5em 0 0.5em 3em;\">\n";
print "$lex{'Student Attendance'} $lex{Entry} &ndash; <i>";
if ( %terms ) { 
    foreach my $trk ( sort keys %terms ) { 
	my $trm = $terms{$trk};
	print "$trm ";
	#print "$g_TermDisplay{$trk}{$trm}:$trm ";
    }
} else {
    print " $g_TermDisplay{$g_DefaultTrack}{$currterm}";
}
print "</i></h1>\n";


# Start Table
print "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr>\n";
print "<td width=\"30%\" valign=\"top\">\n<!--   ********** Column #1 *********  -->\n";


# Get Teacher Attendance Values, Left Column
my $sth3 = $dbh->prepare("select * from tattend where techid = ? order by date desc");
$sth3->execute( $userid );
if ($DBI::errstr){ print $DBI::errstr; die;}
$trows = $sth3->rows;


# Limit View to the $g_teachview value (set in admin.conf)
if ( $trows > $g_teachview ){ $trows = $g_teachview; }

print "<h2>$lex{Teacher} $lex{Attendance}</h2>\n";
print "<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\">\n";
print "<tr><th>$lex{'User Id'}</th><th>$lex{Date}</th></tr>\n";

for (1..$trows){
    @tattend = $sth3->fetchrow;
    print "<tr><td>$tattend[1]</td><td>$tattend[2]</td></tr>\n";
}
print "</table>\n";


if ( $method ne 'subject' ){ # Not High School Entries

    print "<h2>$lex{Previous} $lex{Attendance}</h2>\n";

    foreach my $hroom ( @hroom ) {
	if ( $g_allowedit ){
	    print "<form action=\"tattdeled.pl\" method=\"post\">\n";
	    print "<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");

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

	# Only print the value of $g_attendview attendance records
	if ($rows > $g_attendview) {
	    $rows = $g_attendview;
	}

	print "<table><tr><th>$lex{Name}</th><th>$lex{Date}/$lex{Per}</th></tr>\n";

	for ( my $i=1; $i <= $rows; ++$i) {

	    my $ref = $sth3->fetchrow_hashref;
	    if ( $g_allowedit ) {
		my $id = $ref->{id};
		print "<tr><td><a href=\"tatted.pl?id=$id\">\n";
		print "<b>$ref->{lastname}</b>, $ref->{firstname}</a></td>\n";

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

	    print "<td>$ref->{date}/$ref->{period}</td></tr>\n";
	}
	print "</table>\n";
    }

} # End of Not Subject Method



# Start Right Column - Attendance Proper
print "</td><td width=\"70%\" valign=\"top\">
<!--   ********** Column #2 *********  -->
<center>\n";

print "<table border=\"1\" cellpadding=\"6\" cellspacing=\"0\"><tr><td>\n";
print "<div style=\"text-align:center;font-size:140;\">\n";
print "$lex{'Enter Checks and Reasons for Students Missing ONLY'}</div>\n";
print "</td></tr></table>\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 "<div style=\"padding:0.5em;\">\n";
print"<form action=\"$self\" method=\"post\" style=\"display:inline;\">
  <input type=\"hidden\" name=\"date\" value=\"$prevdate\">
  <input type=\"hidden\" name=\"method\" value=\"$method\">
  <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 "<form action=\"$self\" method=\"post\" style=\"display:inline;\">
  <input type=\"hidden\" name=\"method\" value=\"$method\">
  <input type=\"hidden\" name=\"date\" value=\"$nextdate\">
  <input type=\"submit\" value=\"$lex{'Next Week'} =>\"></form>\n";

# Pop Up Calendar Date Selector
print "<form action=\"$self\" method=\"post\" ";
print "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{<button type="reset" id="date_trigger">$lex{Select} $lex{Date}</button>\n};
print "<input type=\"text\" name=\"date\" id=\"date\" size=\"10\">\n";
print "<input type=\"submit\" value=\"$lex{Go}\">\n";
print "</form></div>\n\n";


my $sth = $dbh->prepare("select id, dayfraction from dates where date = ?");

# Main Attendance Entry begins here.
if ( $method ne 'multiday' ) { 
    # multiday calls a different script to allow for reason entry
    # before going to confirmation in tattentry1 script.


    if ( $method ne 'subject' ) {

	print "<form action=\"tattentry1.pl\" method=\"post\">\n";
	print "<input type=\"hidden\" name=\"name\" value=\"$userid\">\n";
	print "<input type=\"hidden\" name=\"method\" value=\"$method\">\n";

	print "<b>$lex{Date}</b>: <select name=\"date\">\n";
	for my $i (1..5) {
	    my ($wkyear, $wkmonth, $wkday) = inverse_julian_day($mondayjd);
	    my $activedate = "$wkyear-$wkmonth-$wkday";
	    my $dow = day_of_week( $mondayjd ) + 1;

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

	    print qq{<option };
	    if ($wkmonth == $month and $wkday == $day) {
		print " selected";
	    }
	    print " value=\"$activedate\">$dow[$dow], $activedate</option>\n";

	    $mondayjd++;
	}
	print "</select><p></p>\n\n\n";


    } else { # subject method

	for my $i ( 1..5 ) {

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

	    # NEW 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.999 ) { # ie. only 1.000, closed all day, skip
		$mondayjd++;
		next;
	    }

	    print "<form action=\"$self\" method=\"post\" style=\"display:inline;\">\n";
	    print "<input type=\"hidden\" name=\"date\" value=\"$tmpdate\">\n";
	    print "<input type=\"hidden\" name=\"method\" value=\"$method\">\n";
	    print "<input type=\"submit\" value=\"$dow[$dow] $month[$wkmonth] $wkday\"></form>\n";

	    $mondayjd++;
	}

	print "<form action=\"tattentry1.pl\" method=\"post\">\n";
	print "<input type=\"hidden\" name=\"name\" value=\"$userid\">\n";
	print "<input type=\"hidden\" name=\"method\" value=\"$method\">\n";
	print "<input type=\"hidden\" name=\"date\" value=\",$currdate\">\n";

	print "<div style=\"padding:0.4em;\">$lex{Date}: ";
	print "<span style=\"font-weight:bold;font-size:120%;\">$currdate</span>\n";
	print "</div>\n";

    }

}


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

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

    # Get Subjects on currdate;
    my %subjects = findCurrentSubjects( $userid, $currdate, $dbh );
    if ( not %subjects ) {
	print "<h1>$lex{'No Subjects Found'}</h1>\n";
	print "</body></html>\n";
	exit;
    }
    # returned hash has {subjsec} = '1 3' space separated periods today...
    # print "Subjects:", %subjects, "<br>\n";


    # 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 "<h1>$lex{'School Closed'}</h1>\n";
	print "</body></html>\n";
	exit;
    }


    print "<div>\n";

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

    # Late / Alternate Reasons Box
    print "&nbsp;&nbsp;<span style=\"border:1px solid gray;padding:0.25em;\">";
    print "$lex{Add} $lex{Late}/$lex{Alt} $lex{Reason}";
    print " <input type=\"checkbox\" name=\"latemode\" value=\"1\"></span>\n";
    print "</div>\n";


    # print hyperlink row
    print "<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 "<a href=\"". q{#}. "$subjsec\">$smdesc". '-'. "$section</a> ";
    }
    print "]</div>\n";

    # Prep - Subject Name
    my $sth2 = $dbh->prepare("select description from subject where subjsec = ?");
    # Timetable entries?
    my $sth3 = $dbh->prepare("select count(*) from schedat where subjsec = ?");

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

    # Loop Through Subjects
    foreach my $subjsec ( sort keys %subjects ) {

	# Do we have a timetable for this subject?
	$sth3->execute( $subjsec );
	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;
	}


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

	# Get the students studnums.
	$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 "<h3>$description ($subjsec) - $lex{'No Student(s) Found'}</h3>\n";
	    next;
	}

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

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

	print "<tr><td colspan=\"3\" class=\"cn\">\n";
	print "<input type=\"reset\" value=\"$lex{'Clear Prev Attendance'}\">\n";
	print "<input type=\"submit\" value=\"$lex{'Submit Attendance'}\"></td></tr>\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 = "<span style=\"color:red;\">$lex{Student} $lex{'Not Found'}</span>";
	    }

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


	    if ( @periods ) { 
		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 > 0 ) {
			#print "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"P$per<input type=\"checkbox\" name=\"$studnum:$subjsec:$per\" value=\"1\">\n";
		    }

		}
	    } else { # no defined periods today
		if ( $maxppd == 2 ) { # use am/pm
		    my %ampm = ('1' => "$lex{AM}", '2' => "$lex{PM}");
		    for (1..2){ 
			print"$ampm{$_}<input type=\"checkbox\" name=\"$studnum:$subjsec:$_\" value=\"1\">\n";
		    }
		} else { # maxppd is not 2
		    for (1..$maxppd){ 
			print"P$_<input type=\"checkbox\" name=\"$studnum:$subjsec:$_\" value=\"1\">\n";
		    }
		}
	    }

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

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

	}

	print "<tr><td colspan=\"3\" class=\"cn\">\n";
	print "<input type=\"reset\" value=\"$lex{'Clear Prev Attendance'}\">\n";
	print "<input type=\"submit\" value=\"$lex{'Submit Attendance'}\"></td></tr>\n";
	print "</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') {

    print "<form action=\"tattentry1.pl\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"method\" value=\"$method\">\n";
    print "<input type=\"hidden\" name=\"latemode\" value=\"1\">\n";

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

    # @hroom loaded at top of script for teacher.
    foreach my $hroom ( @hroom ) {
	
	$sth->execute( $hroom );
	if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n";}    

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

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

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

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

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

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

    } # End of This Homeroom (in case of multiple)

} # End of Multi-Day Method


#====== Homeroom Method =========
else { # If not Subject, MultiDay, then use Homeroom (hroom)

    print "<p><span style=\"border:1px solid gray;padding:0.25em;\">\n";
    print $lex{Add}. ' '. $lex{Late}. '/'. $lex{Alt}. ' ', $lex{Reason};
    print " <input type=\"checkbox\" name=\"latemode\" value=\"1\"></span></p>\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 = "$tsal $tfirstname $tlastname"; 
    } else {
	$teacher = "$tfirstname $tlastname";
    }

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

    foreach my $hroom ( @hroom ) {
	$hroom =~ s/\s+//g;
	$sth->execute($hroom);
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	$rows = $sth->rows;

	# Now get the maxppd by using the homeroom
	my $maxppd = 0;
	my $sth1 = $dbh->prepare("select distinct grade from student where homeroom = ?");
	$sth1->execute( $hroom );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $grade = $sth1->fetchrow ) {
	    if ( $g_ppd{$grade} > $maxppd ) { 
		$maxppd = $g_ppd{$grade}; 
	    }
	}

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

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

	print "<tr><td colspan=\"4\" align=\"center\">\n";
	print "<input type=\"reset\" value=\"$lex{'Clear Prev Attendance'}\">\n";
	print "<input type=\"submit\" value=\"$lex{'Submit Attendance'}\"></td></tr>\n";

	print "<tr><th>$lex{Student}</th><th>";
	if ( $maxppd == 1 ) {
	    print $lex{Sel};
	} else {
	    print $lex{AM}. "</th><th>". $lex{PM};
	} 
	print "</th><th>". $lex{Reason}. "</th></tr>\n";

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

	    print "<tr><td><b>$lastname</b>, $firstname</td>\n";
	    print "<td><input type=\"checkbox\" name=\"$studnum:1\" value=\"1\"></td>\n";
	    if ( $maxppd != 1 ) {
		print "<td><input type=\"checkbox\" name=\"$studnum:2\" value=\"1\"></td>\n";
	    }
	    print "<td><select name=\"$studnum:\:Reason\"><option></option>\n";
    
	    foreach $reason ( @attend ){
		print "<option>$reason</option>\n";
	    }
	    print "</select></td></tr>\n";

	}

	print "<tr><td colspan=\"4\" align=\"center\">\n";
	print "<input type=\"reset\" value=\"$lex{'Clear Prev Attendance'}\">\n";
	print "<input type=\"submit\" value=\"$lex{'Submit Attendance'}\"></td></tr>\n";

	print "</table><p></p>\n";

    }  # Outer Loop here for each grade.

} # End of Else Method (Homeroom)

print "</form></center></td></tr></table>\n";

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

print "</body></html>\n";




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

    my ($jd, $weeks) = (@_);
    # Build an array of ISO dates 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.
    for (1..$weeks){
	for (1..5){
	    my ($yr,$mon,$day) = inverse_julian_day($jd);
	    my $dow = day_of_week($jd) + 1;
	    push @days, "$yr-$mon-$day";
	    $datedata{"$yr-$mon-$day"} = "$s_dow[$dow], $s_month[$mon] $day";
	    $jd++;
	}
	$jd = $jd + 2; # skip over weekend.
    }
}


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

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

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

    print "<form action=\"$self\" method=\"post\">\n";
    print qq{<input type="hidden" name="method" value="homeroom">\n};
    print qq{<input type="submit" value="$lex{Homeroom} $lex{Attendance}"></form>\n};

    print "<p></p>\n";

    print "<form action=\"$self\" method=\"post\">\n";
    print qq{<input type="hidden" name="method" value="subject">\n};
    print qq{<input type="submit" value="$lex{Subject} $lex{Attendance}"></form>\n};

    print "<p></p>\n";

    print "<form action=\"$self\" method=\"post\">\n";
    print qq{<input type="hidden" name="method" value="multiday">\n};
    print qq{<input type="submit" value="$lex{Multiday} $lex{Attendance}"></form>\n};

    print qq{</div>\n};

    print "</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 = 5;
     $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 "$doctype\n<html><head><title>$error</title>\n";
    print "<link rel=\"stylesheet\" href=\"$tchcss\" type=\"text/css\">\n";
    print "$chartype\n</head>\n";
    print "<body onload=\"document.forms[0].elements[1].focus()\">\n";
    print "[ <a href=\"$tchpage\">$lex{Main}</a> ]\n";

    print "<center><h1>$error</h1>\n";

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

    print "<tr><td align=\"right\">$lex{'User Id'}</td>\n";

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

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

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

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

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

    print "</center></body></html>\n";

    exit;

}
