#!/usr/bin/perl
#  Copyright 2001-2020 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 $self = 'tattCrsEdit.pl'; # Edit attendance by subject records.

my %lex = ('Attendance Records' => 'Attendance Records',
	   'Main' => 'Main',
	   'Homeroom' => 'Homeroom',
	   'Please Log In' => 'Please Log In',
	   'Student' => 'Student',
	   'Date' => 'Date',
	   'Period' => 'Period',
	   'Reason' => 'Reason',
	   'Edit' => 'Edit',
	   'Delete' => 'Delete',
	   'Duration' => 'Duration',
	   'Error' => 'Error',
	   'Not Found' => 'Not Found',
	   'Subjects' => 'Subjects',
	   'Course' => 'Course',
	   'Select' => 'Select',
	   'Months' => 'Months',
	   'Continue' => 'Continue',

	   );


use DBI;
use CGI;


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


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

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


my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";


my $userid;  # no need for session, just get userid.
if ( not defined $arr{userid} ) {
    $userid = $ENV{'REMOTE_USER'};
} else {
    $userid = $arr{userid};
}

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


# Print top of page
my $title = qq{$lex{Edit}/$lex{Delete} $lex{'Attendance Records'}};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" 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{$chartype\n</head><body>\n};

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

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


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

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

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    delEditStudents(); # delete immediately, then show Edit forms.

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    updateRecords(); # update any record edits.

} elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    selectStudentRecords(); # called by attEntry.pl to edit single student/course.
}





#----------------
sub showStartPage { # Select Month or Student.
#----------------

    print qq{<h3>$currdate</h3>\n};

    
    # needed to load $additionalcomments subject description (in order to skip).
    my $sth = $dbh->prepare("select id, datavalue from conf_system where dataname = ?");
    foreach my $field (r_AdditionalComments ) {
	$sth->execute( $field );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while (	my ($id, $datavalue) = $sth->fetchrow ) {
	    eval $datavalue;
	    if ( $@ ) {
		print qq{$lex{Error}: $@<br>\n};
		die "$lex{Error}: $@\n";
	    }
	}
    }

    
    # Get the user's courses (all).
    my @courses;
    $sth = $dbh->prepare("select subjsec from subject where teacher = ?
      order by description");
    $sth->execute( $userid );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $subjsec = $sth->fetchrow) {
	if ( $r_AdditionalComments{$subjsec} ) { next;  }  # skip any global, additional comments)
	push @courses, $subjsec;
    }


    if ( not @courses ) {
	print qq{<h3>No Courses Found</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

	
    # get distinct year-month values from attend table.
    my $sth = $dbh->prepare("select distinct year(absdate), month(absdate) from attend 
      where subjsec = ?");
    my %yrmo;
    foreach my $subjsec ( @courses ) {
	$sth->execute($subjsec);
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my ($year, $month) = $sth->fetchrow ) {
	    if ( length $month == 1 ) { $month = '0'. $month; }
	    $val = qq{$year-$month};
	    $yrmo{$val} = 1;
	    # print qq{<div>Subjsec:$subjsec Year:$year MO:$month</div>\n};
	}
    }

    # Pass this to next script to save this calc again.
    my $fullyrmo = join(',', sort keys %yrmo );

    my $sth1 = $dbh->prepare("select description, startrptperiod, endrptperiod from subject where subjsec = ?");
    
    my $courses = join(',',@courses ); # for passing to next script.

    
    # get sorted courses and descriptions.
    my (%sort, %desc, %terms);
    foreach my $subjsec ( @courses ) {
	# Get Description
	$sth1->execute($subjsec);
	my ($desc, $start,$end) = $sth1->fetchrow;
	$sort{"$desc$subjsec"} = $subjsec;
	$desc{$subjsec} = qq{$desc};
	$terms{$subjsec} = qq{$start - $end};
    }
    

    # Notes
    print qq{<div>If you select:<ul style="margin:0.4em;">\n};
    print qq{<li><b>Courses Only</b>, you will see all records for that course.</li>\n};
    print qq{<li><b>Months Only</b>, you will see all of your courses records for those months.</li>\n};
    print qq{<li><b>Both Courses and Months</b>, you will see the students records for };
    print qq{those months, split by course.</li>\n};
    print qq{</ul></div>\n};
   
 
    # Start the form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="fullyrmo" value="$fullyrmo">\n};
        
    
    print qq{<div style="text-align:left"><input type="submit" value="$lex{Continue}"></div>\n};

        
    # Display Courses
    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:0.6em;">\n};
    print qq{<tr><th>$lex{Select} Courses</th><th>Terms</th></tr>\n};
    foreach my $key ( sort keys %sort ) {
	my $subjsec = $sort{$key};
	print qq{<tr><td><input type="checkbox" name="c:$subjsec" value="1">};
	print qq{$desc{$subjsec} ($subjsec)</td><td class="cn">$terms{$subjsec}</td></tr>\n};
    }
    print qq{</table>\n};


    
    # Display Year-Months.
    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:0.6em;">\n};
    print qq{<tr><th>$lex{Select} $lex{Months}</th></tr>};
    foreach my $yrmo ( sort keys %yrmo ) {
	my ($yr,$mo) = split '-', $yrmo;
	print qq{<tr><td><input type="checkbox" name="yrmo:$yrmo" value="1">};
	print qq{$month[$mo] $yr</td></tr>\n};
    }
    print qq{</table>\n};
    
    #  Sort
    print qq{<br clear="left"><div style="width:20ch;border:1px solid gray;padding:0.6em;margin:0.6em;">};
    print qq{Sort by <select name="sort">\n};
    print qq{<option value="course">Course</option><option value="date">Date</option></select></div>\n};
    
   
    # Continue
    # print qq{<br clear="left">\n};
    print qq{<div style="margin:0.6em;"><input type="submit" value="$lex{Continue}"></div>\n};
    print qq{</form></body></html>\n};

    exit;

} # end of showStartPage



#----------------
sub selectRecords {
#----------------

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

    my $sort = $arr{sort}; # by Course or by Date. (both lowercase)
    delete $arr{sort};

    my $fullyrmo = $arr{fullyrmo};
    delete $arr{fullyrmo};
    
    
    # If only months, display courses by date. If courses, then only show limited courses.

    # values passed:yrmo type is year-month, c is course subjsec. (ie. 8400-1 )

    my (@yrmo, @courses, %sort, %studname, %coursename, %rec );

    # For alternating background on changing dates;
    my $color1 = '#FFF';
    my $color2 = '#DDD';
    my $bgcolor;


    foreach my $key ( keys %arr ) {
	my ($type, $val) = split(':', $key);
	if ( $type eq 'c' ) { push @courses, $val; }
	if ( $type eq 'yrmo' ) { push @yrmo, $val; }
    }

    
    if ( not @courses and not @yrmo ) {
	print qq{<h3>No Selection</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Get all courses names. If selected ones, they must be sorted too.
    
    if (not @courses )  { # no courses selected; we'll need all courses for search by month
	my $sth = $dbh->prepare("select subjsec, description from subject 
           where teacher = ? order by description");
	$sth->execute($userid);
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my ($subjsec, $desc) = $sth->fetchrow ) {
	    push @courses, $subjsec;
	    $coursename{$subjsec} = $desc;
	}
	
    } else { # we have courses, get the names, and sort.
	my (%tempsort, @tempcourse); # hold course info
	my $sth = $dbh->prepare("select description from subject where subjsec = ?");
	foreach my $crs ( @courses ) {
	    $sth->execute($crs);
	    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $desc = $sth->fetchrow;
	    $coursename{$crs} = $desc;
	    $tempsort{"$desc$crs"} = $crs;
	}
	foreach my $key ( sort keys %tempsort ) {
	    my $crs = $tempsort{$key};
	    push @tempcourse, $crs;
	}
	@courses = @tempcourse;
    }

# TEST    
#    print "<b>Courses</b><br>";
#    foreach my $crs ( @courses ) {
#	print "$coursename{$crs} - $crs<br>\n";
#    }

    # At this point we have @courses (sorted), and have %coursenames set also.

    if ( not @yrmo ) { 
	# then we have all months, so populate @yrmo with all values, just
	# like we did with the courses. This makes it easy to output results.

	@yrmo = split(',', $fullyrmo);  # already sorted.
    }
    

# TEST    
#    print qq{<div><b>Year Month</b></div>\n};
#    foreach my $yrmo ( @yrmo ) {
#	print qq{$yrmo<br>\n};
#    }
    
    
    # Get all attendance records; all courses, all dates;
    my %rec; # rec{subjsec}{yrmo}{id} = ref to record.
    my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    
    my $sth = $dbh->prepare("select * from attend where subjsec = ? and 
      year(absdate) = ? and month(absdate) = ?");

    foreach my $subjsec ( @courses ) {
	foreach my $yrmo ( @yrmo ) {
	    my ($yr,$mo) = split('-',$yrmo);
	    $sth->execute($subjsec, $yr,$mo);
	    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $ref = $sth->fetchrow_hashref ) {
		my %r = %$ref;
		if ( $sort eq 'course' ) {
		    $rec{$subjsec}{$yrmo}{ $r{attid} } = $ref;  # only partially containerized. Rest below
		} else { # sort by date...
		    # $rec{$yrmo}{$subjsec}{ $r{attid} } = $ref;  # only partially containerized. Rest below
		    $rec{$yrmo}{ $r{attid} } = $ref;  # only partially containerized. Rest below
		}
		    
		# Check student name
		if ( not $studname{ $r{studentid} } ) { # get name and add to hash if not present
		    $sth1->execute( $r{studentid} );
		    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		    my ($lname,$fname) = $sth1->fetchrow;
		    $studname{ $r{studentid} } = qq{$lname, $fname};
		}

	    } # end of this record
	} # end of year-month
    } # end of each course

# TEST
=head
    foreach my $subjsec ( sort keys %rec ) {
	foreach my $yrmo ( sort keys %{ $rec{$subjsec} } ) {
	    foreach my $id ( sort {$a <=> $b} keys %{ $rec{$subjsec}{$yrmo} } ) {
		print "CRS:$subjsec YRMO:$yrmo ID:$id<br>\n";
	    }
	}
    }
=cut


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

    print qq{<h3>There is NO CONFIRMATION on DELETE. Record is Immediately Removed.</h3>\n};
    
    print qq{<div><input type="submit" value="Continue"></div>\n};
     
    # Loop over all courses
    if ( $sort eq 'course' ) {
	foreach my $subjsec ( @courses ) {
	    foreach my $yrmo ( sort keys %{ $rec{$subjsec} } ) {
		
		my ($yr, $mo) = split('-', $yrmo);
		
		# Get Records for Edit/Delete
		my $first = 1;
		my $count = 1;
		
		# Get all students, dates in this block.(subjsec/year-month);
		my %datestud; # dates / student / recid
		foreach my $id ( keys %{ $rec{$subjsec}{$yrmo} } ) {
		    my %r = %{ $rec{$subjsec}{$yrmo}{$id} };
#		    print qq{Date:$r{absdate} - $studname{ $r{studentid} }<br>\n};
		    my $studkey = qq{$studname{ $r{studentid} }-$r{studentid}};
		    $datestud{ $r{absdate} }{ $studkey }{ $r{period} } = $id;
		}

# Test
=head		foreach my $date ( sort keys %datestud ) {
		    foreach my $studkey ( sort keys %{ $datestud{$date} } ) {
			foreach my $period ( sort keys %{ $datestud{$date}{$studkey} } ) {
			    print "Date:$date Key:$studkey Period:$period<br>\n";
			}
		    }
		}
=cut		
		$bgcolor = $color2;
		
		foreach my $date ( sort keys %datestud ) {

		    # Toggle color
		    if ( $bgcolor eq $color1 ) { $bgcolor = $color2; } else { $bgcolor = $color1; }
		    
		    foreach my $studkey ( sort keys %{ $datestud{$date} } ) {
			foreach my $period ( sort keys %{ $datestud{$date}{$studkey} } ) {
#			    print "Date:$date Key:$studkey Period:$period<br>\n";
			    my $id = $datestud{$date}{$studkey}{$period};
			    my %r = %{ $rec{$subjsec}{$yrmo}{$id} };

		
			    if ( $first ) { # start table layout.
#				print qq{<div><input type="submit" value="Continue"></div>\n};
				print qq{<table cellpadding="3" border="1" cellspacing="0" style="float:left;">\n};
				print qq{<caption style="font-weight:bold;font-size:120%;">};
				print qq{$coursename{$subjsec} ($subjsec) - $month[$mo] $yr</caption>\n};
				print qq{<tr><th>$lex{Student}</th><th>Edit</th><th>Delete</th>};
				print qq{<th>Date/Period</th><th>Reason</th></tr>\n};
				$first = 0;
			    }

			    print qq{<tr style="background-color:$bgcolor;">};
			    print qq{<td>$count. $studname{$r{studentid}} ($r{studentid})</td>};
			    print qq{<td class="cn"><input type="radio" name="$id" value="E"></td>\n};
			    print qq{<td class="cn"><input type="radio" name="$id" value="D"></td>\n};
			    print qq{<td>$r{absdate} / $r{period}</td><td>$r{reason}</td></tr>\n};

			    $count++;
			    if ( $count % 25 == 0 ) { # put in title line
				print qq{<tr><th>$lex{Student}</th><th>Edit</th><th>Delete</th>};
				print qq{<th>Date/Period</th><th>Reason</th></tr>\n};
			    }
		
			} # end of period loop
		    } # end of student loop
		} # end of date loop

		if ( not $first ) {
		    print qq{</table>\n};
		}		    
		
	    } # yrmo loop
	} # end of course loop

    } else { # DATE loop in month blocks.

	# %rec structure is date / course / student format.
	# We will only have date blocks for each month, and only selected courses.
	# Selected courses will have a %coursename entry.
	foreach my $yrmo ( sort keys %rec ) {
	    # We now have to sort records by date, and period to put into correct reporting order.

	    my ($yr, $mo) = split('-', $yrmo);

	    
	    # Get Records for Edit/Delete
	    my $first = 1;
	    my $count = 1;
		
	    # Get all students, dates in this block.(year-month);
	    my %datestud; # dates / student / recid
	    foreach my $id ( keys %{ $rec{$yrmo} } ) {
		    my %r = %{ $rec{$yrmo}{$id} };
#		    print qq{Date:$r{absdate} - $studname{ $r{studentid} }<br>\n};
		    my $studkey = qq{$studname{ $r{studentid} }-$r{studentid}};
		    $datestud{ $r{absdate} }{ $r{period} }{ $studkey } = $id;
		}

# Test
=head	    foreach my $date ( sort keys %datestud ) {
		foreach my $period ( sort keys %{ $datestud{$date} } ) {
		    foreach my $studkey ( sort keys %{ $datestud{$date}{$period} } ) {
			print "Date:$date Key:$studkey Period:$period<br>\n";
		    }
		}
	    }
=cut


	    $bgcolor = $color2;
	    
	    foreach my $date ( sort keys %datestud ) {

		# Toggle color
		if ( $bgcolor eq $color1 ) { $bgcolor = $color2; } else { $bgcolor = $color1; }
		
		foreach my $period ( sort keys %{ $datestud{$date} } ) {
		    foreach my $studkey ( sort keys %{ $datestud{$date}{$period} } ) {

			#   print "Date:$date Key:$studkey Period:$period<br>\n";
			my $id = $datestud{$date}{$period}{$studkey};
			my %r = %{ $rec{$yrmo}{$id} };

		
			if ( $first ) { # start table layout.
			    print qq{<table cellpadding="3" border="1" cellspacing="0" style="float:left;">\n};
			    print qq{<caption style="font-weight:bold;font-size:120%;">};
			    print qq{ $month[$mo], $yr</caption>\n};
			    print qq{<tr><th>$lex{Student}</th><th>Edit</th><th>Delete</th>};
			    print qq{<th>Date/Period</th><th>Reason</th><th>Course</th></tr>\n};
			    $first = 0;
			}

			print qq{<tr style="background-color:$bgcolor;">};			
			print qq{<td>$count. $studname{$r{studentid}} ($r{studentid})</td>};
			print qq{<td class="cn"><input type="radio" name="$id" value="E"></td>\n};
			print qq{<td class="cn"><input type="radio" name="$id" value="D"></td>\n};
			print qq{<td>$r{absdate} / $r{period}</td><td>$r{reason}</td>\n};
			print qq{<td>$coursename{$r{subjsec}}</td></tr>\n};

			$count++;
			if ( $count % 25 == 0 ) { # put in title line
			    print qq{<tr><th>$lex{Student}</th><th>Edit</th><th>Delete</th>};
			    print qq{<th>Date/Period</th><th>Reason</th><th>Course</th></tr>\n};
			}
		
		    } # end of student loop
		} # end of period loop
	    } # end of date loop

	    if ( not $first ) {
		print qq{</table>\n};
	    }		    
		
	} # yrmo loop

    } # end of date format loop
    
    print qq{<br clear="left"><div><input type="submit" value="Continue"></div>\n};
    print qq{</form>\n};
    print qq{</body></html>\n};


} # end of selectStudents / months



#------------------
sub delEditStudents {
#------------------

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

    # setup selects
    my $sth = $dbh->prepare("select * from attend where attid = ?");
    my $sth1 = $dbh->prepare("delete from attend where attid = ?");
    my $sth2 = $dbh->prepare("select lastname, firstname, grade from studentall where studnum = ?");

    print qq{<h2>Delete Attendance Records</h2>\n};
    my $first = 1;
    foreach my $id ( keys %arr ) {
	if ( $arr{$id} eq 'D' ) { # delete
	    
	    # get record
	    $sth->execute($id);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth->fetchrow_hashref;
	    my %r = %$ref;

	    # get name, grade (not needed yet)
	    $sth2->execute( $r{studentid} );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname,$firstname, $grade) = $sth2->fetchrow;

	    # delete record from attend table.
	    
	    $sth1->execute($id);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    print qq{<div><b>Deleted $firstname $lastname</b> on $r{absdate}, period $r{period} };
	    print qq{for $r{reason}</div>\n};

	    # delete from %arr hash
	    delete $arr{$id};
	    
	}
    }
    if ( $first ) { print qq{<h3>No Attendance Deletion</h3>\n}; }
    
    
    # now do the edits.

    print qq{\n\n<h2>Edit Attendance Records</h2>\n};
    my $first = 1;
    my %absdate; # $absdate{$id} = $absdate
    
    foreach my $id ( keys %arr ) {
	if ( $arr{$id} eq 'E' ) { # edit, likely redundant since deletes are done.
    
	    # get record
	    $sth->execute($id);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth->fetchrow_hashref;
	    my %r = %$ref;
	    $absdate{$id} = $r{absdate}; # used below for calendar

	    # get name, grade
	    $sth2->execute( $r{studentid} );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname,$firstname, $grade) = $sth2->fetchrow; # grade used below

	    if ( $first ) { # start the form
		print qq{<form action="$self" method="post">\n};
		print qq{<input type="hidden" name="page" value="3">\n};
		$first = 0;
	    }

	    print qq{<table cellpadding="3" border="1" cellspacing="0" style="margin:0.5em;">\n};

	    print qq{<tr><td class="bra">Name</td>};
	    print qq{<td><b>$lastname</b>, $firstname ($r{studentid})</td></tr>\n};
	    
	    print qq{<tr><td class="bra">Date</td>\n};
	    print qq{<td><input type="text" style="width:12ch;" name="$id:absdate" id="$id:absdate"};
	    print qq{ value="$r{absdate}"> };
	    print qq{<button type="reset" id="$id:date_trigger">...</button>\n};

	    
	    print qq{</td></tr>\n};

	    print qq{<tr><td class="bra">Reason</td>\n};
	    print qq{<td><select name="$id:reason"><option>$r{reason}</option>\n};
	    foreach my $rsn ( @attend ) { # @attend is global array from configuration
		if ( $rsn eq $r{reason} ) { next; }
		print qq{<option>$rsn</option>\n};
	    }
	    print qq{</select></td></tr>\n};

	    my $ppd = $g_ppd{$grade}; # attendance periods from grade of student; g_ppd is from conf
	    print qq{<tr><td class="bra">Period</td>\n};
	    print qq{<td><select name="$id:period"><option>$r{period}</option>\n};
	    foreach my $per ( 1..$ppd ) { # $g_ppd hash is global from configuration system
		if ( $per == $r{period} ) { next; }
		print qq{<option>$per</option>\n};
	    }
	    print qq{</select></td></tr>\n};

	    print qq{<tr><td class="bra">Minutes Late</td>\n};
	    print qq{<td><input type="text" style="width:4ch;" name="$id:late" };
	    print qq{value="$r{late}"></td></tr>\n};
	    
	    print qq{</table>\n\n};

	} # end of if an edit
    } # end of edit loop

    if ( not $first ) { # we had some edits.
	print qq{<input type="submit" value="Update Records">\n};
	print qq{</form>\n};

    } else {
	print qq{<h3>No Attendance Edits</h3>\n};
    }

    # now calendar javascript
    foreach my $id ( keys %arr ) {
	if ( $arr{$id} eq 'E' ) { # edit, likely redundant since deletes are done.

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



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

    exit;

}


#----------------
sub updateRecords {
#----------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    my %studname;
    
    my $sth1 = $dbh->prepare("select * from attend where attid = ?");
    my $sth2 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    
    
    foreach my $key ( sort keys %arr ) {

	my ( $id, $field ) = split(':', $key);

	# Get the record
	$sth1->execute( $id );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth1->fetchrow_hashref;
	my %r = %$ref;

	# Get Name
	my $studnum = $r{studentid};
	$sth2->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lname, $fname) = $sth2->fetchrow;
	
	
	# load this record and get student name
	my $sth = $dbh->prepare("update attend set $field = ? where attid = ?");
	$sth->execute( $arr{$key}, $id );
	

	# Update Record
	my $sth = $dbh->prepare("update attend set $field = ? where attid = ?");
	$sth->execute( $arr{$key}, $id );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	print qq{<div><b>$lname</b>, $fname - $field - $arr{$key} Updated</div>\n};

    }

    print qq{<h1>$lex{Records} $lex{Updated}</h1>\n};

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

    exit;

}


#-----------------------
sub selectStudentRecords {
#-----------------------

    # a link passed from the tattentry.pl script to edit all
    # attendance records for a single student in a course. Find all
    # his/her attendance records for this course and allow for
    # edit/delete.

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

    # just to keep it simple
    my $subjsec = $arr{subjsec};
    my $studnum = $arr{studnum}; 


    # For alternating background on changing dates;
    my $color1 = '#FFF';
    my $color2 = '#DDD';
    my $bgcolor;

    # Get courses name.
    my $sth = $dbh->prepare("select description from subject where subjsec = ?");
    $sth->execute($subjsec);
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $desc = $sth->fetchrow;

    # Get student name
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    $sth->execute($studnum);
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname) = $sth->fetchrow;


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

    print qq{<h3>There is NO CONFIRMATION on DELETE. Record is Immediately Removed.</h3>\n};
    
    print qq{<div><input type="submit" value="Continue"></div>\n};

    
    # Get all attendance records for this student in this course.
    my $sth = $dbh->prepare("select * from attend where subjsec = ? and studentid = ?");
    $sth->execute($subjsec, $studnum);
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    my $first = 1;
    my $count = 1;

    $bgcolor = $color1;
    
    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref;

#	if ( $bgcolor eq $color1 ) { $bgcolor = $color2; } else { $bgcolor = $color1; }     
	
	if ( $first ) { # start table layout.
	    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};
	    print qq{<caption style="font-weight:bold;font-size:120%;">};
	    print qq{$desc ($subjsec)</caption>\n};
	    print qq{<tr><th>$lex{Student}</th><th>Edit</th><th>Delete</th>};
	    print qq{<th>Date/Period</th><th>Reason</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr style="background-color:$bgcolor;">};
	print qq{<td>$count. <b>$lastname</b>, $firstname ($r{studentid})</td>};
	print qq{<td class="cn"><input type="radio" name="$r{attid}" value="E"></td>\n};
	print qq{<td class="cn"><input type="radio" name="$r{attid}" value="D"></td>\n};
	print qq{<td>$r{absdate} / $r{period}</td><td>$r{reason}</td></tr>\n};

	$count++;
	if ( $count % 25 == 0 ) { # put in title line
	    print qq{<tr><th>$lex{Student}</th><th>Edit</th><th>Delete</th>};
	    print qq{<th>Date/Period</th><th>Reason</th></tr>\n};
	}
		
    } # end of record loop

    if (not $first) {
	print qq{</table>\n};
    }
    
    print qq{<p><input type="submit" value="Continue"></p>\n};
    print qq{</form>\n};

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


} # end of selectStudents / months

