#!/usr/bin/perl
#  Copyright 2001-2021 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 = ('Periods per Day' => 'Periods per Day',
	   'Main' => 'Main',
	   'Date' => 'Date',
	   'Next Week' => 'Next Week',
	   'Previous Week' => 'Previous Week',
	   'Subject' => 'Subject',
	   'Student' => 'Student',
	   'Error' => 'Error',
	   'Add' => 'Add',
	   'Attendance' => 'Attendance',
	   'Record' => 'Record',
	   'Exists' => 'Exists',
	   'Select' => 'Select',
	   'Go' => 'Go',
	   'Term' => 'Term',
	   'More' => 'More',
	   'Skipping' => 'Skipping',
	   'No Absences Found' => 'No Absences Found',
	   'Contact' => 'Contact',
	   'Saved' => 'Saved',
	   'Not Found' => 'Not Found',

    );

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

my $self = 'attAddCrsWeek.pl';


# Since we may run in admin or teacher site.
my $configpath;
my $teachermode;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.

} else {
    $configpath = '../..'; # go back two to get to etc.
}


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

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


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


my $q = CGI->new;
my %arr = $q->Vars; # Get passed values

if ( $teachermode ) {
    $css = $tchcss;
    $homepage = $tchpage;
}

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

# Print top of page
my $title = qq{$lex{Add} Subject/Course $lex{Attendance}};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{<link rel="stylesheet" type="text/css" media="all" href="/js/calendar-blue.css" title="blue">
<script type="text/javascript" src="/js/calendar.js"></script>
<script type="text/javascript" src="/js/lang/calendar-en.js"></script>
<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};
print qq{<style>.btn-gray {
  width:100px; height:40px; margin:10px; border-radius:10px;
  background-color:#888; color:#FFF; font-size:150%;  font-weight:bold; border:1px solid gray;
}</style>\n};


print qq{$chartype\n</head><body style="margin:1em;">\n};

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

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

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


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

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

    foreach my $key ( keys %arr ) {
	my ($type,$fld) = split(':', $key);
	if ( $type eq 'U' ) { # userid
	    $userid = $fld;
	} #elsif ( $type = 'D' ) { # date
	  #  $date = $fld;	}
    }

    if ( $teachermode and not $userid ) {
	$userid = $ENV{'REMOTE_USER'};
    }
    
    # print "Userid:$userid<br>\n";
    
    # Load Teacher / Userid name
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth->execute($userid);
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my ($tchlastname,$tchfirstname) = $sth->fetchrow;
    if ( not $tchlastname ) {
	print qq{<h3>Staff Member not found!</h3>\n};
    }

    print qq{<span style="font-weight:bold;font-size:120%;">$tchfirstname $tchlastname</span>\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 $startjd = julian_day( split('-',$schoolstart));
    my $endjd = julian_day(split('-',$schoolend));
    my ( $year, $month, $day ); # now global for homeroom entry method
    
    my ($currdate, $mondayjd, $currjd, $dow, $dayfraction );
    
    if ( $arr{date} ) { # passed a date;
	$currjd = julian_day(split('-',$arr{date}));
	$dow = day_of_week($currjd); # for use below in subject att entry
	$mondayjd = $currjd - ($dow-1);
	$currdate = join('-', inverse_julian_day($currjd));

    } 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 - ($dow-1); #This will now give Monday of that week.
	$currdate = "$year-$month-$day";
    } 

    # Figure out the current term(s) for each track.
    my ($currterm, %terms, %grade2terms, %track2grades ); #%track2grades{track} = @grades.

    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.
	    }
	}
    }

    # 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};
	push @{ $track2grades{$track}}, $gr; # used to display grade and term at line~1036
	$grade2terms{$gr} = $terms{$track};
    }

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

    # foreach my $track ( sort keys %track2grades ) {
    #  print "Track:$track Grades: ", @{ $track2grades{$track} }, "<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'} in Configuration!</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

   
    # Setup Array and Hash to hold Dates and DOW Dates (Multi-Day Method)
    my $weekcount = 1; # we're not doing 2!
    my ($ddref, $dayref) = mkDateData($mondayjd,$weekcount);
    my @days = @$dayref;
    my %datedata = %$ddref;
#    foreach my $key ( sort keys %datedata ) {
#	print "K:$key DateData:$datedata{$key}<br>\n";
#    }
    

    # Rest of Top of Page...
    print qq{<h1 style="display:inline;padding:0.5em 0 0.5em 3em;">\n};
    my $firstview = 1;
    foreach my $trk ( sort keys %terms ) { 
	my $trm = $terms{$trk};
	my @grades = sort {$a <=> $b} @{ $track2grades{$trk} } ;
	my $gradestring = qq{$grades[0]-$grades[-1]};
	#	my $gradestring = join(',', sort {$a <=> $b} @{ $track2grades{$trk} } );
	if ( not $firstview ) { print qq{ | }; }
	print qq{ Grade <b>$gradestring</b> <b>$lex{Term}</b> $trm};
	$firstview = 0;
    }
    print qq{</h1>\n};
    
    
    # Weekly Date Calcs - Previous Week / Next Week.
    my $prevjd = $mondayjd - 7;
    if ( $prevjd < $startjd ){ $prevjd = $startjd;}
    my $prevdate = join('-', inverse_julian_day($prevjd));

    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="page" value="1">\n};
    print qq{<input type="hidden" name="U:$userid" value="1">\n};

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

    my $nextjd = $mondayjd + 7; 
    if ($nextjd > $endjd){ $nextjd = $endjd;}
    my $nextdate = join('-', inverse_julian_day($nextjd));

    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="date" value="$nextdate">\n};
    print qq{<input type="hidden" name="U:$userid" 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.5em;};
    print qq{border:1px solid gray;">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="U:$userid" 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};

    
    # 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="userid" value="$userid">\n};

    print qq{<div><input class="btn-gray" type="submit" Value="Save"></div>\n};

    # Main Loop
    foreach my $day (@days){
	dailyAttendance($userid, $day, \%grade2terms,\%datedata, $dbh);
    }

    print qq{<br clear="left"><div><input class="btn-gray" type="submit" Value="Save"></div>\n};
    print qq{</form>\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 qq{<body></html>\n};

    
} # end of enterAttendance



#------------------
sub dailyAttendance {
#------------------

    my ($teacher,$date,$grade2termsRef, $datedataref, $dbh) = @_;
    # Also need grade2term so we can pick teacher current courses.
    my %gradeToTerms = %{$grade2termsRef}; # note name change
    my %datedata = %{$datedataref};

    # Get Date info.
    my $jd = julian_day( split('-',$date));
    my $dow = day_of_week( $jd );
    my ($y,$m,$d) = split('-',$date);
    my $fmtdate = qq{$month[$m] $d};

    
    # Get Current Courses.
    my $sth = $dbh->prepare("select * from subject where teacher = ?");
    my $sth1 = $dbh->prepare("select count(*) from eval where subjcode = ?");

    $sth->execute( $teacher );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my (%courses, %smallcourses, %courseTerm );
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %s = %$ref;
	my $grade = $s{grade};
	my $currterm = $gradeToTerms{$s{grade}};
#	print qq{<div>$s{subjsec} / $s{grade} / $gradeToTerms{$s{grade}}</div>\n};
	if ( $currterm >= $s{startrptperiod} and $currterm <= $s{endrptperiod} ) {

	    # Check for Course Enrollments
	    $sth1->execute( $s{subjsec} );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my $enrolled = $sth1->fetchrow;
	    #if ( not $enrolled ) { print qq{Skipping $s{description}/$s{subjsec}<br>\n}; next; }
	    
	    $courses{$s{subjsec}} = $s{description};
	    $smallcourses{$s{subjsec}} = $s{smdesc};
	    $courseTerm{ $s{subjsec}} = $gradeToTerms{ $s{grade}}; 
	}
    }

#    foreach my $subjsec ( sort keys %courses ) {
#	print qq{<div>$subjsec / $courses{$subjsec} / $smallcourses{$subjsec}</div>\n};
#    }


    # Get DayInCycle
    my $dayincycle = findDayInCycle( $date, $dbh );
    # print "Day In Cycle $dayincycle</br>\n";
    
    # Get courses taught today along with their period.
    my %periods; # periods{subjsec} = period
    my $sth = $dbh->prepare("select period from schedat where subjsec = ? and day = ? and term = ?");
    foreach my $subjsec ( keys %courses ) {
	my $term = $courseTerm{ $subjsec };
	$sth->execute( $subjsec, $dayincycle, $term );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $period = $sth->fetchrow;
#	print qq{<div>Term $term / $subjsec / $period</div>\n};
	if ( $period ) { # timetable today.
	    $periods{$subjsec} = $period;
	}
    }

    # Now reverse
    my %revperiods; # {period} = @subjsecs.
    foreach my $subjsec ( keys %periods ) {
	my $period = $periods{$subjsec};
	push @{ $revperiods{$period} }, $subjsec;
    }

# Testing    
#    foreach my $subjsec ( sort keys %periods ) {
#	print qq{<div>$courses{$subjsec} $subjsec / $periods{$subjsec}</div>\n};
#    }

    # Get students enrolled in courses today, and sort by name
    my (%studname, @studsort);
    
    my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    my $sth2 = $dbh->prepare("select count(*) from studentwd where studnum = ?");
    # check for existing attendance record
    my $sth3 = $dbh->prepare("select attid from attend where studentid = ? 
			     and absdate = ? and period = ? and subjsec = ? ");


    
    my $sth = $dbh->prepare("select distinct studnum from eval where subjcode = ?");

    my %eval; # eval{subjsec}{studnum} = 1;
    my @notInSchool;
    foreach my $subjsec ( keys %periods ) {
	$sth->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $studnum = $sth->fetchrow ) {
	    
	    # Get Name, and check for wd
	    $sth1->execute( $studnum );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname, $firstname ) = $sth1->fetchrow;

	    $sth2->execute( $studnum );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my $wd = $sth2->fetchrow;
	    if ( $wd ) {
		push @notInSchool, qq{$firstname $lastname ($studnum)};
#		print qq{<div><b>$firstname $lastname</b> ($studnum) };
#		print qq{not enrolled in school. Skipping!</div>\n};
		next;
	    }

	    $studname{$studnum} = qq{<b>$lastname</b>, $firstname};
	    $studsort{"$lastname$firstname$studnum"} = $studnum;
	    $eval{$subjsec}{$studnum} = 1; # needed to track which students in which course for att
	}
    }

    if ( not %eval ) {
	print qq{<h3>$fmtdate - No Courses Enrolled</h3>\n};
	return;
    }

    # SUMMARY: We now have periods scheduled today, and we have the students.
    
    # Now Display the table for Attendance Entry
    print qq{\n\n<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:0.5em;">\n};
    print qq{<caption style="font-weight:bold;font-size:120%;">};
    print qq{$datedata{$date} / Day $dayincycle</caption>\n};
    # First Row - Courses.
    print qq{<tr><th></th>};
    foreach my $period ( sort keys %revperiods ) {
	my @courses = @{ $revperiods{$period} };
	foreach my $subjsec ( @courses ) {
	    print qq{<th title="$courses{$subjsec} / $subjsec">$smallcourses{$subjsec}</th>};
	}
    }
    print qq{</tr>\n};
    
    # Second Row - Perfect Attendance
    print qq{<tr style="background-color:#DDD;font-weight:bold;font-size:120%">};
    print qq{<td>Perfect Attendance</td>\n};
    foreach my $period ( sort keys %revperiods ) {
	my @courses = @{ $revperiods{$period} };
	foreach my $subjsec ( @courses ) {
	    print qq{<td title="$courses{$subjsec}/$subjsec" class="cn">Period $period };
	    print qq{<input type="checkbox" name="PA:$subjsec:$date:$period" value="1"></td>};
	    #PA:subjsec:date:period - value of the 'name' of checkbox.
	}
    }
    print qq{</tr>\n};

    # Following Rows - all students.
    foreach my $key ( sort keys %studsort ) {
	print qq{<tr>};	
	my $studnum = $studsort{$key};
	print qq{<td>$studname{$studnum}</td>};
    
	foreach my $period ( sort keys %revperiods ) {
	    my @courses = @{ $revperiods{$period} };
	    foreach my $subjsec ( @courses ) {
		if ( $eval{$subjsec}{$studnum} ) {

		    # Check for an existing attendance entry.
		    $sth3->execute($studnum,$date,$period, $subjsec );
		    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		    my $attid = $sth3->fetchrow;
		    print qq{<td title="$courses{$subjsec} / $subjsec" class="bcn">};
		    
		    if ( $attid ) { # attendance already done.
			print qq{Complete</td>\n};
		    } else {

			# Block for Attendance Entry/Reason
			print qq{<select name="$studnum:$subjsec:$date:$period"><option></option>\n};
			foreach my $rsn ( @attend ) {
			    print qq{<option>$rsn</option>};
			}
			print qq{</select></td>\n};
		    }
		} else {
		    print qq{<td></td>};
		}
		
	    }
	}
	print qq{</tr>\n};
	
    }

    # Students Not Enrolled in School
    if ( @notInSchool ) {
	print qq{<tr><td colspan = "5">};
	print qq{<b>Not In School - Skipped</b><br>\n};
	foreach my $stud ( @notInSchool ) {
	    print qq{$stud<br>\n};
	}
	print qq{</td></tr>\n};
    }
    
    print qq{</table>\n};

    return;

} # end of dailyAttendance (table)



#-------------
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);
	if ( $dow == 0 or $dow == 6 ) {  # 0 is Sunday, 6 is Saturday
	    $jd++;
	    next; 
	} # skip Saturday, Sunday.
	my $date = qq{$yr-$mon-$day};
	    
	# Check if the school is closed all day.
	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{$dowstd[$dow], $month[$mon] $day};
	$jd++;
    }

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

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




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

    #foreach my $key ( sort keys %arr ) {
    # if ( not $arr{$key} ) { next; }
    # print "K:$key V:$arr{$key}<br>\n";
    #}
    
    # Strip passed userid.
    my $userid = $arr{userid};
    delete $arr{userid}; 

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

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

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

    
    foreach my $key ( keys %arr ) {
	if ( not $arr{$key} ) { next; } # skip no reasons/PA have 1 values.
	my ( $studnum,$subjsec,$date,$period ) = split(':',$key);
	if ( $studnum eq 'PA' ) { next;	}; # pa done below

	my $reason = $arr{$key}; # reason is value of hash element.

	# Get Student Name
	if ( not exists $studname{$studnum} ) { # add it in.
	    $sth2->execute( $studnum );
	    if ( $DBI::errstr ) { print $DBI::errstr;die $DBI::errstr; }
	    my ($lastname, $firstname ) = $sth2->fetchrow;
	    if ( not $lastname ) { $lastname = qq{Name Missing}; }
	    $studname{$studnum} = qq{<b>$lastname</b>, $firstname};
	}
	
	my $name = $studname{$studnum};

	
	$first = 0;
	my @values;
	my @fieldnames = @fields;
	my @qst = qw(? ? ? ? ?); # 5 fields


	push @values, $studnum, $date, $reason, $period, $subjsec;


#	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, course).
	$sth1->execute( $studnum, $date, $period, $subjsec );
	if ( $DBI::errstr ) { print $DBI::errstr;die $DBI::errstr; }
	my $count = $sth1->fetchrow;
	if ( $count ) {
	    print qq{<h4>$name $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 )");
	
	$sth->execute( @values );
	if ( $DBI::errstr ) { print $DBI::errstr;die $DBI::errstr; }
	print qq{<div>Added $name / $subjsec / $date / $period / $reason</div>\n};
	
    } # End of ForEach loop


    if ( $first ) { # no attendance entries done; perfect attendance done below
	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{$DBI::errstr</h3>\n};
    }


    
    # Now do teacher attendance entries, including perfect attendance

    # 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.
    my %tchatt; # hold list of teacher attendance already done.
    
    foreach my $key ( keys %arr ) {
	if ( not $arr{$key} ) { next; } # skip no reasons
	
	my ( $studnum,$subjsec,$date,$period ) = split(':',$key);
	my $tchkey = qq{$userid:$subjsec:$date:$period};

	# Check if added already to tattend (teacher attendance) table.
	if ( not $tchatt{$tchkey} ) { # teacher att record not yet added.
	    # Add to tchatt hash and also tattend entry
	    print qq{<div><b>Add Teacher Entry</b> $userid / $subjsec /$date / $period</div>\n};
	    $sth->execute( $userid, $date, $subjsec, $period );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    $tchatt{$tchkey} = 1;
	}
	    
    } # end of %arr loop adding teacher attendance
    

    # Add more Attendance Records
    print qq{<div style="font-weight:bold;">};
    print qq{$lex{Add} $lex{More} Weekly Course $lex{Attendance}</div>\n};
    
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="submit" value="$lex{Add} $lex{Attendance}"></form>\n};

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

    exit;

} # end of writeAttendance


#----------------
sub selectTeacher {
#----------------

    # select a teacher that does course attendance;
    # Get Name
    my $sth1 = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    my $sth2 = $dbh->prepare("select count(e.id) from eval e, subject s 
			     where e.subjcode = s.subjsec and s.teacher = ?");
    
    my (%teachers, %sort);
    my $sth = $dbh->prepare("select distinct teacher, grade from subject 
			    where teacher is not null and teacher != ''");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my ($userid, $grade) = $sth->fetchrow ) {
	if ( not $g_AttendanceEntryMethod{$grade} eq 'subject' ) { next; }

	# Check for enrollments
	$sth2->execute( $userid );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $enrolcount = $sth2->fetchrow;
	if ( not $enrolcount ) { next; }

	# Get name
	$sth1->execute( $userid );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth1->fetchrow;
	if ( not $lastname ){ next; } # skip withdrawn teachers (but still set in course)
	$teachers{$userid} = qq{$lastname, $firstname};
	$sort{"$lastname$firstname$userid"} = $userid;
    }

    # Start Form
    print qq{\n<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    
    # Start Table
    print qq{\n<table cellpadding="3" border="0" cellspacing="0" };
    print qq{style="border:1px solid gray;margin:1em;padding:0.5em;">\n\n};
    print qq{<caption style="font-weight:bold;">Select Teacher</caption>\n};
    print qq{<tr><th>Course/$lex{Subject} $lex{Attendance}</th></tr>\n\n};

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

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