#! /usr/bin/perl
#  Copyright 2001-2024 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 = ('Marks' => 'Marks',
	   'Main' => 'Main',
	   'Report Card' => 'Report Card',
	   'No Record(s) Found' => 'No Record(s) Found',
	   'Grade' => 'Grade',
	   'Term' => 'Term',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Error' => 'Error',
	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Font Size' => 'Font Size',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'A4' => 'A4',
	   'Legal' => 'Legal',
	   'Term Mark' => 'Term Mark',
	   'Report' => 'Report',
	   'Or' => 'Or',
	   'Homeroom' => 'Homeroom',
	   'Students' => 'Students',
	   'Not Found' => 'Not Found',

	   );

use DBI;
use CGI;

my $self = 'rpt_term_mark_stud.pl';

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

# Set Date
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";


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

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



# Get the values from configuration system
my $sth = $dbh->prepare("select datavalue from conf_system where dataname = ?");
foreach my $val ( qw( r_MarkField r_SupressSubject r_AdditionalComments )) {
    $sth->execute( $val  );
    my $datavalue = $sth->fetchrow;
    eval $datavalue;
    if ( $@ ) {
	print $lex{Error}. " $@<br>\n";
	die $lex{Error}. " $@\n";
    }
}


my $title = "$lex{Student} $lex{'Term Mark'} $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:2em;">\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};
    showReport();
}


#-------------
sub showReport {
#-------------

    my $maxlines;
    if ($arr{maxstudents}) {
	$maxlines=$arr{maxstudents};
    } else {
	$maxlines = 32;
    }

    
    my $grade = $arr{grade};
    my $homeroom = $arr{homeroom};

    my $grouptype = 'grade';
    my $groupvalue = $arr{grade};
    if ( not $arr{grade} ) {
	$grouptype = 'homeroom';
	$groupvalue = $arr{homeroom};
    }
    
    my $term = $arr{term};

    if ( not $groupvalue ) {
	print qq{<h3>$lex{Students} $lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    my $sth = $dbh->prepare("select s.lastname, s.firstname, 
      e.studnum, e.subjcode, e.$r_MarkField from eval e 
      left outer join student s on s.studnum = e.studnum 
      where term = ? and $grouptype = ? 
      order by s.lastname, s.firstname, e.studnum, e.subjcode");
    $sth->execute( $term, $groupvalue );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $rows = $sth->rows;
    if ($rows < 1) { 
	print qq{<h1>$lex{'No Record(s) Found'}  $grouptype};
	print qq{:$groupvalue $lex{Term}:$term</h1>\n};
	print qq{</body></html>\n};
	exit;
    }


    # Now get TEX ready...
    my $shortname = "summarkstud$$";
    my $filename = "$shortname.tex";

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

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


    print TEX "\\documentclass[$fontsize, $papersize]{article}
\\usepackage{array,colortbl,multicol,inputenc}
$a_latex_header
\\renewcommand{\\familydefault}{\\sfdefault}
%\\pagestyle{empty}
\\setlength{\\textwidth}{$textwidth}
\\setlength{\\textheight}{$textheight}
\\setlength{\\hoffset}{-38mm}
\\setlength{\\voffset}{-36mm}
\\addtolength{\\evensidemargin}{0mm}
\\addtolength{\\oddsidemargin}{0mm}
\\setlength{\\tabcolsep}{3.5pt}
\\setlength{\\extrarowheight}{4pt}\n";

    print TEX "\\begin{document}{\\sf\\huge ". ucfirst($grouptype);
    print TEX " $groupvalue $lex{Student} $lex{Marks}}\n\\hfill $lex{Term}";
    print TEX " $term -- $currdate\n\n\\hrulefill\\begin{multicols}{2}\n\\raggedcolumns\n\n";

    my $oldstud = -1;
    my $startflag = 1;

    while ( my @arr = $sth->fetchrow ) {

	@arr = latex_filter(@arr);
	my ( $lastname, $firstname, $studnum, $subjsec, $eval ) = @arr;

	# 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; 
	}


	$oldstud = $curstud;
	$curstud = $studnum;

	if ($oldstud ne $curstud){  # print new student info
	    if (not $startflag) { 
		print TEX "\\end{tabular}\n\\bigskip\n\n"; 
	    } else {
		$startflag = 0;
	    }
	    print TEX "\\begin{tabular}{|p{71mm}|p{12.7mm}|}\\hline\n";
	    print TEX "\\multicolumn{2}{|c|}{\\rule[-2mm]{0mm}{9mm}";
	    print TEX "\\sf\\LARGE $arr[1] $arr[0]}\\\\\\hline\\hline\n";
	}

	# Get the subject name...
	my $sth1 = $dbh->prepare("select description from subject where subjsec = ?"); 
	$sth1->execute($subjsec);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $description = $sth1->fetchrow;

	($description) = latex_filter(($description));

	# Print the Line
	print TEX "$description ($arr[3]) & \\hfil $arr[4]\\hfil\\\\\\hline\n";

    } # End of main loop

    if ( not $startflag ) { print TEX "\\end{tabular}\n\n"; } # no records...

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


    print qq{<h1><a href="$webdownloaddir/$shortname.pdf">};
    print qq{$lex{'View/Download'} $lex{Student} $lex{Marks}</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> ]\n};

    system("$pdflatex $filename >pdflog$$.txt");
    system("mv $shortname.pdf $downloaddir");
    system("mv pdflog$$.txt $downloaddir");
    system("rm -f $shortname.*");

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

    exit;

}



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

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

    # Get Student Grades
    my @grades;
    $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\n"; }
    while ( my $grade = $sth->fetchrow ) {
	push @grades, $grade;
    }


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

    # 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" style="border:1px solid gray;padding:0.5em;">\n};

    # Grade
    print qq{<tr><td class="bra">$lex{Grade}</td><td class="la">};
    print qq{<select name="grade"><option></option>\n};
    foreach my $grade ( sort {$a <=> $b} @grades ) {
	print qq{<option>$grade</option>};
    }
    print qq{\n</select></td></tr>\n};

    # or Homeroom
    print qq{<tr><td class="bra">$lex{Or} $lex{Homeroom}</td><td class="la">};
    print qq{<select name="homeroom"><option></option>\n};
    foreach my $homeroom ( @hrooms ) {
	print qq{<option>$homeroom</option>};
    }
    print qq{\n</select></td></tr>\n};


    # Term
    print qq{<tr><td class="bra">$lex{Term}</td><td class="la">};
    print qq{<select name="term"><option></option>\n};
    foreach my $trm ( sort {$a <=> $b} @terms ) {
	print qq{<option>$trm</option>};
    }
    print qq{\n</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};

    # 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};


    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;

}


