#!/usr/bin/perl
#  Copyright 2001-2016 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 = ('View' => 'View',
	   'Nominal Roll' => 'Nominal Roll',
	   'Main' => 'Main',
	   'Edit' => 'Edit',
	   'Delete' => 'Delete',
	   'Error' => 'Error',
	   'Student' => 'Student',
	   'Grade' => 'Grade',
	   'Records' => 'Records',
	   'Continue' => 'Continue',
	   'All' => 'All',
	   'Fields' => 'Fields',
	   'Select' => 'Select',
	   'Students' => 'Students',
	   'Homeroom' => 'Homeroom',
	   'Check' => 'Check',
	   'Next Page' => 'Next Page',
	   'Blank=All' => 'Blank=All',
	   'Not Found' => 'Not Found',
	   'Record' => 'Record',
	   'Group' => 'Group',

	   );


use DBI;
use CGI;

my $self = 'nrview2.pl';
$nrtable = 'student_inac';


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



# Read student inac fields, and defaults into fields and %fieldname hash.
my $sth = $dbh->prepare("select fieldid, fieldname
 from meta where tableid = 'student_inac' order by fieldname");
$sth->execute;
my %fieldnames = ();
my @fields = ();

while ( ( my $fieldid, $fieldname ) = $sth->fetchrow ) {
    if ( $fieldid eq 'id' ) { next; } # skip id field.
    $fieldname =~ s/\(//g;
    $fieldname =~ s/\)//g; # strip parentheses. (sp?)
    push @fields, $fieldid;
    $fieldnames{ $fieldid } = $fieldname;
}


# Print Page Header
my $title = "$lex{View} $lex{'Nominal Roll'} $lex{'Records'} 2";
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{<h1>$title</h1>\n};

viewStudents();



#---------------
sub viewSelectStudents {
#---------------

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


    my $select;
    my @grp = ();
    my @students = ();
    my %studrec = ();

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


    if ( $arr{groupvalue} ) {
	my $grp = 'grade';
	if ( $arr{grouptype} eq 'homeroom' ) { $grp = 'homeroom'; }

	# Check Value
	my $sth = $dbh->prepare("select distinct $grp from student where $grp != '' and $grp is not NULL");
	$sth->execute;
	my %group = ();
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $val = $sth->fetchrow ) {
	    $group{$val} = 1;
	}

	if ( not $group{ $arr{groupvalue}} ) {
	    print "<h3>$lex{Group} $lex{'Not Found'}</h3>\n";
	    print "</body></html>\n";
	    exit;
	}

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

    } else { # all records in nominal roll table

	my %students = ();

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

	my $sth = $dbh->prepare("select studnum from $nrtable order by studnum");
	$sth->execute;
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

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

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

	foreach my $key ( sort keys  %students ) {
	    push @students, $students{$key};
	}
	    
    }


    # Select Students
    print "<td><form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"2\">\n";
    print "<input type=\"hidden\" name=\"field\" value=\"$arr{field}\">\n";

    print "<table cellpadding=\"3\" border=\"1\" cellspacing=\"0\">\n";

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

    print "<tr><th>$lex{Student}</th><th>";
    print "$lex{Grade}/<br>$lex{Homeroom}";
    print "</th><th>$lex{Select}</th></tr>\n";

    # Get Name
    my $sth1 = $dbh->prepare("select lastname, firstname, grade, homeroom from studentall where studnum = ?");
    my $sth2 = $dbh->prepare("select count(*) from $nrtable where studnum = ?");


    my $count = 1;
    foreach my $studnum ( @students ) {

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

	print "<tr><td>$count. <b>$lastname</b>, $firstname ($studnum)</td>";
	print "<td>$grade/$homeroom</td>\n";

	# Check for NR record
	$sth2->execute($studnum);
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $nrcount = $sth2->fetchrow;

	if ( $nrcount > 0 ) {
	    print "<td><input type=\"checkbox\" name=\"$studnum\" value=\"1\" $checked></td></tr>\n";
	} else {
	    print "<td>$lex{Record} $lex{'Not Found'}</td></tr>\n";
	}

	$count++;

    }

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

    print "</table></form>\n";
    print "</body></html>\n";

} # end of viewSelectStudents


#---------------
sub viewStudents { #all
#---------------

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


    # Read student inac fields, and defaults into fields and %fieldname hash.
    my $sth = $dbh->prepare("select fieldid, defaultvalue,formtype from meta where tableid = 'student_inac'");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my %sp;
    my %formtype;

    while ( my ($fieldid, $dv, $type) = $sth->fetchrow ) {
	$formtype{$fieldid} = $type;
	# print "DV:$dv<br>\n";
	my %tmp = split(/\s+/, $dv);
	foreach my $key ( keys %tmp ) { 
	    $tmp{$key} =~ s/\_/ /g;
	}
	$sp{$fieldid} = { %tmp };
    }

=head
    use Data::Dumper;
    print Dumper %sp;
    exit;
=cut

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

    my $sth = $dbh->prepare("select n.serviceprovision, s.lastname, s.firstname, s.grade, s.studnum from $nrtable n , studentall s
       where s.studnum = n.studnum order by serviceprovision, grade, lastname, firstname");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    print "<table cellpadding=\"3\" border=\"1\" cellspacing=\"0\">\n";
    print qq{<caption style="font-weight:bold;">Continued Enrollment = Current Year Students</caption>\n};

#    print "<tr><th>Name</th><th>Grade</th><th>Service Provision</th>\n";
#    foreach my $fld ( @fields ) {
#	if ( $fld eq 'studnum' or $fld eq 'serviceprovision' ) { next; }
#	print "<th>$fieldnames{$fld}</th>";
#    }
#    print "</tr>\n";
    

    my $color1 = '#FFF';
    my $color2 = '#DDD';
    my $bgcolor;

    my $count = 0;
    my $spval = 0;
    my $grd = 0;

    while ( my ($serviceprovision, $lastname, $firstname, $grade, $studnum ) = $sth->fetchrow ) {


	$sth1->execute( $studnum);
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth1->fetchrow_hashref;
	my %r = %$ref;


	if ( $spval != $serviceprovision ) { $count = 0; }
	$spval = $serviceprovision;
	$count++;

	# Toggle color on grade change.
	if ( $grd ne $grade ) { # toggle color;
	    if ( $bgcolor eq $color1 ) { $bgcolor = $color2; } else { $bgcolor = $color1; }
	    print "<tr><th>Name</th><th>Grade</th><th>Service Provision</th>\n";
	    foreach my $fld ( @fields ) {
		if ( $fld eq 'studnum' or $fld eq 'serviceprovision' ) { next; }
		print "<th>$fieldnames{$fld}</th>";
	    }
	    print "</tr>\n";

	}
	$grd = $grade;


	my $spvalue = "$sp{serviceprovision}{$serviceprovision} ($serviceprovision)";
	if ( not $serviceprovision ) {
	    $spvalue = qq{<span style="color:red;font-weight:bold;">No Value</span>};
	}

	print qq{<tr style="background-color:$bgcolor;">};

	print qq{<td>$count. };

	print qq{<b>$lastname</b>, $firstname ($studnum) } ;

	print qq{<form action="nrdeled.pl" method="post" style="display:inline;"><input type="hidden" name="page" value="2">};
	print qq{<input type="hidden" name="type" value="Edit"><input type="hidden" name="field" value="all">};
	print qq{<input type="hidden" name="$studnum" value="1"><input type="submit" value="Edit"></form></td>\n};


	print qq{<td>$grade</td><td>$spvalue</td>};

	foreach my $fld ( @fields ) {
	    if ( $fld eq 'studnum' or $fld eq 'serviceprovision' ) { next; }

	    my $v = $r{$fld}; # this gives the actual value for this field (ie. code value)

	    my $val;
	    if ( not $v ) { 
		$val = qq{<span style="color:red;font-weight:bold;">No Value</span>}; 
	    } elsif ( $formtype{$fld} eq 'selecthash' ) { # look up matching descriptor for this code value
		$val = "$sp{$fld}{$v} ($v)";
	    } else { # otherwise just a straight value
		$val = $v;
	    }
	    print "<td>$val</td>";
	}
	print "</tr>\n";

    }

    print "</table>\n";
    print "</body></html>\n";

} # end of viewStudents
