#! /usr/bin/perl
#  Copyright 2001-2023 Leslie Richardson
 
#  This file is part of Open Admin for Schools.


my %lex = ('Report' => 'Report',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Report Card' => 'Report Card',
	   'Main' => 'Main',
	   'Term' => 'Term',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Select by' => 'Select by',
	   'End' => 'End',
	   'OR' => 'OR',
	   'Form' => 'Form',
	   
	   );

my $self = 'rptObjective.pl';
# Control printing of numeric values
my $precision = 1;
my $trailing_zeros = 0;

use DBI;
use CGI;
use Cwd;
use Number::Format qw(:all);


# Get current dir so know what path for config files.
my $configpath;
if (getcwd() =~ /tcgi/){ # we are in tcgi
    $configpath = '..'; # go back one to get to etc.
} else {
    $configpath = '../..'; # go back two to get to etc.
}

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

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


# Get current dir so know what CSS to display;
if (getcwd() =~ /tcgi/){ # we are in tcgi
    $css = $tchcss;
}

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

if (length($mon) == 1){ $mon = '0'.$mon;}
if (length($mday) == 1){ $mday = '0'.$mday;}
my $currsdate = "$year-$mon-$mday";


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


my $q = new CGI;
print $q->header( -charset, $charset );
my %arr = $q->Vars;

my $term = $arr{term};

# Print the Page Header
my $title = "Objective $lex{Report}";
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
$chartype\n</head><body style="margin:1em;">\n};

print qq{<div>[ <a href="$homepage">$lex{Main}</a> \n};
if ( not (getcwd() =~ tcgi) ) { # not running in tcgi
    print qq{| <a href="$reppage">$lex{'Report Card'}</a>\n};
}
print qq{ ]</div>\n};

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



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

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

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    showObjectives();
}


#----------------
sub selectCourses {
#----------------

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

    if ( not $arr{homeroom} and not $arr{grade} ) {
	print qq{<h3>No Grade or Homeroom Selected</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    if ( not $arr{term} ) {
	print qq{<h3>No End Term Selected</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my $endterm = $arr{term}; # select courses for a student group.

    
    my (%students,@studnum);
    if ( $arr{grade} ) { # get all students in this grade;
	my $sth = $dbh->prepare("select * from student where grade = ?");
	$sth->execute( $arr{grade} );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    my $studnum = $ref->{studnum};
	    push @studnum, $studnum;
	    $students{$studnum} = $ref;
	}
    } elsif ( $arr{homeroom} ) {
	my $sth = $dbh->prepare("select * from student where homeroom = ?");
	$sth->execute( $arr{homeroom} );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    my $studnum = $ref->{studnum};
	    push @studnum, $studnum;
	    $students{$studnum} = $ref;
	}
    }

    # now get the students' courses
    my %courses;
    
    my $sth = $dbh->prepare("select subjcode from eval where studnum  = ?");

    # Loop over all students in this grade/homeroom and get their course codes
    foreach my $studnum ( @studnum ) {
	$sth->execute( $studnum );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $subjsec = $sth->fetchrow ) {
	    $courses{$subjsec} = 1;
	}
    }
    # we now have all courses for all these students

#    print qq{<div>Courses: }, %courses, "<br>\n";
    

    my %sort; # course sort;
    my $sth = $dbh->prepare("select * from subject where subjsec = ?");
    foreach my $subjsec ( keys %courses ) {
	
	$sth->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %c = %$ref; # course record	
	
	if ( $c{endrptperiod} != $endterm ) { next; } # skip if not correct end term.

	$courses{$subjsec} = $ref;
	$sort{"$c{description}$subjsec"} = $subjsec;
    }

    # Start Form
    # now select the courses of interest with the correct end term.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    foreach my $key ( keys %arr ) { # grade, homeroom, term (end term)
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }

    # now display courses for selection.
    my $first = 1;
    
    foreach my $key ( sort keys %sort ) {
	my $subjsec = $sort{$key};

	if ( $first ) { # start table.
	    print qq{<table cellpadding="3" cellspacing="0" border="0" };
	    print qq{style="border:1px solid gray;padding:0.4em;">\n};
	    print qq{<tr><th>Select Courses</th>\n};
	    $first = 0;
	}

	my %crs = %{$courses{$subjsec}}; # get record of this course
	
	print qq{<tr><td><input type="checkbox" name="$subjsec" value="1"> };
	print qq{$crs{description} ($subjsec)</td></tr>\n};

    }

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

    
    if ( not $first ) { # close table
	print qq{</table>\n};
    } else { # no courses
	print qq{<h3>No Courses Found</h3>\n};
	exit;
    }

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

    exit;

} # end of selectCourses



#-----------------
sub showObjectives {
#-----------------

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

    my $endterm = $arr{term};
    my $grade = $arr{grade};
    my $homeroom = $arr{homeroom};
    delete $arr{term};
    delete $arr{grade};
    delete $arr{homeroom};
    # now just courses left in %arr hash.

    if ( $grade ) {
	print qq{<h2>Grade $grade</h2>\n};
    } elsif ( $homeroom ) {
	print qq{<h2>Homeroom $homeroom</h2>\n};
    }

    
    
    my (%students,@sort);
    if ( $grade ) { # get all students in this grade;
	my $sth = $dbh->prepare("select * from student where grade = ?");
	$sth->execute( $grade );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    my %s = %$ref;
	    my $studnum = $s{studnum};
	    $sort{"$s{lastname}$s{firstname}$studnum"} = $studnum;
	    $students{$studnum} = $ref;
	}
    } elsif ( $homeroom ) {
	my $sth = $dbh->prepare("select * from student where homeroom = ?");
	$sth->execute( $homeroom );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $ref = $sth->fetchrow_hashref ) {
	    my %s = %$ref;
	    my $studnum = $s{studnum};
	    $sort{"$s{lastname}$s{firstname}$studnum"} = $studnum;
	    $students{$studnum} = $ref;
	}
    }

    # now do sorted course.
    my ( %course, %csort);
    my $sth = $dbh->prepare("select * from subject where subjsec = ?");
    
    foreach my $subjsec ( keys %arr ) {
	$sth->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %c = %$ref;
	$csort{"$c{description}$subjsec"} = $subjsec;
	$course{$subjsec} = $ref;
    }

    # Course Loop
    foreach my $key ( sort keys %csort ) {
	my $subjsec = $csort{$key};
	my %crs = %{$course{$subjsec}}; # full record for this course, including objectives
	my $startterm = $crs{startrptperiod};
	my $endterm = $crs{endrptperiod};
	my $termcount = $endterm - $startterm + 1;
	
	my %index; # index of the objective (in subject) and answer (in eval table)
	my @objidx; 
	for my $idx ( 1..20 ) {
	    my $okey = 'q'.$idx; # objective key
	    if ( $crs{$okey} ) { # we have an objective
		my $ekey = 'a'.$idx; # eval key field
		$index{$okey} = $ekey;
		push @objidx, $okey; # q1,q2, etc.
	    }
	}
	
	# Start table for this course
	my $first = 1;
	my $sth = $dbh->prepare("select * from eval where subjcode = ? and term = ? and studnum = ?");
	
	# Loop over the students
	foreach my $key ( sort keys %sort ) {
	    my $studnum = $sort{$key};
	    my %s = %{ $students{$studnum}}; # student record in %s hash

	    # get all term data in this course for this student
	    my %eval; # eval{term} = rec
	    foreach my $trm ( $startterm..$endterm ) {
		$sth->execute( $subjsec,$trm,$studnum );
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		my $ref = $sth->fetchrow_hashref;
		my %e = %$ref;
#		print qq{<div>1:$e{a1} / $e{a2} / $e{a3} / $e{a4} / $e{a5}</div>\n};
		$eval{$trm} = $ref;
	    }

	    
	    if ( $first ) { # start table.
		print qq{<h3>$crs{description} ($subjsec)</h3>\n};
		print qq{<table cellpadding="3" cellspacing="0" border="1" };
		print qq{style="border:1px solid gray;padding:0.4em;">\n};
		
		print qq{<tr><th>Name</th>\n};

		foreach my $okey ( @objidx ) {
		    print qq{<th colspan="$termcount">$crs{$okey}</th>}; # ($okey) testing
		}
		print qq{</tr>\n};

		# now the terms row
		print qq{<tr><th></th>};
		foreach my $okey ( @objidx ) {
		    foreach my $trm ($startterm .. $endterm) {
			print qq{<th>Term $trm</th>};
		    }
		}
		print qq{</tr>\n};
		
		$first = 0;
	    }

	    # now the student records
	    print qq{<tr><td>$s{firstname} <b>$s{lastname}</b></td>\n};
	    #	    foreach my $okey ( sort {$a <=> $b} keys %index ) {
	    foreach my $okey ( @objidx ) {
		foreach my $trm ($startterm .. $endterm) {
		    my $evalindex = $index{$okey};
		    my $val = ${ $eval{$trm} }{$evalindex};
		    if ( $val =~ m/\d+/ ) {
			$val = format_number($val, $precision,$trailing_zeros);
		    }
		    print qq{<td class="cn">$val</td>}; # ($okey)</td>};
		}
	    }
	    print qq{</tr>\n};
    
	} # end of student loop
	if ( not $first ) { # close table
	    print qq{</table>\n};
	    print qq{<div style="page-break-after:always;"></div>\n};
	}
	
    } # end of course loop

    
    print qq{</body></html>\n};
    exit;
    
} # end of showObjectives
    



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

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

    # Get the grades
    my @grades;
    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;
    }


    # Get the homerooms.
    my @homerooms;
    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; # removed checking below
    }

    
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;padding:0.4em;">\n};

    # Grades
    print qq{<tr><td class="bra">$lex{'Select by'} $lex{Grade}};
    if ( $schoolmode == 1 ) {
	print qq{/$lex{Form}};
    }
    print qq{</td>};
    print qq{<td class="la"><select name="grade"><option value=""></option>\n}; 
    foreach my $gr ( sort {$a <=> $b} @grades ) {
	my $displaygrade = $gr;
	if ( $schoolmode == 1 ) { # British mode
	    my $val = $g_FormMap{$gr};
	    if ( not $val ) { $val = $gr; }
	    if ( $val =~ m/F|f/ ) { # we are adding form.
		$val =~ s/F|f/$lex{Form} /;
	    }
	    $displaygrade = $val;
	}
	print qq{<option value="$gr">$displaygrade</option>};
    }
    print qq{</select></td></tr>\n};

    print qq{<tr><td class="bcn" colspan="2">$lex{OR}</td><td></td></tr>\n};
    
    # Homeroom
    print qq{<tr><td class="bra">$lex{'Select by'} $lex{Homeroom}</td>};
    print qq{<td class="la"><select name="homeroom"><option value=""></option>\n}; 
    foreach my $hr ( sort {$a <=> $b} @homerooms ) {
	print qq{<option>$hr</option>};
    }
    print qq{</select></td></tr>\n};
    
    print qq{<tr><td colspan="2"><hr></td></tr>\n};

    
    # Term Select
    # Find all of the term end dates
    my $sth = $dbh->prepare("select distinct endrptperiod from subject order by endrptperiod");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    print qq{<tr><td class="bra">Course $lex{End} $lex{Term}</td><td class="la">};
    print qq{<select name="term"><option value=""></option>\n};
    while ( my $endterm = $sth->fetchrow ) {
	if ( not $endterm ) { next; }
	print qq{<option value="$endterm">$endterm</option>\n};
    }
    print qq{</select></td></tr>\n};

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

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

    exit;

}

