#!/usr/bin/perl
#  Copyright 2001-2024 Leslie Richardson

#  This file is part of Open Admin for Schools.

my %lex = ('Main' => 'Main',
	   'Student' => 'Student',
	   'Select' => 'Select',
	   'View Marks' => 'View Marks',
	   'Error' => 'Error',
	   'No Course Enrollments' => 'No Course Enrollments',

	   );

my $self = 'markview.pl';

use DBI;
use CGI;

# Passed Values: group: Homeroom, Grade, Student
# value: A value for one of the groups above.

# Read config variables
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);


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


# Print Page Head
my $title = $lex{'View Marks'};
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$tchcss" type="text/css">
$chartype\n</head><body>\n};

print qq{<div>[ <a href="$tchpage">$lex{Main}</a> ]</div>\n};
print qq{<h1>$title</h1>\n};

if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    selectStudents();
    
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    showResults();
}



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

    # Load Homerooms and Grades
    my (@grades, @homeroom, %homerooms );
    my $sth = $dbh->prepare("select distinct grade from student 
			    where grade is not NULL and grade != ''");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $gr = $sth->fetchrow ) {
	push @grades, $gr;
    }
    @grades = sort {$a <=> $b} @grades;

    # Get Staff Name
    my $sth1 = $dbh->prepare("select s.lastname, s.firstname, m.userid from staff s, staff_multi m
			    where m.field_name = 'homeroom' and m.field_value = ? and
			    m.userid = s.userid");

    
    my $sth = $dbh->prepare("select distinct homeroom from student 
			    where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr = $sth->fetchrow ) {
	push @homerooms, $hr;

	$sth1->execute($hr);
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname, $userid) = $sth1->fetchrow;
	$homerooms{$hr} = qq{$firstname $lastname};
	
    }
    # sort homerooms
    @homerooms = sort {$a <=> $b} @homerooms;


    
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;float:left;">\n};
    print qq{<tr><th>Home Room</th></tr>\n};
#    print qq{<caption>Select Homeroom</caption>\n};

    foreach my $hr ( @homerooms ) {
	print qq{<tr><td>};
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="submit" name="H:$hr" value="$hr - $homerooms{$hr}">\n};
	print qq{<input type="hidden" name="page" value="1">\n};
	print qq{</form></td></tr>\n};
    }
    print qq{</table>\n};

    print qq{<span style="float:left;margin:1em;">OR</span>\n};
    
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;float:left;">\n};
    print qq{<tr><th>Grade</th></tr>\n};
    foreach my $gr ( @grades ) {
    	print qq{<tr><td class="cn">};
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="submit" name="G:$gr" value="$gr">\n};
	print qq{<input type="hidden" name="page" value="1">\n};
	print qq{</form></td></tr>\n};
    }
    print qq{</table>\n};
    print qq{</body></html>\n};

    exit;

} # end of showStartPage

    
#-----------------
sub selectStudents {
#-----------------
    
    #foreach my $key (keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }    
    # Passed either grade or homeroom in (type:group) format.

    my $checked = qq{checked="checked"};
    if ( $arr{checknone} ) {
	$checked = '';
    }
    delete $arr{checknone};
    
    my ($type,$group);
    foreach my $key ( keys %arr ) {
	($type,$group) = split(':', $key);
    }

    my $groupname;
    if ( $type eq 'H' ) {
	$groupname = qq{Homeroom};
    } else {
	$groupname = qq{Grade};
    }
    print qq{<h3>$groupname $group</h3>\n};
    
    # Start Select None 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="checknone" value="1">\n};
    foreach my $key ( keys %arr ) {
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }
    
    print qq{<input type="submit" value="Turn Off All Selections"></form>\n};

    print qq{<hr style="width:10em;margin-left:0;height:3px;background-color:black;">\n};

    
    # Page Form start
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="submit" value="$lex{'View Marks'}">\n};

    
    my $sth;
    if ($type eq 'H') { # homeroom
	$sth = $dbh->prepare("select lastname,firstname, studnum from student 
			     where homeroom = ? order by lastname, firstname");
    } else { # grade
	$sth = $dbh->prepare("select lastname,firstname, studnum from student 
			     where grade = ? order by lastname, firstname");
    }
    
    $sth->execute( $group );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

    
    # Setup statement handle to find which table student is in.
    my $sth1 = $dbh->prepare("select count(*) from student where studnum = ?");

    
    print qq{<table border="1" cellpadding ="3" cellspacing="0">\n};
    print qq{<tr><th>$lex{Student}</th><th>$lex{Select}</th></tr>\n};


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

	# Now let's find which table student from: student or studentwd
	$sth1->execute($studnum);
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $active = $sth1->rows;  # returns 1 if in student, 0 if not.

	my $studentname = qq{<b>$lastname,</b> $firstname ($studnum) };
	if ( not $active ){ 
	    $studentname = qq{<span style="color:red">$studentname</span>};
	    $checked = '';
	}
    
	print qq{<tr><td>$studentname</td><td class="cn"><input type="checkbox" };
	print qq{name="$lastname:$firstname:$studnum" value="1" $checked>\n};
	print qq{</td></tr>\n};
    }
  
    print qq{</table>\n};
    print qq{<input type="submit" value="$lex{'View Marks'}">\n};
    print qq{</form></body></html>\n};

} # end of selectStudents



#--------------
sub showResults {
#--------------

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

    # Get All Course Information and put into hash with key as subjsec
    #  and value is pointer to the hash

    # Load the SupressSubject/Additional Comment data
    $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
    foreach my $val ('r_SupressSubject','r_AdditionalComments', 'g_TermDisplay') {
	$sth->execute( $val );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $dv = $sth->fetchrow;
	eval $dv;
    }

    
    my %course;
    my $sth = $dbh->prepare("select * from subject");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ){
	$course{ $ref->{subjsec} } = $ref;
    }

    # Get the number of terms from the eval table
    my $sth = $dbh->prepare("select max(term) from eval");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die;}
    my $maxterm = $sth->fetchrow;


    foreach my $stud (sort keys %arr){ # loop through passed student values

	my ($lastname, $firstname, $studnum) = split(':',$stud);
	print qq{<h3>$firstname $lastname ($studnum)</h3>\n};
	print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	print qq{<tr><th>Course</th><th colspan="10">Terms</th></tr>\n};
    
	# Create Structured Hash for eval results: 
	# a)Find his/her courses in order
	my $sth = $dbh->prepare("select distinct e.subjcode from eval e, subject s
				where e.subjcode = s.subjsec and e.studnum = ? 
				order by s.description,e.subjcode");
	$sth->execute($studnum);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

	my $sth1 = $dbh->prepare("select * from eval where subjcode = ? and
				 studnum = ? order by term");


	my $courseflag = 0; # flag in case of no course enrollments.
	while ( my $subjsec = $sth->fetchrow ){ # Loop through each course.

	    # skip if member of %r_SupressSubject or %r_AdditionalComments
	    my ($subjcode, $dud) = split('-', $subjsec);
	    if ( $r_SupressSubject{$subjcode} or $r_SupressSubject{$subjsec} or
		 $r_AdditionalComments{$subjcode} or $r_AdditionalComments{$subjsec} ) {
		next;
	    }
	    
	    # Get the Track, for Term Display
	    my $grade = $course{$subjsec}{grade};
	    my $track = $g_MTrackTermType{ $grade };
	    
	    $courseflag = 1;

	    # Get Objectives Count for this course; also # of loops
	    my $objcount; # objective count
	    for my $idx (1 .. 20){
		my $key = qq{q$idx};
		if ( $course{$subjsec}->{$key} ){ $objcount++; } else {last;}
	    }
	    
	    $sth1->execute($subjsec, $studnum); # Find the records for this course.
	    my %eval;
	    
	    while ( my $ref = $sth1->fetchrow_hashref ){ # Loop through eval recs.
		$eval{$ref->{term}} = $ref; # keyed by term.
	    }

# Test	    
#	    foreach my $term ( sort keys %eval ) {
#		print qq{TRM:$term / $eval{$term}{a1} / $eval{$term}{a2} / $eval{$term}{comment}<br>\n};
#	    }

	    if ( %eval ){ # If we have any eval records for this course...
		if ($objcount == 0){ # No objectives... just marks (1 line)
		    print qq{<tr><td class="bla">$course{$subjsec}{description}</td>};
		    for my $term (sort keys %eval ){
			print qq{<td class="la"><b>$g_TermDisplay{$track}{$term}</b><br>};
			print qq{$eval{$term}{a1}<br>\n};
			print qq{$eval{$term}{comment}</td>\n};
		    }
		    print qq{</tr>\n};
		    
		} else { # We have objectives listed
		    print qq{<tr><td class="bla">$course{$subjsec}{description}</td>};
		    for my $term (sort keys %eval ){
			print qq{<td class="la"><b>$g_TermDisplay{$track}{$term}</b><br>\n};
			# Print eval records
			foreach my $idx (1..$objcount) {
			    my $evalkey = qq{a$idx}; # key is 'a' for eval','q' for subject/course
			    my $crskey = qq{q$idx};
			    print qq{$course{$subjsec}{$crskey} - $eval{$term}{$evalkey}<br>\n};
			}
			if ( $eval{$subjsec}{$term}{comment} ) { # print comment if present
			    print qq{$eval{$subjsec}{$term}{comment}<br>\n};
			}
			print qq{</td>\n\n};
		    }
		}
		
	    }  # End of 'Do we have eval records?'

	} # Next Course

	if ( not $courseflag ){ # No course enrollments for this student.
	    print qq{<tr><td colspan="10" class="la">$lex{'No Course Enrollments'}</td></tr>\n};
	}
	print qq{</table>\n};

    } # End of Student Loop

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

    exit;

}
