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

#  This file is part of Open Admin for Schools.


my %lex = ('Mark Report' => 'Mark Report',
	   'Main' => 'Main',
	   'Report Card' => 'Report Card',
	   'Grade' => 'Grade',
	   'Teacher' => 'Teacher',
	   'Subject' => 'Subject',
	   'Error' => 'Error',
	   'Term' => 'Term',
	   'Sort by' => 'Sort by',
	   'Continue' => 'Continue',
	   'Not Found' => 'Not Found',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Font Size' => 'Font Size',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Students' => 'Students',
	   'Page' => 'Page',
	   'Width' => 'Width',
	   'Mark' => 'Mark',
	   'Select by' => 'Select by',
	   'Subjects' => 'Subjects',
	   'Homeroom' => 'Homeroom',
	   'Course' => 'Course',
	   'WD' => 'WD',
	   
	   );

use DBI;
use CGI;

my $self = 'rptTermMark.pl';
my $maxlines = 24;
my $markwidth = 8; # 8mm
my $bgcolor = '#DDD';

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

eval require "../../lib/liblatex.pl";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

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

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

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



# Load the SupressSubject, AdditionalComments data
my $sth = $dbh->prepare("select datavalue from conf_system
			where dataname = ?");

foreach my $val ( qw(r_SupressSubject r_AdditionalComments g_TermDisplay )) {
    $sth->execute( $val );
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my $dv = $sth->fetchrow;
    eval $dv;
}



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

print qq{[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="$reppage">$lex{'Report Card'}</a> ]\n};

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

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

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

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

}


#--------------
sub printReport {
#--------------

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

    my %skiplist = qw( fontsize 1 papersize 1 markwidth 1 term 1 display 1 
		       sort 1 select 1 maxstudent 1);
    # maxstudent 1 was above by mistake.
    # foreach my $key ( sort keys %skiplist ) { print qq{K:$key V:$skiplist{$key}<br>\n}; }

    my @subjects;
    if ( $arr{select} eq 'grade' ) { # get the subjects for each of these grades

	my $sortorder = 'description, subjsec';
	if ( $arr{sort} eq 'teacher' ) {
	    $sortorder = 'teacher, description, subjsec';
	}

	# find all subjects containing this term.
	my $sth = $dbh->prepare("select subjsec, grade, description, teacher from subject
				where startrptperiod <= ?  and endrptperiod >= ?
				order by $sortorder");
	$sth->execute( $arr{term}, $arr{term});
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	my %subjects = ();
	while ( my ( $subjsec, $grade, $desc, $teacher ) = $sth->fetchrow ) {

	    # Skip Unwanted Subjects
	    my ($subjcode, $dud) = split(/-/, $subjsec);
	    if (   $r_SupressSubject{$subjsec} or $r_SupressSubject{$subjcode} or 
		   $r_AdditionalComments{$subjsec} or $r_AdditionalComments{$subjcode} ) {
		next; 
	    }
	    
	    my $sortfield;
	    if ( $arr{sort} eq 'teacher' ) {
		$sortfield = "$teacher$subjsec";
	    } else {
		$sortfield = "$desc$subjsec";
	    }

	    $subjects{$grade}{$sortfield} = $subjsec;
	}


	# Now select subjects in these grades, sort by 
	# Loop through all grades; skip other values
	foreach my $key ( sort {$a <=> $b} keys %arr ) {
	    if ( exists $skiplist{$key} ) { next; }

	    foreach my $skey ( sort keys %{ $subjects{$key} } ) {
		push @subjects, $subjects{$key}->{$skey};
	    }
	}

    } elsif ( $arr{select} eq 'homeroom' ) { # get the subjects for this homeroom


	my %subjects;

	my $sth1 = $dbh->prepare("select distinct e.subjcode, s.description 
				 from eval e, subject s where e.subjcode = s.subjsec and studnum = ?");

	my $sth = $dbh->prepare("select studnum from student where homeroom = ?");
	$sth->execute( $arr{homeroom} );
	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; }
	    while ( my ($subjsec, $desc) = $sth1->fetchrow ) {

		# skip if one of the 'attendance only' subjects
		if (   $r_SupressSubject{$subjsec} or $r_SupressSubject{$subjcode} or 
		       $r_AdditionalComments{$subjsec} or $r_AdditionalComments{$subjcode} ) {
		    next; 
		}

		$subjects{"$desc$subjsec"} = $subjsec;
	    }
	}
	# now all subjects in %subjects

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


    } else { # select by subjsec (passed)


	my $sth = $dbh->prepare("select grade, description, teacher from subject
				where subjsec = ?");

	my %subjects;
	foreach my $key ( keys %arr ) {
	    if ( exists $skiplist{$key} ) { next; }

	    $sth->execute( $key );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $grade, $desc, $teacher ) = $sth->fetchrow;
	    my $subjsec = $key;

	    my $sortfield;
	    if ( $arr{sort} eq 'teacher' ) {
		$sortfield = "$teacher$desc$subjsec";
	    } elsif ( $arr{sort} eq 'grade' ) {
		$sortfield = "$grade$desc$subjsec";
	    } else {
		$sortfield = "$desc$subjsec";
	    }
	    $subjects{$sortfield} = $subjsec;
	}

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

    } # end

    # Now all subjects in @subjects!

  
    if ( not @subjects ){ 
	print qq{<h1>$lex{Subjects} $lex{'Not Found'}</h1>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    my $fontsize = $arr{fontsize}. 'pt';

    my ( $papersize, $textwidth, $textheight );

    if ( $arr{papersize} eq 'letter' ) {
	$papersize = 'letterpaper';
	$textwidth = $g_letterpaper_textwidth;
	$textheight = $g_letterpaper_textheight;

    } elsif ( $arr{papersize} eq 'legal' ) {
	$papersize = 'legalpaper';
	$textwidth = $g_legalpaper_textwidth;
	$textheight = $g_legalpaper_textheight;

    } elsif ( $arr{papersize} eq 'a4' ) {
	$papersize = 'a4paper';
	$textwidth = $g_a4paper_textwidth;
	$textheight = $g_a4paper_textheight;
    } 

    
    # max lines per page, default at top
    if ( $arr{maxstudent} ) {
	$maxlines = $arr{maxstudent};
    } 


    # Setup TEX Code
    my $shortname = "termmark$$";
    my $filename = "$shortname.tex";

    open(TEX,">$filename") || die "Can't open tex file";


    print TEX "\\documentclass[ $fontsize, $papersize]{article}
\\usepackage{array,rotating,noto}
\\renewcommand{\\familydefault}{\\sfdefault}
\\pagestyle{empty}
\\setlength{\\textwidth}{$textwidth}
\\setlength{\\textheight}{$textheight}
\\setlength{\\hoffset}{-20mm}
\\setlength{\\voffset}{-50mm}
\\setlength{\\evensidemargin}{0mm}
\\setlength{\\oddsidemargin}{0mm}
\\setlength{\\tabcolsep}{3.5pt}
\\setlength{\\extrarowheight}{6pt}\n";

    print TEX "\\begin{document}\n";


    print qq{<div style="font-weight:bold;font-size:120%;">Courses</div>\n};
    foreach my $subjsec ( @subjects ) {

	# Get Course Information
	my $sth = $dbh->prepare("select * from subject where subjsec = ?");
	$sth->execute( $subjsec );
	if ($DBI::errstr) { print $DBI::errstr; die; }
	my $sref = $sth->fetchrow_hashref;
	my %s = %$sref;
	

	print qq{<div>$s{description} ($subjsec)</div>\n};

	%s = latex_filter( %s );
	$sref->{description} = $s{description}; # so filtering is passed to header printing.
	
	
	my @objectives;
	# Now get the objectives and objective count
	for $i (1..20) {
	    my $key = 'q'. $i;
	    if ( $s{$key} ) {
		# Check Length of each objective; truncate if needs be.
		my $objlen = length $s{$key};
		if ( $objlen > 24 ) {
		    my $objnum = $i;
		    print qq{<div style="color:red;font-weight:bold;">};
		    print qq{Course $subject[2] - Objective $objnum too long: $subject[$i]. };
		    print qq{Shortening.</div>\n};
		    $s{$key} = substr $s{$key}, 0, 24;
		}
		push @objectives,$s{$key};
	    } # may truncate len
	}
	

	if ( not @objectives ){ # Has at least a mark field
	    push @objectives, $lex{Mark};
	}
	my $objcount = scalar @objectives;

	@objectives = latex_filter( @objectives );
#	print "Objectives: @objectives<br>\n";
	

	# Get all the kids for this subject-section; get names, sort, print
	$sth = $dbh->prepare("select distinct e.studnum, s.lastname, s.firstname 
			     from eval e, student s
			     where e.studnum = s.studnum and e.subjcode = ? 
			     order by s.lastname, s.firstname");
	$sth->execute( $subjsec );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	my @student;
	while ( my ($studnum, $lastname, $firstname) = $sth->fetchrow ) {
	    push @student, "$studnum:$lastname:$firstname";
	    #$studname{ $studnum } = "$lastname, $firstname";
	}


	# Print the header file...
	print_header(\@objectives, $sref ); # was \@subject );  # print header to tex file.

	my $studcount = @student;
	my $linecount = 0;

	# Loop through and print each student
	my $sth2 = $dbh->prepare("select count(*) from studentwd where studnum = ?");


	foreach my $student ( @student ){

	    my ($studnum,$lastname,$firstname ) = split(':', $student);

	    # Check for withdrawn and add flag.
	    $sth2->execute( $studnum );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $wdflag;
	    if ( ( my $wdcount = $sth2->fetchrow ) > 0 ) {
		$wdflag = "{\\scriptsize ". $lex{WD}. q{\} };
	    }

	    $linecount++;
	    if ( $linecount > $maxlines ) { # We'll print a new page header here
		$linecount = 0;
		print TEX "\\end{tabular}\\\\ \\newpage\n";
		print_header( \@objectives, $sref );
	    }

	    # Get his/her evaluation for this subject in this term
	    #  We will use the global $subjsec and $term
#	    print "SN:$studnum Trm:$arr{term} Subjsec:$subjsec<br>\n";
	    
	    $sth1 = $dbh->prepare("select * from eval where 
             studnum = ? and term = ? and subjcode = ?");
	    $sth1->execute( $studnum, $arr{term}, $subjsec );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    # my @evalrec = $sth1->fetchrow;
	    my $evalref = $sth1->fetchrow_hashref;
	    my %e = %$evalref;

#	    @evalrec = latex_filter( @evalrec );
	    %e = latex_filter( %e );
	    
	    #	    print "REC:"@evalrec<br>\n";
#	    foreach my $key ( sort keys %e ) { print qq{K:$key VAL:$e{$key}<br>\n}; }
	    
	    
	    print TEX "\\raggedright $lastname, $firstname $wdflag& ";

	    for my $val (1..$objcount ) {
		my $key = 'a'. $val;
		print TEX $e{$key};
		
#		$ct = $val + 6;
#		print TEX $evalrec[$ct];

		if ( $val != $objcount ){ print TEX "& "; }
	    }

	    
	    print TEX "\\\\\\hline\n";  


	}  # End of Student Loop 

	print TEX "\\end{tabular}\\newpage\n\n";

    } # End of multiple Subjects loop

    print TEX "\\end{document}\n";
    close TEX;

    print qq{<h1><a href="$webdownloaddir/$shortname.pdf">};
    print qq{$lex{'View/Download'} $lex{Term} $lex{'Mark Report'}</a></h1>\n};

    print qq{[ <a href="$reppage">$lex{'Report Card'}</a> |\n};
    print qq{<a href="$webdownloaddir/pdflog$$.txt">$lex{'View Log File'}</a> ]};
    
    system("$pdflatex $filename >pdflog$$.txt");
    system("mv $shortname.pdf $downloaddir");
    system("mv pdflog$$.txt $downloaddir");
    system("rm -f $shortname.*");

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

} # end of printReport



#---------------
sub print_header {
#---------------

    my $objref = shift;
    my @objectives = @$objref;
    my $subjectref = shift;


    # find longest string in objectives.
    my $len = 0;
    foreach my $obj ( @objectives ) {
	if ( length( $obj ) > $len ){ $len = length($obj);}
    }

    # Get Teacher Name
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth->execute( $subjectref->{teacher} );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname ) = $sth->fetchrow;
    my $teacher = "$lastname, $firstname";


    my $offset = $len * 0.8 + 18; # very rough formula for strut spacing
    $offset = $offset . "mm";

    print TEX "\\begin{tabular}{>{\\raggedright}b{50mm}";
    foreach my $i ( @objectives ){ print TEX "p{$arr{markwidth} mm}";}

    print TEX "}\n ";
    print TEX "\\rule{0pt}{$offset}\n";
    print TEX "{\\bf\\Large $subjectref->{description}}\\\\";
    print TEX "$teacher \\\\";
    print TEX "$lex{Grade}: $subjectref->{grade}\\\\ &";

    my $first = 1;
    foreach my $objective ( @objectives ){
	if ( not $first){ print TEX "&\n";} else { $first = 0; }
	$objective =~ s/\\\\/\\/;
	print TEX "\\hfil\\begin{rotate}{45}{\\small $objective }\\end{rotate}\\hfil";
    }
    print TEX "\\\\ \n\\end{tabular}\n\n";

    # Now print header section WITH dividers
    print TEX "\\begin{tabular}{|p{50mm}|";
    foreach my $i ( @objectives ){ print TEX "p{$arr{markwidth} mm}|"; }
    print TEX "}\\hline\n";


} # end of print_header;




#-----------------
sub selectSubjects {
#-----------------

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

    my $sortorder = "teacher, grade, description";
    if ( $arr{sort} eq 'grade' ){
	$sortorder = "grade, description, teacher";
    } elsif ( $arr{sort} eq 'subject' ){
	$sortorder = "description, grade, teacher";
    }


    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    foreach my $key ( keys %arr ) { # pass values through
	print qq{<input type="hidden" name="$key" value="$arr{$key}">\n};
    }


    if ( $arr{select} eq 'grade' ){ # Display choices by Grade

	# Get all the grades
	my @grades;
	$sth = $dbh->prepare("select distinct grade from subject");
	$sth->execute;
	if ( $DBI::errstr){print $DBI::errstr; die $DBI::errstr; }
	while ( my $grade = $sth->fetchrow ) {
	    push @grades, $grade;
	}
	@grades = sort {$a <=> $b} @grades;
	# print "Grades:@grades<br>\n";
	
	
	print qq{<table border="1" cellpadding ="3" cellspacing="0">\n};
	print qq{<tr><th>$lex{Grade}</th></tr>\n};

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

	# Loop through all grades
	foreach my $grade ( sort {$a <=> $b } @grades ) {
	    print qq{<tr><td class="la"><input type="checkbox" name="$grade" value="1">\n};
	    print qq{$grade</td></tr>\n};
	}

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

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


    } elsif ( $arr{select} eq 'homeroom' ){ # Display choices by Homeroom

	# Get all the homerooms
	my @hrooms;
	$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 @hrooms, $hr;
	}

	print qq{<table border="1" cellpadding ="3" cellspacing="0">\n};
	print qq{<tr><th>$lex{Homeroom}</th></tr>\n};
	print qq{<tr><td><select name="homeroom"><option></option>\n};
	# Loop through all homerooms
	foreach my $hr ( @hrooms ) {
	    print qq{<option>$hr</option>};
	}
	print qq{</td></tr>\n};
	print qq{<tr><td class="cn"><input type="submit" value="$lex{Continue}"></td></tr>\n};
	print qq{</table></form>\n};


    } else { # Display choices by Subject (sorted various ways)


	# select by term overlap and sort by sortorder
	my $sth = $dbh->prepare("select subjsec, description, grade, teacher from subject 
				where startrptperiod <= ? and endrptperiod >= ? 
				order by $sortorder");
	$sth->execute( $arr{term}, $arr{term} );
	if ($DBI::errstr){print $DBI::errstr; die $DBI::errstr; }

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


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

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

	while ( my ( $subjsec, $description, $grade, $teacher ) = $sth->fetchrow ) {

	    # Skip Unwanted Subjects
	    my ($subjcode, $dud) = split(/-/, $subjsec);
	    if ( $r_SupressSubject{$subjsec} or $r_SupressSubject{$subjcode} or 
		 $r_AdditionalComments{$subjsec} or $r_AdditionalComments{$subjcode} ) {
		next; 
	    }

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

	    print qq{<tr><td class="la"><input type="checkbox" name="$subjsec" value="1"> };
	    print qq{<b>$description</b> ($subjsec)</td><td>$grade</td>};
	    print qq{<td>$firstname $lastname</td></tr>\n};

	}

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

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

    }

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

    exit;
}



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

    # Get Terms of enrolled subjects.
    my @terms;
    $sth = $dbh->prepare("select distinct term from eval order by term");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n"; }
    while ( my $term = $sth->fetchrow ) {
	push @terms, $term;
    }


    # Start the Form
    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};

    # Select by
    print qq{<tr><td class="bra">$lex{'Select by'}</td><td class="la">};
    print qq{<select name="select"><option value="subject">$lex{Subject}</option>\n};
    print qq{<option value="grade">$lex{Grade}</option>};
    print qq{<option value="homeroom">$lex{Homeroom}</option>\n};
    print qq{</select></td></tr>\n};

    # Sort by
    print qq{<tr><td class="bra">$lex{'Sort by'}</td><td class="la">};
    print qq{<select name="sort"><option value="subject">$lex{Subject}</option>\n};
    print qq{<option value="grade">$lex{Grade}</option>};
    print qq{<option value="teacher">$lex{Teacher}</option>\n};
    print qq{</select></td></tr>\n};

    # Set Term
    print qq{<tr><td class="bra" style="vertical-align:top;padding-top:0.6em;">};
    print qq{$lex{Term}</td><td class="la">};
    print qq{<select name="term">\n};
    foreach my $trm ( @terms ) {
	print qq{<option>$trm</option>};
    }
    print qq{</select>\n};


    print qq{<table cellpadding="3" cellspacing="0" border="1" style="display:inline;">\n};
    print qq{<tr><th>$lex{Term}</th>};
    foreach my $trk ( sort keys %g_TermDisplay ) {
	print qq{<th>$g_TrackDisplay{$trk}</th>};
    }
    print qq{</tr>\n};

    foreach my $trm ( @terms ) {
	print qq{<tr><td style="background-color:$bgcolor;text-align:center;">$trm</td>};
	foreach my $trk ( sort keys %g_TermDisplay ) {
	    print qq{<td>$g_TermDisplay{$trk}{$trm}</td>};
	}
	print qq{</tr>\n};
    }
    print qq{</table>\n};


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


    # Paper Size
    print qq{<tr><td class="bra">$lex{'Paper Size'}</td><td>};
    print qq{ <select name="papersize"><option value="letter">$lex{Letter}</option>\n};
    print qq{<option value="legal">$lex{Legal}</option><option value="a4">$lex{A4}</option>\n};
    print qq{</select></td></tr>\n};

    # Font size
    print qq{<tr><td class="bra">$lex{'Font Size'}</td><td>\n};
    print qq{<select  name="fontsize">};
    print qq{<option>11</option><option>12</option><option>10</option>\n};
    print qq{</select></td></tr>\n};


    # Students per page
    print qq{<tr><td class="bra">$lex{Students}/$lex{Page}</td><td>};
    print qq{ <input type="text"  name="maxstudent" value="$maxlines" style="width:3ch;"></td></tr>\n};

    # Mark Column 
    print qq{<tr><td class="bra">$lex{Mark} $lex{Width}</td><td>};
    print qq{ <input type="text"  name="markwidth" value="$markwidth" style="width:3ch;"> };
    print qq{mm</td></tr>\n};

    
    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;

}
