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

my $self = "rptCourse.pl"; # report for each subject

my %lex = ('Display Comments?' => 'Display Comments?',
	   'New Page for each?' => 'New Page for each?',
	   'Continue' => 'Continue',
	   'Groups Only?' => 'Groups Only?',
	   'by Course' => 'by Course',
	   'Main' => 'Main',
	   'Course' => 'Course',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Font Size' => 'Font Size',
	   'Paper Size' => 'Paper Size',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Student Number' => 'Student Number',
	   'Password' => 'Password',
	   'Marks Report' => 'Marks Report',
	   'Gradebook' => 'Gradebook',
	   'Absent' => 'Absent',
	   'Late' => 'Late',
	   'minutes' => 'minutes',
	   'Display Complete Attendance?' => 'Display Complete Attendance?',
	   'Display Brief Attendance?' => 'Display Brief Attendance?',
	   'Attendance' => 'Attendance',
	   'Select' => 'Select',
	   'Error' => 'Error',
	   'Courses' => 'Courses',

	);

use DBI;
use CGI;
use CGI::Session;

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

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


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

# needed to exclude additional comments subjects; get subject.
eval require "../../etc/repcard.conf";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@<br>\n";
}

my $q = CGI->new;
my %arr = $q->Vars;

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

my $userid = $ENV{'REMOTE_USER'};

print $q->header( -charset, $charset );


my ($sec, $min, $hour, $mday, $mon, $year, $wday, 
 $yday, $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
# Now using global values for month and dow.
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";

# Control setting of newpages;
my $newpage;
if ( $arr{newpage} ){ $newpage = 1; delete $arr{newpage}; }

# Control printing of groups;
my $showgroup;
if ($arr{showgroup}){ $showgroup = 1; delete $arr{showgroup};}

my $groupsonly;
if ($arr{groupsonly}){ 
    $groupsonly = 1; 
    $showgroup = 1; # override in case groups not selected.
    delete $arr{showgroup};
}

# Control printing of comments;
my $showcomment;
if ($arr{showcomment}){ $showcomment = 1; delete $arr{showcomment};}

# Control printing of attendance;
my $showshortattend;
if ( $arr{showshortattend} ){ $showshortattend = 1; delete $arr{showshortattend};}
my $showlongattend;
if ( $arr{showlongattend} ){ $showlongattend = 1; delete $arr{showlongattend};}

# Now all passed values but subjects (subjsec) are deleted.. 


# print page header
my $title = "$lex{'Marks Report'} - $lex{'by Course'}";
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$tchcss" type="text/css">\n};
print qq{</head><body style="padding:1em 2em;">\n};

print qq{[ <a href="$tchpage">$lex{Main}</a> |\n};
print qq{<a href="gbmain.pl">$lex{Gradebook}</a> | <a href="rptMenu.pl">Report Menu</a> ]\n};
print qq{<h1>$title</h1>\n};


# Select subjects to print.
if ( not $arr{page} ) { 
    showStartPage();
}
delete $arr{page};
delete $arr{subjsec};

my $fontsize = $arr{fontsize};
delete $arr{fontsize};
my $papersize = $arr{papersize};
delete $arr{papersize};

startTex(); # Setup the Tex file for writing.

# loop through each subject
foreach my $subj (keys %arr){
    my ($subjsec,$desc) = split(':',$subj);

    # Find kids in this subject.
    $sth = $dbh->prepare("select distinct e.studnum from eval e, studentall s
			 where e.subjcode = ? and s.studnum = e.studnum
			 order by s.lastname, s.firstname");
    $sth->execute( $subjsec );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

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

    my $sth2 = $dbh->prepare("select count(*) from attend where studentid = ? and subjsec = ? 
			     and reason = '$absentUnexcused'");
    my $sth3 = $dbh->prepare("select count(late), sum(late) from attend 
			     where studentid = ? and subjsec = ? and reason = '$lateUnexcused'");

    while ( my $studnum = $sth->fetchrow ){  # loop through kids

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

	my ($subjcount, $latecount, $latesum);
	if ( $showshortattend or $showlongattend ) {

	    # Get attendance
	    $sth2->execute( $studnum, $subjsec );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}
	    $subjcount = $sth2->fetchrow;

	    # Get Late
	    $sth3->execute( $studnum, $subjsec );
	    ($latecount,$latesum) = $sth3->fetchrow;
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}

	}

	print TEX "{\\LARGE $firstname $lastname}\\qquad\n";

	# Put Short Attendance Here, if selected.
	if ( $showshortattend ) {
	    print TEX $lex{Absent}. ": $subjcount\\quad ";
	    print TEX $lex{Late}. ": $latecount ";
	    if ( $latesum ) {
		print TEX "($latesum $lex{minutes})";
	    }
	    print TEX "\n\n";

	} else {
	    print TEX "\n";
	}


	# print table of marks
        prStudentSubject($studnum, $subjsec, $groupsonly, $showcomment);

	# put full attendance here, if selected.
	if ( $showlongattend ) {

	    my $sth = $dbh->prepare("select absdate, reason, late from attend 
				    where studentid = ? and subjsec = ?");
	    $sth->execute( $studnum, $subjsec );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    my $first = 1;
	    my $count = 1;

	    while ( my ($absdate, $reason, $late) = $sth->fetchrow ) {
		
		if ( $first ) {
		    print TEX "\\medskip\n";
		    print TEX "\\begin{tabular}{|p{6.35cm}|p{6.35cm}|} \\hline\n";
		    print TEX "\\rowcolor[gray]{0.90}\\Large $lex{Attendance} & \\\\ \\hline\n";
		    $first = 0;
		}
		
		print TEX "$absdate - $reason ";
		if ( $late ) { print TEX "- $late"; }
		#print TEX "\n\n";
		if ( $count % 2 ) { print TEX ' & '; } else { print TEX "\\\\ \\hline\n"; }
		$count++;
	    }
	    if ( not $first ) {
		if ( not ($count % 2) ) { print TEX "\\\\ \\hline\n"; }
		print TEX "\\end{tabular}\n"; # closing brace ends parbox.
	    }
	}

	if ( $newpage ){ 
	    print TEX "\\newpage\n\n";
	} else {
	    print TEX "\\bigskip\n\n";
	}
    }

    # finish subject with newpage...
    if (not $newpage){ print TEX "\\newpage\n\n";} 

} # End of this subject.

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

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

print qq{<h1><a href="$tchwebdownloaddir/$shortname.pdf">};
print qq{$lex{'View/Download'} $lex{'Course'} $lex{'Marks Report'}</a></h1>};
print qq{ <p>[ <a href="$tchwebdownloaddir/pdflog$$.txt">$lex{'View Log File'}</a> ]</p>\n};

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


#-----------
sub startTex {
#-----------

    # Set paper size; default to letter.
    if ($papersize eq $lex{Legal}) {
	$papersize = 'legalpaper';
    } elsif ($papersize eq $lex{A4}) {
	$papersize = 'a4paper';
    } else {
	$papersize = 'letterpaper'; 
    }

    $fontsize = $fontsize . 'pt';

    $subjspace = '6cm';

    $shortname = "subjrpt$$";
    $filename = "$shortname.tex";

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

    # Preamble and Head of Document
    print TEX <<"EOS1";  
\\documentclass[ $fontsize, $papersize, oneside]{article}
\\usepackage{array,graphicx,multicol,colortbl,tabularx,inputenc}
$a_latex_header
\\renewcommand{\\familydefault}{\\sfdefault}
\\setlength{\\hoffset}{-7.6mm}
\\setlength{\\voffset}{-10.2mm}
\\setlength{\\headsep}{10pt}
\\setlength{\\headheight}{14pt}
\\setlength{\\topmargin}{0mm}
\\setlength{\\textwidth}{182.9mm}
\\setlength{\\textheight}{228.6mm}
\\setlength{\\parindent}{0pt}
\\setlength{\\evensidemargin}{0in}
\\setlength{\\oddsidemargin}{0in}
\\setlength{\\extrarowheight}{4pt}
\\pagestyle{headings}
\\newcolumntype{G}{>{\\columncolor[gray]{0.85}}p{$subjspace cm}}
\\markright{$currdate\\hfill $lex{Course} $lex{'Marks Report'} \\hfill Page }

\\begin{document}
EOS1

} # End of startTex


#----------------
sub showStartPage { # Select subjects to print for this teacher
#----------------

    # Note: assume that userid and subjsec is already loaded from Session.

    my @subjsec;

    # Now find the subjects and store the subjsec, desc for them 
    $sth = $dbh->prepare("select subjsec, description from subject
     where teacher = ? and description != '$additionalcomments'
     order by description");
    $sth->execute( $userid );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}
    while (my ($subjsec,$desc) = $sth->fetchrow){
	$desc =~ s/://g;
	push @subjsec, "$subjsec:$desc";
    }
    

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

    print qq{<tr style="background-color:#BBB;"><td colspan="2" class="cn">\n};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};

    print qq{<tr style="background-color:#DDD;"><td class="ra">};
    print qq{$lex{'Font Size'}</td><td><select name="fontsize"><option>11</option><option>10</option>};
    print qq{<option>12</option></select>pt</td></tr>\n};

    print qq{<tr style="background-color:#DDD;"><td class="ra">};
    print qq{$lex{'Paper Size'}</td><td><select name="papersize"><option>$lex{Letter}</option>\n};
    print qq{</option><option>$lex{Legal}</option><option>$lex{A4}</option></select>\n};
    print qq{</td></tr>\n};

    print qq{<tr style="background-color:#DDD;"><td class="ra">};
    print qq{$lex{'Groups Only?'}</td>};
    print qq{<td class="cn"><input type="checkbox" name="groupsonly" value="1">\n};
    print qq{</td></tr>\n};

    print qq{<tr style="background-color:#DDD;"><td class="ra">};
    print qq{$lex{'New Page for each?'}</td>};
    print qq{<td class="cn"><input type="checkbox" name="newpage" value="1">\n};
    print qq{</td></tr>\n};

    print qq{<tr style="background-color:#DDD;">};
    print qq{<td class="ra">$lex{'Display Comments?'}</td>};
    print qq{<td class="cn"><input type="checkbox" name="showcomment" value="1">};
    print qq{</td></tr>\n};

    print qq{<tr style="background-color:#DDD;">};
    print qq{<td class="ra">$lex{'Display Brief Attendance?'}</td>};
    print qq{<td class="cn"><input type="checkbox" name="showshortattend" value="1">};
    print qq{</td></tr>\n};

    print qq{<tr style="background-color:#DDD;">};
    print qq{<td class="ra">$lex{'Display Complete Attendance?'}</td>};
    print qq{<td class="cn"><input type="checkbox" name="showlongattend" value="1">};
    print qq{</td></tr>\n};

    print qq{<tr><th colspan="2">$lex{Select} $lex{Courses}</th></tr>\n};
    foreach my $subj ( @subjsec ){
	my ($subjsec, $desc) = split(':',$subj);
	print qq{<tr><td class="ra">$desc ($subjsec)</td>\n};
	print qq{<td class="cn"><input type="checkbox" };
	print qq{name="$subj" value="1"></td></tr>\n};
    }

    print qq{<tr style="background-color:#BBB;"><td colspan="2" class="cn">};
    print qq{<input type="submit" value="$lex{Continue}">};
    print qq{</td></tr>\n};

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

    exit;

} # End of showStartPage

