#!/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',
	    'Error' => 'Error',
	    'Weekly' => 'Weekly',
	    'Grade' => 'Grade',
	    'Homeroom' => 'Homeroom',
	    'Biweekly' => 'Biweekly',
	    'Continue' => 'Continue',
	    'Mode' => 'Mode',
	    'No Student(s) Found' => 'No Student(s) Found',
	    'Start Date' => 'Start Date',
	    'Period' => 'Period',
	    'Late' => 'Late',
	    'Contact' => 'Contact',
	    'Reason' => 'Reason',
	    'Skipping' => 'Skipping',
	    'Save' => 'Save',
	    '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',

	    'Record' => 'Record',
	    'Exists' => 'Exists',
	    'Saved' => 'Saved',
	    'Student' => 'Student',
	    'More' => 'More',
	    'No Absences Found' => 'No Absences Found',
	    'Select' => 'Select',
	    
	    
	    );

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);



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

    my $homeroom = $arr{homeroom};
    delete $arr{homeroom};
    
    # 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="$homeroom">\n};

    print qq{<div style="margin:1em;"><input type="submit" value="$lex{Save}"></div>\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;

    my @perfect; # perfect attendance keys
    my $first = 1;
    foreach my $key ( sort keys %arr ) {

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

	if ( $studnum eq 'PA' ) {
	    push @perfect, $key;
	    next;
	}

	# print qq{SN:$studnum DT:$date PER:$period<br>\n};
	if ( not $period ) {
	    next; 
	} 

	if ( $first ) { # start the table
	    # 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};
	    $first = 0;
	}


	
	my $jd = julian_day( split('-', $date));
	my $dow = day_of_week( $jd ); #  0-6

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

	print qq{<tr><td><b>$lastname</b>, $firstname</td><td>$dowstd[$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};

	print qq{</tr>\n};

    }

    print qq{</table>\n};

    # Now any perfect attendance values.
    foreach my $key ( @perfect ) {
	my ($dud,$date,$period) = split(':', $key);
	print qq{<div><b>Perfect Attendance</b> Date $date / Period $period };
	print qq{<input type="hidden" name="$key" value="1"></div>\n};
    }

    print qq{<div style="margin:1em;"><input type="submit" value="$lex{Save}"></div>\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};
    my $subjsec = qq{HR:$homeroom}; # subjsec field in the attend table.

    # 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;
#    print "Userid:$userid Subjsec:$subjsec Homeroom:$homeroom<br>\n";
    
    my @fields = qw(studentid absdate reason period subjsec late );
    
    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 ( $type, $studnum,$date,$period ) = split(':',$key);
	if ( $type eq 'PA' or $type eq 'L' ) { next; }; # PA done below, Late key created.

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

	my $late;
	my $lateKey = qq{L:$studnum:$date:$period};
	if ( $arr{$lateKey} ) { # we have minutes set
	    $late = $arr{$lateKey};
	} else {
	    undef $late; # will be NULL when stored.
	}
	
	$first = 0;
	my @values;
	my @fieldnames = @fields;
	my @qst = qw(? ? ? ? ? ?); # 6 fields (includes late)

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

	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.
    foreach my $key ( keys %arr ) {
	if ( not $arr{$key} ) { next; } # skip no values
	
	# my ( $type,$studnum,$subjsec,$date,$period ) = split(':',$key);
	my @data = split(':', $key );

	if ( $data[0] eq 'L' ) { next; } # skip any lates
	
	if ( $data[0] eq 'PA' ) { #PA:date:period
	    $date = $data[1];
	    $period = $data[2];
	} else { # a normal student record. R:studnum:date:period
	    $date = $data[2];
	    $period = $data[3];
	}

	# Check if already done.
	# Userid and subjsec (ie. HR:$homeroom) defined at top of function.
	$sth1->execute( $userid, $date, $subjsec, $period );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $tacount = $sth1->fetchrow;
	if ( $tacount ) { # already present in tattend (teachers attendance table)
	    print qq{<div>Teacher Attendance Record exists. Skipping \n};
	    print qq{User:$userid / $date / $subjsec / Period $period</div>\n};
	    next;
	} # otherwise continue and add a record.
	
	# Add  tattend entry
	$sth->execute( $userid, $date, $subjsec, $period );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	print qq{<div><b>Added Teacher Entry</b>\n};
	print qq{User:$userid / $subjsec /$date / Period $period</div>\n};
	    
    } # end of %arr loop adding teacher attendance
    

    # Add more Attendance Records
    print qq{<div style="font-weight:bold;margin:1em;border:1px solid gray;width:40ch;padding:0.6em;">};
    print qq{$lex{Add} $lex{More} Weekly Homeroom $lex{Attendance}\n};
    
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="submit" value="$lex{Add} $lex{Attendance}"></form></div>\n};

    print qq{<p>[ <a href="$homepage">$lex{Main}</a> ]</p>\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, %onlineday ); # Days Closed, Periods closed, Online Learning
    # dclosed{date} = 1;  $pclosed{date}{grade/homeroom}{period} = 1;

    # Check for Full Day School Closure
    my $sth = $dbh->prepare("select id, dayfraction, type from dates where date = ?");
    foreach my $date ( @days ) {
	$sth->execute( $date );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ( $id, $dayfraction, $type ) = $sth->fetchrow;
	if ( $dayfraction > 0.99 ) { 
	    $dclosed{$date} = 1; 
	}
	if ( $type eq 'onlinelearning' ) {  # used below to modify periods close (%pclosed)
	    $onlineday{$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 homeroom values (various homerooms) for days/part days
    # closed for this date, unless onlinelearning is set.
    
    my $sth = $dbh->prepare("select period, homeroom, closuretype from dates_homeroom where date = ?");
    foreach my $date ( @days ) {

	# Grades closed
	if ( not $online{$date} ) { # not online learning type in dates table
	    # Periods Closed from dates_periods table.
	    my $ref = parseGradesPeriod( $date, $dbh);
	    # $pclosed{date}{grade/homeroom}{period} load from dates_period
	    my %temp = %$ref;
	    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;
		}
	    }
	}

	# Homerooms closed
	$sth->execute( $date );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my ($period,$homeroom,$closuretype) = $sth->fetchrow ) {
	    if ( $closuretype ne 'onlinelearning' ) {
		$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};

    # Get Homeroom grade for PPD calc
    my $maxppd; # always use biggest attendance periods per day.
    my $sth = $dbh->prepare("select distinct grade from student where homeroom = ?");
    $sth->execute( $homeroom );
    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n";}
    while ( my $grade = $sth->fetchrow ) {
	my $tempppd = $g_ppd{$grade};
	if ($tempppd > $maxppd ) { $maxppd = $tempppd; }
    }

    my %ampm = (1 => $lex{'AM'}, 2 => $lex{'PM'} );
    my $ppdmode;
    if ( $maxppd == 2 ) {
	$ppdmode = 1;  # am/pm mode
    }
    
    # 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">\n};
	for my $period ( 1..$maxppd ) {
	    my $inputval = qq{<input type="checkbox" name="PA:$day:$period" value="1">};
	    # check for a closed period.
	    if ( $pclosed{$day}{$homeroom}{$period} or $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};


    # Find the students' 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 = ?");

    # check for an existing entry
    my $sth2 = $dbh->prepare("select count(*) from attend 
			     where studentid = ? and absdate = ? and period = ?");


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


	$first = 0;

	# print the days for this mode:
	foreach my $day ( @days ){
	    print qq{<td class="cn">};
	    for my $period ( 1..$maxppd ) {

		# Check if already done
		$sth2->execute($studnum, $day, $period);  # day is really a date
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}		
		my $attcount = $sth2->fetchrow;
		if ( $attcount ) {
		    print qq{Done };
		    next;
		}
		
		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 {
#----------------

    my (%homerooms, %teachernames);

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

    my $sth2 = $dbh->prepare("select field_value from staff_multi 
      where field_name = 'grade' and userid = ?");

    
    my $sth = $dbh->prepare("select userid, field_value from staff_multi 
      where field_name = 'homeroom' order by field_value");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
    
TCH:  while ( my ($userid, $hr) = $sth->fetchrow ) {
	
	# Get Teacher Name
	$sth1->execute($userid);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	my ($lastname, $firstname) = $sth1->fetchrow;
	$teachernames{$userid} = qq{$lastname, $firstname};
	
	# Check for their grade, and if subject attendance entry only.
	$sth2->execute($userid);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	
	while ( my $grade = $sth1->fetchrow ) {
	    if ( $g_AttendanceEntryMethod{$grade} eq 'subject' ) {
		next TCH;
	    }
	    # 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};
	print qq{<option value="$hr:$userid">$hr - $teachernames{$userid}</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;

}
