#!/usr/bin/perl
# Copyright Les Richardson 2001-2019

my %lex = ('Homeroom Assignment' => 'Homeroom Assignment',
	   'Update Homerooms' => 'Update Homerooms',
	   'Student' => 'Student',
	   'HRm' => 'HRm',
	   'Teacher' => 'Teacher',
	   'Not Found' => 'Not Found',
	   'Grade' => 'Grade',
	   'Main' => 'Main',
	   'Eoy' => 'Eoy',
	   'Contact' => 'Contact',
	   'Error' => 'Error',
	   'Record(s) Updated' => 'Record(s) Updated',

	   );

my $self = 'resethroom.pl';

use DBI;
use CGI;

eval require "../../etc/admin.conf";
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);


# Start Page Head
my $title = $lex{'Homeroom Assignment'};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body>\n};

print qq{[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="$eoypage">$lex{Eoy}</a> ]\n};

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


# update records if necessary.
if ( $arr{flag} ) {
    delete $arr{flag};
    resetRecords();
}


# Read teachers into a data structure
my $sth = $dbh->prepare("select lastname, firstname, userid
 from staff order by lastname, firstname");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

# Clone Query Functions.
my $sth1 = $dbh->prepare("select sm.field_value from staff as s, staff_multi as sm
 where sm.userid = s.userid and sm.field_name = ? and s.userid = ?");
my $sth2 = $dbh->prepare("select sm.field_value from staff as s, staff_multi as sm
 where sm.userid = s.userid and sm.field_name = ? and s.userid = ?");


# Put Teachers into Data Struct
while ( my ( $lastname, $firstname, $userid ) = $sth->fetchrow ){

    $sth1->execute( 'grade', $userid );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my  $grade = $sth1->fetchrow ) {

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

	    if ( not $homeroom{ $grade } ) {
		$homeroom{ $grade } = { }; # hash constructor
	    }

	    if ( not $homeroom{$grade}->{$homeroom} ) {
		$homeroom{$grade}->{$homeroom} = [ ]; # array constructor
	    }

	    push @{ $homeroom{$grade}->{$homeroom} }, "$firstname $lastname";
	}
    }
}


# Now test construction
#foreach my $grade ( sort keys %homeroom ) {
#    foreach my $hrm (sort keys %{ $homeroom{$grade} } ) {
#        foreach my $name ( @{ $homeroom{$grade}->{$hrm} } ){
#	    print qq{Name: $name  Hr:$hrm Gr:$grade<br>\n};
#	}
#    }
#}



my $sth = $dbh->prepare("select distinct grade from student 
  order by grade, lastname, firstname");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
my $ref = $sth->fetchall_hashref(grade);
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
my @grades = sort {$a <=> $b} keys %$ref; 


$sth = $dbh->prepare("select studid, lastname, firstname, homeroom from student 
  where grade = ? order by lastname, firstname");

print qq{<form action="$self" method="post">\n};
print qq{<input type="hidden" name="flag" value="1">\n};
print qq{<p><input type="submit" value="$lex{'Update Homerooms'}"></p>\n};


my $currgrade = "-1";
my $oldgrade;

my $count;
foreach my $grade ( @grades ) {

    print qq{<table border="1" cellpadding="3" cellspacing="0" };
    print qq{style="margin-bottom:1em;float:left;margin:1em;">\n};
    print qq{<caption style="font-weight:bold;font-size:130%;">};
    print qq{$lex{Grade} $grade</caption>\n};
    print qq{<tr><th>$lex{Student}</th><th>$lex{HRm} $lex{Teacher}};
    print qq{</th></tr>\n};

    # setup homeroom/teacher choices for this grade
    my %hrtable; # empty table
    foreach my $hrm ( keys %{ $homeroom{$grade} } ) {
	my $teachernames;
	foreach my $name ( @{ $homeroom{$grade}->{$hrm} } ) {
	    $teachernames .= $name. '/';
	}
	chop $teachernames; # remove trailing slash;
	if ( not $teachernames ){ $teachernames = $lex{'Not Found'}; }
	$hrtable{$hrm} = $teachernames;
    }


    $sth->execute( $grade );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $first = 1;

    while ( my ( $studid, $lastname, $firstname, $homeroom ) = $sth->fetchrow ) {

	print qq{<tr><td><b>$lastname</b>, $firstname</td>\n<td>};
	print qq{<select name="$studid"><option>$homeroom:$hrtable{$homeroom}</option>\n};
	
	foreach my $hr ( sort keys %hrtable ) {
	    if ( $hr eq $homeroom ) { next; }
	    print qq{<option>$hr:$hrtable{$hr}</option>};
	}

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

    } # End of student Loop
    print qq{</table>\n};

    $count++;
    if ( $count % 3 == 0 ) { print qq{<br clear="left">\n}; }

} # end of grade loop

print qq{<br clear="left"><input type="submit" value="$lex{'Update Homerooms'}">};
print qq{</form></body></html>\n};



#---------------
sub resetRecords {
#---------------

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

    my $sth = $dbh->prepare("update student set homeroom = ? where studid = ?");
    foreach my $key ( keys %arr ) {
	my ($rmnum, $teacher) = split(/:/,$arr{$key});
	$rmnum =~ s/://;
	if ( not $teacher ) { $rmnum = undef; }

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


    if ( not $DBI::errstr ) {
	print qq{<h3>$lex{'Record(s) Updated'}</h3>};

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

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

    exit;

}
