#!/usr/bin/perl
#  Copyright 2001-2023 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 = ('Main' => 'Main',
	   'Student' => 'Student',
	   'Student(s)' => 'Student(s)',
	   'Edit' => 'Edit',
	   'Add' => 'Add',
	   'Delete' => 'Delete',
	   'Category' => 'Category',
	   'New' => 'New',
	   'Description' => 'Description',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'Contact Log' => 'Contact Log',
	   'Error' => 'Error',
	   'or' => 'or',
	   'Please Log In' => 'Please Log In',
	   'Save' => 'Save',
	   'Date' => 'Date',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'Student Group' => 'Student Group',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Or' => 'Or',
	   'Last,First/Last/Initials/Studnum' => 'Last,First/Last/Initials/Studnum',
	   'Next Page' => 'Next Page',
	   'Check' => 'Check',
	   'Continue' => 'Continue',
	   'Select' => 'Select',
	   'Mode' => 'Mode',
	   'Not Found' => 'Not Found',
	   'New' => 'New',
	   'No Record(s) Found' => 'No Record(s) Found',
	   'More' => 'More',
	   'Record(s)' => 'Record(s)',
	   'Deleted' => 'Deleted',

	   );

my $self = 'ctEdit.pl';

use DBI;
use CGI;

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

my $q = new CGI;
my %arr = $q->Vars;
print $q->header;

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


# Get Current 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 $userid = $ENV{'REMOTE_USER'};

# Get User 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 ( $lastname, $firstname ) = $sth->fetchrow;


# Print Page Header
my $title = qq{$lex{Add}/$lex{Edit} $lex{'Contact Log'}};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};

if ( $arr{page} == 3 ) {
    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{<div>[ <a href="$tchpage">$lex{Main}</a> ] $firstname $lastname</div>\n};
print qq{<h3>$title</h3>\n};

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


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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    if ( $arr{student} ) {
	searchStudent( $arr{student} );
    } else {
	searchGroup( $arr{group}, $arr{groupid} );
    }

} elsif ( $arr{page} == 2 ) { # add,edit,delete operation on students selected
    delete $arr{page};
    modeOperate(); 

} elsif ( $arr{page} == 3 ) { # edit records
    delete $arr{page};
    editRecords();

} elsif ( $arr{page} == 4 ) { # update the database.
    delete $arr{page};
    writeRecords();
}


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

    print qq{<h1>$lex{Select} $lex{'Student(s)'}</h1>\n};

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

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

    print qq{<tr><td class="bra">$lex{'Student Group'}</td>\n<td>};
    print qq{<select name="group"><option value="grade">$lex{Grade}</option>\n};
    print qq{<option value="homeroom">$lex{Homeroom}</option></select>\n };
    print qq{<input type="text" name="groupid" size="6">};

    print qq{<tr><td class="ra">$lex{Or}</td><td></td></tr>\n};

    print qq{<tr><td class="bra">$lex{Student}</td>};
    print qq{<td><input type="text" name="student" size="30"></tr>\n};
    print qq{<tr><td></td><td class="cn">$lex{'Last,First/Last/Initials/Studnum'}</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Check} $lex{'Next Page'}</td>};
    print qq{<td><input type="checkbox" name="check"></td></tr>\n};

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

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

}



#----------------
sub searchStudent {
#----------------

    my $checked;
    if ( $arr{check} ) {
	$checked = q{checked = "checked"};
    }

    my $student = shift;

    # Setup the Search
    if ($student =~ /\d+/) {  # we have a student number
	$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
          where studnum = ?");
	$sth->execute( $student );

    } else { # we have words possibly with a comma
	($lastname,$firstname)  = split /\,/, $student;
	$firstname =~ s/^\s*//;
	$lastname =~ s/^\s*//;
	if ($lastname and $firstname){ # both entered.
	    $sth = $dbh->prepare("select  lastname, firstname, studnum from studentall 
             where lastname = ? and firstname = ?");
	    $sth->execute( $lastname, $firstname );

	} elsif ($lastname and not $firstname){ # only lastname (no comma)
	    if (length($lastname) == 2){ # search by initials: fi, li.
		my $fi = substr($lastname,0,1). '%'; 
		my $li = substr($lastname,1,1). '%';
		$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
                 where lastname $sql{like} ? and firstname $sql{like} ?");
		$sth->execute( $li, $fi );

	    } else {
		$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
                  where lastname = ? order by firstname");
		$sth->execute( $lastname );
	    }
	} else { # print an error....
	    print qq{<h1>$lex{Error}</h1>\n};
	    print qq{</body></html>\n};
	    exit;
	}

    } # Last Else
    # We should now have a $sth defined.


    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $rows = $sth->rows;
    # print qq{Rows: $rows<br>\n};


    if ( $rows < 1 ) { 
	print qq{<h1>$lex{'No Student(s) Found'}</h1>\n};
	print qq{<table cellspacing="0" cellpadding="3" border="0">\n};
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="hidden" name="page" value="1">\n};
	print qq{<table cellspacing="0" cellpadding="3" border="0">\n};

	print qq{<tr><td colspan="2" class="cn">$lex{Student} };
	print qq{($lex{'Last,First/Last/Initials/Studnum'})<br>};
	print qq{<input type="text" name="student" size="30"></td></tr>\n};

	print qq{<tr><td colspan="2" class="cn">\n};
	print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
	print qq{</table></form></body></html>\n};
	exit; 
    }

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


    # Get the Mode:  Add, Edit, Delete.
    print qq{<table cellpadding="3" cellspacing="0" border="0" style="margin-bottom:1em;">\n};
    print qq{<tr><th colspan="2">$lex{Mode}</th></tr>\n};
    print qq{<tr><td class="la"><input type="radio" name="mode" value="add"> $lex{Add}</td></tr>\n};
    print qq{<tr><td class="la"><input type="radio" name="mode" value="edit"> $lex{Edit}</td></tr>\n};
    print qq{<tr><td class="la"><input type="radio" name="mode" value="delete"> $lex{Delete}</td>};
    print qq{</tr>\n};
    print qq{</table>\n};

    # Select Students
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};

    print qq{<tr><td colspan="3" class="cn">\n};
    print qq{<input type="submit" value="$lex{'Continue'}"></td></tr>\n};

    print qq{<tr><th>$lex{Student}</th><th>$lex{'Record(s)'}</th><th>$lex{Select}</th></tr>\n};


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

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

	# Find any contacts
	$sth1->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth1->fetchrow;

	print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>$count</td><td>\n};
	print qq{<input type="checkbox" name="$studnum" value="1" $checked>\n};
	print qq{</td></tr>\n};

    }

    print qq{<tr><td colspan="3" class="cn">\n};
    print qq{<input type="submit" value="$lex{'Continue'}"></td></tr>\n};

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

    exit;

} # end of searchStudent



#--------------
sub searchGroup {
#--------------

    # search for a group of students (by grade(s) or homeroom(s))
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

    my $checked;
    if ( $arr{check} ) {
	$checked = q{checked = "checked"};
    }

    my ( $group, $groupid ) = @_;

    # Select Students
    my @students;
    my $sort = 'name'; # hold type of sort.

    if ( $groupid ) { # then we have to do something...

	my @groups;
	@groups = split /\s+/, $arr{groupid};
	if ( $group eq 'grade' ) {
	    $group = 'grade';
	    $sort = 'grade';
	} else {
	    $group = 'homeroom';
	    $sort = 'homeroom';
	}

	my $sth = $dbh->prepare("select studnum from student where $group = ? 
         order by $group, lastname, firstname");
	foreach my $grp ( @groups ) {
	    $sth->execute( $grp );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $studnum = $sth->fetchrow ) {
		push @students, $studnum;
	    }
	}

    } else { # all students

	my $sortorder = "lastname, firstname";
	if ( $arr{sortorder} eq $lex{Homeroom} ) {
	    $sortorder = "homeroom, lastname, firstname";
	    $sort = 'homeroom';
	} elsif ( $arr{sortorder} eq $lex{Grade} ) {
	    $sortorder = "grade, lastname, firstname";
	    $sort = 'grade';
	}

	$sth = $dbh->prepare("select studnum from student order by $sortorder");
	$sth->execute;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $studnum = $sth->fetchrow ) {
	    push @students, $studnum;
	}
    }

    # Now loop through all students
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};


    # Get the Mode:  Add, Edit, Delete.
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr><th colspan="2">$lex{Mode}</th></tr>\n};
    print qq{<tr><td class="la"><input type="radio" name="mode" value="add"> $lex{Add}</td></tr>\n};
    print qq{<tr><td class="la"><input type="radio" name="mode" value="edit"> $lex{Edit}</td></tr>\n};
    print qq{<tr><td class="la"><input type="radio" name="mode" value="delete"> $lex{Delete}</td>};
    print qq{</tr>\n};
    print qq{</table><p></p>\n};


    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><td colspan="3" class="cn">\n};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{<tr><th>$lex{Student}</th><th>$lex{'Record(s)'}</th><th>$lex{Select}</th></tr>\n};

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

    my $first = 1;

    foreach my $studnum ( @students ) {

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

	# Find any transactions; otherwise skip
	$sth1->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth1->fetchrow;

	print qq{<tr><td class="la"><b>$lastname</b>, $firstname ($studnum)</td>};
	print qq{<td class="cn">$count</td><td>\n};
	print qq{<input type="checkbox" name="$studnum" value="1" $checked>\n};
	print qq{</td></tr>\n};

    }

    print qq{<tr><td colspan="3" class="cn">\n};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};

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

    exit;

} # end of selectGroup



#--------------
sub modeOperate {  # either add, edit, or delete.
#--------------

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

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

    if ( not $mode ) {
	print qq{<h3>$lex{Mode} $lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Load any categories
    my @categories = ();
    my $sth = $dbh->prepare("select distinct category from contactlog 
      where category is not NULL and category != ''");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr;}
    while ( my $cat = $sth->fetchrow ) {
	push @categories, $cat;
    }


    # Get the students into %students hash
    $sth = $dbh->prepare("select lastname, firstname from student where studnum = ?");
    my %students = ();
    foreach my $key ( sort keys %arr ) {
	my $studnum = $key;
	$sth->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr;}
	my ( $lastname, $firstname ) = $sth->fetchrow;

	$students{"$lastname:$firstname:$studnum"} = $studnum;
    }



    if ( $mode eq 'add' ) {

	# Start Form.
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="hidden" name="page" value="4">\n};
	print qq{<input type="hidden" name="mode" value="add">\n};
	print qq{<input type="submit" value="$lex{Add}">\n};

	my $first = 1;
	foreach my $key ( sort keys %students ) {

	    my $studnum = $students{$key};
	    my ( $lastname, $firstname ) = split(':', $key); # last value is dropped

	    if ( $first ) { print qq{<hr>\n}; $first = 0; } # put in hrule.

	    print qq{<h1>$firstname $lastname ($studnum)</h1>\n};
	    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};


	    # Date
	    print qq{<tr><td class="bra">$lex{Date}</td><td class="la">\n};
	    print qq{<input type="text" size="10" id="date" name="$studnum:cdate" value="$currdate"> \n};
	    print qq{<button type="reset" id="date_trigger">...</button>\n};
	    print qq{</td></tr>\n};


	    # Category
	    print qq{<tr><td class="bra" valign="top">$lex{Category}</td><td class="la">\n};

	    print qq{<select name="$studnum:category"><option></option>};
	    foreach my $cat ( @categories ) { print qq{<option>$cat</option>}; }
	    print qq{</select>&nbsp;&nbsp;};

	    print qq{$lex{New} $lex{Category} <input type="text" size="30" name="$studnum:newcat">\n};
	    print qq{</td></tr>\n};


	    # Description
	    print qq{<tr><td class="bra">$lex{Description}</td><td class="la">\n};
	    print qq{<textarea rows="6" cols="60" name="$studnum:description"></textarea>\n};
	    print qq{</td></tr>\n};

	    print qq{</table><hr>\n};


	}

	print qq{<input type="submit" value="$lex{Add}">\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};



    } elsif ( $mode eq 'edit' ) {


	# Start Form.
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="hidden" name="page" value="3">\n}; # page 3 is edit function.
	print qq{<input type="submit" value="$lex{Edit}">\n};

	my $sth = $dbh->prepare("select * from contactlog where studnum = ?");

	my $first = 1;
	foreach my $key ( sort keys %students ) {

	    my $studnum = $students{$key};
	    my ( $lastname, $firstname ) = split(/:/, $key); # last value is dropped

	    if ( $first ) { print qq{<hr>\n}; $first = 0; } # put in hrule.
	    print qq{<h1>$firstname $lastname ($studnum)</h1>\n};

	    # Load records for this student.
	    $sth->execute( $studnum );
	    my $firstrec = 1;

	    while ( my $ref = $sth->fetchrow_hashref ) {

		if ( $firstrec ) {
		    print qq{<table cellpadding="5" cellspacing="0" border="1">\n};
		    print qq{<tr><th></th><th>$lex{Date}</th><th>$lex{Category}</th>};
		    print qq{<th>$lex{Description}</th></tr>\n};
		    $firstrec = 0;
		}

		my $desc = substr($ref->{description}, 0, 60);
		print qq{<tr><td><input type="checkbox" name="$ref->{id}" value="1"></td>};
		print qq{<td>$ref->{cdate}</td><td>$ref->{category}</td><td>$desc</td></tr>\n};

	    }

	    if ( $firstrec ) {
		print qq{<h3>$lex{'No Record(s) Found'}</h3><hr>\n};
	    } else {
		print qq{</table><hr>\n};
	    }

	} # end of student loop

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



    } elsif ( $mode eq 'delete' ) {


	    # Start Form.
	    print qq{<form action="$self" method="post">\n};
	    print qq{<input type="hidden" name="page" value="4">\n};
	    print qq{<input type="hidden" name="mode" value="delete">\n};
	    print qq{<input type="submit" value="$lex{Delete}">\n};


	    my $sth = $dbh->prepare("select * from contactlog where studnum = ?");

	    my $first = 1;
	    foreach my $key ( sort keys %students ) {

		my $studnum = $students{$key};
		my ( $lastname, $firstname ) = split(/:/, $key); # last value is dropped

		if ( $first ) { print qq{<hr>\n}; $first = 0; } # put in hrule.
		print qq{<h1>$firstname $lastname ($studnum)</h1>\n};

		# Load records for this student.
		$sth->execute( $studnum );
		my $firstrec = 1;

		while ( my $ref = $sth->fetchrow_hashref ) {

		    if ( $firstrec ) {
			print qq{<table cellpadding="5" cellspacing="0" border="1">\n};
			print qq{<tr><th></th><th>$lex{Date}</th><th>$lex{Category}</th>};
			print qq{<th>$lex{Description}</th></tr>\n};
			$firstrec = 0;
		    }

		    my $desc = substr($ref->{description}, 0, 60);
		    print qq{<tr><td>};
		    if ( $ref->{author} eq $userid ) { # only author can delete
			print qq{<input type="checkbox" name="$ref->{id}" value="1">};
		    }
		    print qq{</td><td>$ref->{cdate}</td><td>$ref->{category}</td><td>$desc</td></tr>\n};

		}

		if ( $firstrec ) {
		    print qq{<h3>$lex{'No Record(s) Found'}</h3><hr>\n};
		} else {
		    print qq{</table><hr>\n};
		}

	    } # end of student loop

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


    } # end of Delete


=head
    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 
    })\n};

    print qq{</script>\n};
=cut

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

    exit;

}


#--------------
sub editRecords {
#--------------

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

    # Load categories
    my @categories;
    my $sth = $dbh->prepare("select distinct category from contactlog 
      where category is not NULL and category != ''");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr;}
    while ( my $cat = $sth->fetchrow ) {
	push @categories, $cat;
    }

    my $sth = $dbh->prepare("select * from contactlog where id = ?");
    my $sth1 = $dbh->prepare("select lastname, firstname from student where studnum = ?");

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

    my $first = 1;

    foreach my $id ( sort keys %arr ) { 

	# Get Contactlog record
	$sth->execute( $id );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;

	my $studnum = $ref->{studnum};

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

	if ( $first ) { print qq{<hr>\n}; $first = 0; } # put in hrule.

	print qq{<h1>$firstname $lastname ($studnum)</h1>\n};
	print qq{<table cellpadding="3" cellspacing="0" border="0">\n};

	# Date
	print qq{<tr><td class="bra">$lex{Date}</td><td class="la">\n};
	if ( $ref->{author} eq $userid ) {
	    print qq{<input type="text" size="10" name="$id:cdate" id="$id:date" };
	    print qq{value="$ref->{cdate}"> \n};
	    print qq{<button type="reset" id="$id:date_trigger">...</button>\n};
	}
	print qq{</td></tr>\n};


	# Category
	print qq{<tr><td class="bra" valign="top">$lex{Category}</td><td class="la">\n};

	if ( $ref->{author} eq $userid ) {
	    print qq{<select name="$id:category"><option>$ref->{category}</option>};
	    foreach my $cat ( @categories ) { 
		if ( $cat eq $ref->{category} ) { next; }
		print qq{<option>$cat</option>}; 
	    }
	    print qq{</select> };
	    print qq{$lex{New} $lex{Category} <input type="text" size="30" name="$id:newcat">\n};

	} else { # just print existing category
	    print qq{$ref->{category}\n};

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


	# Description
	print qq{<tr><td class="bra">$lex{Description}</td><td class="la">\n};
	if ( $ref->{author} eq $userid ) {
	    print qq{<textarea rows="6" cols="60" name="$id:description">};
	    print qq{$ref->{description}</textarea>\n};

	} else {
	    print qq{$ref->{description}\n};
	}

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

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

	

    }

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



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

    exit;

}



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

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

    if ( not $mode ) {
	print qq{<h3>$lex{Mode} $lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


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


    if ( $mode eq 'add' ) {

	my $sth = $dbh->prepare("insert into contactlog ( studnum, cdate, category, description, author ) 
         values (?, ?, ?, ?, ?)");

	foreach my $key ( sort keys %arr ) {

	    my ($studnum, $fld ) = split(/:/, $key );
	    if ( $fld ne 'description' ) { next; } # skip all fields but description.
	    if ( not $arr{$key} ) { next; } # skip blank descriptions.

	    my $desc = $arr{$key};

	    my $newcatkey = "$studnum:newcat";
	    my $catkey = "$studnum:category";
	    my $datekey = "$studnum:cdate";

	    # New Category override
	    my $category;
	    if ( $arr{"$newcatkey"} ) {
		$category = $arr{"$newcatkey"};
	    } else {
		$category = $arr{"$catkey"};
	    }

	    my $cdate = $arr{"$datekey"};

	    # print qq{SN:$studnum Date:$cdate Cat:$category  Desc:$desc<br>\n};

	    $sth->execute( $studnum, $cdate, $category, $desc, $userid );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	
	}

	if ( not $DBI::errstr ) { 
	    print qq{<h3>$lex{'Record(s) Stored'}</h3>\n}; 
	} else { 
	    print qq{<h3>$lex{Error}: $DBI::errstr<br>\n};
	    print qq{$lex{Contact} $adminname  <a href="mailto:$adminemail">$adminemail</a></h3>\n};
	}


    } elsif ( $mode eq 'edit' ) {


	my %skip = (); # category records to skip, since newcat has value. 

	foreach my $key ( sort keys %arr ) {

	    if ( $skip{$key} ) { 
		print qq{Skipping: $key<br>\n};
		next; 
	    }

	    my ($id, $fld ) = split(/:/, $key );

	    if ( $fld eq 'newcat' ) { 
		if ( $arr{$key} ) { # and has a value.
		    $fld = 'category';
		    my $skipkey = "$id:category";
		    $skip{"$skipkey"} = 1;
		} else {
		    next;
		}
	    }

	    # print qq{ID:$id  Field:$fld Value:$arr{$key}<br>\n};

	    my $sth = $dbh->prepare("update contactlog set $fld = ? where id = ?");
	    $sth->execute( $arr{$key}, $id );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	
	}


	if ( not $DBI::errstr ) { 
	    print qq{<h3>$lex{'Record(s) Stored'}</h3>\n}; 
	} else { 
	    print qq{<h3>$lex{Error}: $DBI::errstr<br>\n};
	    print qq{$lex{Contact} $adminname  <a href="mailto:$adminemail">$adminemail</a></h3>\n};
	}

	# end of edit mode


    }  elsif ( $mode eq 'delete' ) {

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

	my $sth = $dbh->prepare("delete from contactlog where id = ?");

	foreach my $key ( sort keys %arr ) {

	    $sth->execute( $key );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	
	}


	if ( not $DBI::errstr ) { 
	    print qq{<h3>$lex{'Record(s)'} $lex{Deleted}</h3>\n}; 
	} else { 
	    print qq{<h3>$lex{Error}: $DBI::errstr<br>\n};
	    print qq{$lex{Contact} $adminname  <a href="mailto:$adminemail">$adminemail</a></h3>\n};
	}


    }

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

    exit;

};
