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

#  This file is part of Open Admin for Schools.

# Passed as "group": Accept Grade, Class, or All for group to 
# find for attendance.
# Passed as "mode": Weekly or Biweekly Mode. (or Date Range?)
# Passed as "class": The value of the group: ie. 8c, 10.

my %lex = ( 'Add' => 'Add',
	    'Multi-Day' => 'Multi-Day',
	    'Attendance' => 'Attendance',
	    'Date' => 'Date',
	    'Name' => 'Name',
	    'Continue' => 'Continue',
	    'Error' => 'Error',
	    'Weekly' => 'Weekly',
	    'Select by' => 'Select by',
	    'Grade' => 'Grade',
	    'Homeroom' => 'Homeroom',
	    'Weekly' => 'Weekly',
	    'Biweekly' => 'Biweekly',
	    'Continue' => 'Continue',
	    'Mode' => 'Mode',
	    'Blank=All' => 'Blank=All',
	    'Sort by' => 'Sort by',
	    'Separate with Spaces' => 'Separate with Spaces',
	    'No Student(s) Found' => 'No Student(s) Found',
	    'Start Date' => 'Start Date',
	    'Period' => 'Period',
	    'Reason' => 'Reason',
	    'Late' => 'Late',
	    'Subject' => 'Subject',
	    'Record(s) Stored' => 'Record(s) Stored',
	    'Contact' => 'Contact',
	    'Missing' => 'Missing',
	    'Reason' => 'Reason',
	    'Skipping' => 'Skipping',
	    'Save' => 'Save',
	    'Start Page' => 'Start Page',
	    'Previous Week' => 'Previous Week',
	    'Next Week' => 'Next Week',
	    'AM' => 'AM',
	    'PM' => 'PM',
	    'Show' => 'Show',
	    'Withdrawn' => 'Withdrawn',
	    'Students' => 'Students',
	    'WD' => 'WD',
	    'Perfect Attendance' => 'Perfect Attendance',
	    'Main' => 'Main',
	    
	    );

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

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

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

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


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

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


# Set Default Date
my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
my $day = @tim[3];
my $currdate = "$year-$month-$day";


my $title = "$lex{Add} $lex{Homeroom} $lex{Attendance} - $lex{'Multi-Day'}";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};


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

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

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

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

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

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



#-------------
sub setReasons {
#-------------

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

    # Form start
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="hidden" name="homeroom" value="$arr{homeroom}">\n};
    print qq{<input type="submit" value="$lex{Save}">\n};

    # Table and Heading
    print qq{<table border="1" cellspacing="0" cellpadding="3">\n};
    print qq{<tr><th>$lex{Name}</th><th>$lex{Date}/$lex{Period}};
    print qq{</th><th>$lex{Reason}</th><th>$lex{Late}</th></tr>\n};
    # Not used, yet.<th>$lex{Subject}</th></tr>\n};

    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    my $sth1 = $dbh->prepare("select distinct subjcode from eval where studnum = ?");
    my $sth2 = $dbh->prepare("select description from subject where subjsec = ?");
    my %subjects;


    foreach my $key ( sort keys %arr ) {

	my ( $studnum, $date, $period ) = split(/:/, $key);

	if ( $studnum eq 'PA' ) {
	    print qq{<input type="hidden" name="$key" value="1">\n};
	    next;
	}

	# print qq{SN:$studnum DT:$date PER:$period<br>\n};
	if ( not $period ) {
#	    print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
	    next; 
	} # skip 5 other passed values; pass through to next function.

	
	my $jd = julian_day( split(/-/, $date));
	my $dow = day_of_week( $jd ) + 1; # since not 0-6,but 1-7 for @dow

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

=head
	# Check/Get Subjects
	if ( not $subjects{$studnum} ) {
	
	    $sth1->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	    $subjects{$studnum} = [ ]; # create array
	
	    while ( my $subjsec = $sth1->fetchrow ) {

		# Get Description
		$sth2->execute( $subjsec );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
		my $desc = $sth2->fetchrow;
		$desc =~ s/\(/ /g;

		push @{$subjects{$studnum}}, "$desc ($subjsec)";
	    }
	}
=cut

	print qq{<tr><td><b>$lastname</b>, $firstname</td><td>$dow[$dow] $date };
	print qq{<i>$lex{Period}:</i> $period</td>};

	# Reasons
	print qq{<td><select name="R:$key"><option></option>\n};
	foreach my $reason ( @attend ) {
	    print qq{<option>$reason</option>\n};
	}
	print qq{</select></td>};

	# Late
	print qq{<td><input type="text" size="6" name="L:$key"></td>\n};

=head	
	# Subjects
	print qq{<td><select name="S:$key"><option></option>\n};
	foreach my $subj ( @{ $subjects{$studnum} } ) {
	    print qq{<option>$subj</option>\n};
	}
	print qq{</select></td></tr>\n};
=cut
    print qq{</tr>\n};

    }

    print qq{</table><input type="submit" value="$lex{Save}">\n};
    print qq{</form></body></html>\n};

    exit;

} # end of setReasons();



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

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

    my $homeroom = $arr{homeroom};
    delete $arr{homeroom};

    # Get Userid from homeroom
    my $sth = $dbh->prepare("select userid from staff_multi 
       where field_name = 'homeroom' and field_value = ?");
    $sth->execute( $homeroom );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $userid = $sth->fetchrow;

    #  store the dates for attendance entry for teacher attendance.
    my %tattendance;

    my $first = 1;
    my $grade; # for finding PPD (Attendance Periods per Day)

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

    
    foreach my $key ( keys %arr ) {

	my ( $type,$studnum,$date,$period ) = split( ':',$key);

	if ( $type eq 'PA' ) { # perfect attendance for that day.
	    my $date = $studnum; # studnum is really a date for this hash item.
	    $tattendance{$date} = 1; 
	    next;
	}

	if ( $type eq 'L' or $type eq 'S' or not $period ) { next; } 
	# skip Late, Subject, and additional vars in loop


	# Check for Missing Reason
	if ( not $arr{$key} ) { # missing reason
	    print qq{<div style="color:red;font-weight:bold;">};
	    print qq{$lex{Missing} $lex{Reason} - $lex{Skipping}: $key</div>\n};
	    next;
	}

	# Check for an existing record.
	my $sth = $dbh->prepare("select count(*) from attend 
          where studentid = ? and absdate = ? and period = ?");
	$sth->execute( $studnum, $date, $period );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth->fetchrow;
	if ( $count ) { # we have an existing record

	    # Get Student Name
	    $sth1->execute( $studnum );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname,$firstname ) = $sth1->fetchrow;
	    
	    print qq{<div style="color:red;font-weight:bold;">};
	    print qq{Record exists for $firstname $lastname, $date, Period $period, };
	    print qq{$lex{Skipping}</div>\n};
	    next;
	}

	
	if ( $first ) { # get grade for this student to set PPD.
	    my $sth = $dbh->prepare("select grade from studentall where studnum = ?");
	    $sth->execute( $studnum );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    $grade = $sth->fetchrow;
	}


	$first = 0;
	$tattendance{$date} = 1; # track teacher/admin attendance entry.


	my $late;
	my $lkey = "L:$studnum:$date:$period";
	if ( $arr{$lkey} ) { $late = $arr{$lkey}; }

	my $subject = qq{HR:$homeroom};

	$sth = $dbh->prepare("insert into attend ( studentid, absdate, reason, period, late, subjsec )
         values ( ?, ?, ?, ?, ?, ? )");
	$sth->execute( $studnum, $date, $arr{$key}, $period, $late, $subject );
	
    } # End of Record Entry loop

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

    # Duplicate check.
    my $sth1 = $dbh->prepare("select count(*) from tattend 
      where attdate = ? and subjects = ? and periods = ?");
    
    # Teacher Attendance Records
    if ( not $first ) { 
	my $periods = $g_ppd{$grade};
	my $subject = qq{HR:$homeroom};

	foreach my $date ( keys %tattendance ) {
	    foreach my $period (1..$periods ) {
		# Check for existing...
		$sth1->execute( $date, $subject, $period);
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		my $count = $sth1->fetchrow;
		if ( $count ) { next; }
		
		print qq{Teacher Attendance Entry Added - Date:$date Period:$period<br>\n};
		my $sth = $dbh->prepare("insert into tattend 
                  ( userid, attdate, currdate, subjects, periods )
                  values ( ?,?,now(),?,? )");
		$sth->execute( $userid, $date, $subject, $period);
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    }
	}
    }


    if ( not $DBI::errstr ) {
	print qq{<h3>Attendance Records Stored</h3>\n};

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

    # More Attendance Entry...
    # Start Page Form
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="submit" value="$lex{'Start Page'}"></form>\n\n};

    # Previous Page Form
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    foreach my $key ( sort keys %arr ) {
	if ( $key =~ m/:/ ) { next; } # skip attendance values
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }
    print qq{<input type="submit" value="$lex{Add} $lex{Attendance}"></form>\n};

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

    exit;

} # end of writeRecords();



#-------------
sub setPeriods {
#-------------

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

    my ($homeroom,$userid) = split(':', $arr{homeroom});
    
    my $studtable = 'student';
    if ( $arr{showwithdrawn} ) {
	$studtable = 'studentall';
    }
    delete $arr{showwithdrawn};


    # Set # of weeks to do, 1 or 2
    my $weekcount = $arr{mode};


    # Get Date
    if ( $arr{date} ) { 
	# Generate a list from those dates. Assume year-mon-day
	($year,$month,$day) = split('-',$arr{date});
	$jd = julian_day($year,$month,$day);
	$dow = day_of_week($jd);
	$mondayjd = $jd - ($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 { # get current date
	@tim = localtime(time);
	$year = @tim[5] + 1900;
	$month = @tim[4] + 1;
	$day = @tim[3];
	$jd = julian_day($year,$month,$day);
	$mondayjd = $jd - ($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"; 
	$currdate1 = "@month[$month] $day, $year";
    }

    # Create global @days Array and %datedata Hash to hold Dates and DOW Dates;
    mkDateData($mondayjd,$weekcount);

    # Closed Days and Periods
    my (%dclosed, %pclosed ); # Days Closed, Periods closed;
    # dclosed{date} = 1;  $pclosed{date}{grade/homeroom}{period} = 1;

    # Check for Full Day School Closure
    my $sth = $dbh->prepare("select id, dayfraction from dates where date = ?");
    foreach my $date ( @days ) {
	$sth->execute( $date );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ( $id, $dayfraction ) = $sth->fetchrow;
	if ( $dayfraction > 0.99 ) { 
	    $dclosed{$date} = 1; 
	}
    }

    # Remove closed days from @days.
    my @temp;
    foreach my $date ( @days ) {
	if ( not $dclosed{$date} ) {
	    push @temp, $date;
	} else { # closed
	    print qq{<div>School Closed: $date</div>\n};
	}
    }
    @days = @temp; # replace @days with a, possibly, smaller array of dates.

    
    # Load non-school values (PK,K) for days/part days closed for this date.
    my $sth = $dbh->prepare("select period,homeroom from dates_homeroom where date = ?");
    foreach my $date ( @days ) {

	# Periods Closed from dates_periods table.
	my $ref = parseGradesPeriod( $date, $dbh);
	# $pclosed{date}{grade/homeroom}{period} load from dates_period
	my %temp = %$ref;
	if ( %temp ) {
#	    print "TEMP", %temp, "<br>\n";
	    foreach my $grade ( keys %temp ) {
		foreach my $period ( keys %{ $temp{$grade} } ) {
#		    print "Date:$date Grade:$grade Period:$period<br>\n";
		    $pclosed{$date}{$grade}{$period}  = 1;
		}
	    }
	}
    
	$sth->execute( $date );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my ($period,$homeroom) = $sth->fetchrow ) {
	    $pclosed{$date}{$homeroom}{$period} = 1;
	}
    }

=head
    # TEST %pclosed hash
    print "Pclosed Hash (date/grade/period)<br>";
    foreach my $date ( sort  keys %pclosed ) {
        foreach my $grade ( sort keys %{ $pclosed{$date} } ) {
	    foreach my $period ( sort keys %{ $pclosed{$date}{$grade} } ) {
		print qq{Date:$date Grade:$grade Period:$period<br>\n};
	    }
	}
    }
=cut

    # Set sorting order
    my $sortorder = "lastname, firstname";
    if ( $arr{sortorder} eq $lex{Grade} ) {
	$sortorder = "grade,lastname, firstname";
    }

    # Teacher Name
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth->execute( $userid );
    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n";}
    my ($lastname, $firstname) = $sth->fetchrow;

    
    print qq{<h3>$lex{Homeroom} $homeroom - $firstname $lastname</h3>\n};


    # Remove date from %arr; already in $currdate;
    delete $arr{date}; # loops below

    # Calculate Previous Week Date
    $prevjd = $mondayjd - 7;
    ($prevyear, $prevmonth, $prevday) = inverse_julian_day($prevjd);
    $prevdate = "$prevyear-$prevmonth-$prevday";

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

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="date" value="$prevdate">\n};
    foreach my $key ( keys %arr ) {
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }
    print qq{<input type="submit" value="<= $lex{'Previous Week'}"></form>\n};
    print qq{</td>\n\n};

    # Calculate Next Week Monday Date
    $nextjd = $mondayjd + 7; 
    ($nextyear, $nextmonth, $nextday) = inverse_julian_day($nextjd);
    $nextdate = "$nextyear-$nextmonth-$nextday";

    print qq{<td><form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="date" value="$nextdate">\n};
    foreach my $key ( keys %arr ) {
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }
    print qq{<input type="submit" value="$lex{'Next Week'} =>"></form>\n};
    print qq{</td></tr></table>\n\n};


    # Start Main Entry 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="homeroom" value="$homeroom">\n};

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

    # Loop through table headings.
    print qq{<table cellpadding="4" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Name}</th>\n};
    foreach my $day ( @days ){ print qq{<th>$datedata{$day}</th>}; }
    print qq{</tr>\n};


    # Perfect Attendance Row
    print qq{<tr style="background-color:#DDD;"><td class="bra">$lex{'Perfect Attendance'}</td>\n};
    foreach my $day ( @days ){ 
	print qq{<td class="cn"><input type="checkbox" name="PA:$day" value="1"></td>\n}; 
    }
    print qq{</tr>\n};


    # Find the kids' names and studnum
    my $sth = $dbh->prepare("select lastname, firstname, studnum, grade from $studtable
    where homeroom = ? order by $sortorder");
    $sth->execute( $homeroom );
    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n";}

    my $sth1 = $dbh->prepare("select count(*) from studentwd where studnum = ?");

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

	# Check if withdrawn
	my $wd;
	$sth1->execute($studnum);
	my $count = $sth1->fetchrow;
	if ( $count ) {
	    $wd = qq{<span style="color:red;">$lex{WD}</span>};
	}


	# print Name.
	print qq{<tr><td><b>$wd $lastname</b>, $firstname ($studnum)($grade)</td>\n};

	my $ppdmode;
	my %ampm = (1 => $lex{'AM'}, 2 => $lex{'PM'} );

	my $ppd = $g_ppd{$grade};
	if ( $ppd == 2 ) {
	    $ppdmode = 1;  # am/pm mode
	}

	$first = 0;

	# print the days for this mode:
	foreach my $day ( @days ){
	    print qq{<td>};
	    for my $period ( 1..$ppd ) {
		my $inputval = qq{<input type="checkbox" name="$studnum:$day:$period" value="1">};
		# check for a closed period.
		if ( $grade eq 'K' or grade eq 'PK' ) { # we could have an NSD homeroom closure
		    if ( $pclosed{$day}{$homeroom}{$period} or $pclosed{$day}{$grade}{$period} ) {
			$inputval = qq{ <span title="Closed">C</span>};
		    }
		} else { # other grades.
		    if ( $pclosed{$day}{$grade}{$period} ) {
			$inputval = qq{ <span title="Closed">C</span>};
		    }
		}
		
		if ( $ppdmode ) {
		    print qq{$ampm{$period}$inputval };
		} else {
		    print qq{P$period $inputval };
		}
	    }
	    print qq{</td>\n};
	}
	print qq{</tr>\n};
    }

    if ( $first ) {
	my $cols = $#days + 2;
	print qq{<tr><td colspan="$cols" style="text-align:center;font-size:130%;font-weight:bold;">};
	print qq{$lex{'No Student(s) Found'}</td></tr>\n};
    }

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

    exit;

} # end of setPeriods();



#-------------
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"} = "$dow[$dow], $s_month[$mon] $day";
	    $jd++;
	}
	$jd = $jd + 2; # skip over weekend.
    }
}


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

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

    my %homerooms;

    my $sth1 = $dbh->prepare("select userid from staff_multi 
      where field_name = 'homeroom' and field_value = ?");
    my $sth2 = $dbh->prepare("select lastname, firstname from staff where userid = ?");

    while ( my ($hr, $grade) = $sth->fetchrow ) {
	# Get Teacher userid;
	$sth1->execute($hr);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	my $userid = $sth1->fetchrow;

	if ( $g_AttendanceEntryMethod{$grade} eq 'subject' ) { next; }
	# We only do homeroom attendance, so far.
	
	$homerooms{$hr} = $userid;
    }

    if ( not %homerooms ) {
	print qq{</h3>No Homeroom Attendance Entry</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

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

    # Start Date
    print qq{<tr><td class="bra">$lex{'Start Date'}</td>\n};
    print qq{<td><input type="text" name="date" id="date" size="12" value="$currdate">\n};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};

    # Homeroom
    print qq{<tr><td class="bra">$lex{Select} $lex{Homeroom}</td>};
    print qq{<td><select name="homeroom"><option></option>\n};

    foreach my $hr ( sort keys %homerooms ) {

	my $userid = $homerooms{$hr};

	$sth2->execute( $userid );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	my ($lastname, $firstname) = $sth2->fetchrow;

	print qq{<option value="$hr:$userid">$hr ($firstname $lastname)</option>\n};
    }
    print qq{</select></td></tr>\n};
    

    # Mode: Weekly, Biweekly
    print qq{<tr><td class="bra">$lex{Mode}\n};
    print qq{</td><td><select name="mode"><option value="1">$lex{Weekly}</option>\n};
    print qq{<option value="2">$lex{Biweekly}</option></select></td></tr>\n};

    # Show Withdrawn
    print qq{<tr><td class="bra">$lex{Show} $lex{Withdrawn} $lex{Students}\n};
    print qq{</td><td><input type="checkbox" name="showwithdrawn" value="1">\n};
    print qq{</td></tr>\n};

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

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

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

    exit;

}
