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

#  This file is part of Open Admin for Schools.


# Passed Values - via loop: passed subject codes, and options.

# rptstud.pl - report for each student with all of their
# courses. (that this teacher teaches).

# If not passed a subjsec value, fail. Find all of the subjects for
# this teacher. Put these subjects into an array sorted by description.
# Then look up all of the kids and their subjects in
# gbscore/gbtest. We want a join to find studnum, lastname, firstname,
# grade, class where kids in gbscore, linked to gbtest linked to
# subject via subjsec where teacher  = $userid.

my $self = 'rptStudent.pl';

my %lex = ('Main' => 'Main',
	   'Please Log In' => 'Please Log In',
	   'Continue' => 'Continue',
	   'Font Size' => 'Font Size',
	   'Groups Only?' => 'Groups Only?',
	   'Select' => 'Select',
	   'Subjects' => 'Subjects',
	   'New Page for each Student?' => 'New Page for each Student?',
	   'Display Comments?' => 'Display Comments?',
	   'Marks Report' => 'Marks Report',
	   'Gradebook' => 'Gradebook',
	   'View Log File' => 'View Log File',
	   'View/Download' => 'View/Download',
	   'Marks' => 'Marks',
	   'by Student' => 'by Student',
	   'No Name Found' => 'No Name Found',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Absent' => 'Absent',
	   'Late' => 'Late',
	   'minutes' => 'minutes',
	   'Display Complete Attendance?' => 'Display Complete Attendance?',
	   'Display Brief Attendance?' => 'Display Brief Attendance?',
	   'Attendance' => 'Attendance',
	   'Error' => 'Error',
	   
	   );

my $grayscale = '0.90'; # grayness in the report.
my $subjspace = '6cm';

my $specchar = '*';  # causes this test to be skipped in calculating avg.
my $altcolor = '#3B7'; #1B6 Complement to the 063 green of teacher site.

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


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

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

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

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


my $dsn = "DBI:$dbtype:dbname=$dbase";
# leave as global since used in the library...
$dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;

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 = CGI->new;

# Get Session Information...
my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

my $logged_in = $session->param(logged_in);
if ( not $logged_in ){
    print $q->header( -charset, $charset );
    print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};
    print qq{$lex{'Please Log In'}<br>\n}; 
    die;
}

my $userid = $session->param('userid');

print $q->header( -charset, $charset ); 
my %arr = $q->Vars; # Get passed values

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

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

# Go to entry page if first invocation
if ( not $arr{page} ) {
    showStartPage();
}
delete $arr{page}; # flag exists if we get here.


# Name passed variables
my ($newpage, $groupsonly, $fontsize, $showcomment, $papersize);

if ( $arr{newpage} ) {
    $newpage = $arr{newpage};
    delete $arr{newpage};
}
if ( $arr{papersize} ) {
    if ( $arr{papersize} eq $lex{Letter} ) {
	$papersize = 'letterpaper';
    } elsif ( $arr{papersize} eq $lex{Legal} ) {
	$papersize = 'legalpaper';
    } elsif ( $arr{papersize} eq $lex{A4} ) {
	$papersize = 'a4paper';
    }
    delete $arr{papersize};
}
if ( $arr{groupsonly} ) {
    $groupsonly = $arr{groupsonly};
    delete $arr{groupsonly};
}
if ( $arr{fontsize} ) {
    $fontsize = $arr{fontsize};
    delete $arr{fontsize};
}
if ( $arr{showcomment} ) {
    $showcomment = $arr{showcomment};
    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};}

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


# Now loop through all subjects getting the students and put into a hash.
my %subjsecsort; # hash to get subjsec's in alpha order.
foreach my $subjsec ( sort keys %arr ) {

    #print qq{<br><b>Subject: $subjsec ($desc)</b><br>\n};
    my $sth = $dbh->prepare("select distinct gbscore.studnum, 
      studentall.lastname, studentall.firstname from gbtest, gbscore 
      left outer join studentall on studentall.studnum = gbscore.studnum
      where gbscore.testid = gbtest.id and gbtest.subjsec = ?");

    $sth->execute( $subjsec );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}

    while ( my ( $studnum, $lastname, $firstname) = $sth->fetchrow ) {
	#print qq{SN: $studnum $lastname, $firstname<br>\n};
	$student{$studnum} = "$lastname, $firstname:$studnum";
    }
    
    $subjsecsort{"$arr{$subjsec}:$subjsec"} = 1;

}

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

# Get attendance values...
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'");


# loop through names ... dictionary sort version.
foreach $name (sort { ($da = lc $a); ($db = lc $b); $da cmp $db;}
	       values %student){

    my ($name,$studnum) = split ':',$name;
    $name =~ s/^\s//;     $name =~ s/\s$//;
    if ($name eq ','){ $name = $lex{'No Name Found'};}

    print TEX "{\\LARGE $name ($studnum)}\n\n";


    #loop through all subjects for this student.
    foreach my $rec ( sort keys %subjsecsort ) {

	my ($subject, $subjsec) = split ':',$rec;

	# Check if student is in this subj by looking for a score...
	$sth = $dbh->prepare("select id from gbtest where subjsec = ?");
	$sth->execute( $subjsec );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}

	# Loop through all tests looking for a score...
	my $enrolflag;  # Set flag if he/she enrolled in subject.
	while ( my $id = $sth->fetchrow ) {
	    my $sth1 = $dbh->prepare("select count(*) from gbscore
             where testid = ? and studnum = ?");
	    $sth1->execute( $id, $studnum );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}
	    my $count = $sth1->fetchrow;
	    if ($count > 0){ $enrolflag = 1; last; }
	}

	if (not $enrolflag){ next;} # skip this subject

	# Get Attendance Values
	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;}

	}

	if ( $showshortattend ) {
	    print TEX $lex{Absent}. ": $subjcount\\quad ";
	    print TEX $lex{Late}. ": $latecount ";
	    if ( $latesum ) {
		print TEX "($latesum $lex{minutes})";
	    }
	    print TEX "\n\n";
	} 


	# print table of marks (from libgbreport.pl)
	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"; }
		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.
	    }
	}

	print TEX "\\bigskip\n\n";

    } # End of this subject.

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


} # End of this student.

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{Marks} - $lex{'by Student'}</a></h1>\n};

print qq{<p>[ <a href="$tchwebdownloaddir/pdflog$$.txt">$lex{'View Log File'}};
print qq{</a> ]</p></body></html>\n};



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

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

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

    # papersize set in entry form...
    if ( not $papersize ) {
	$papersize = $defaultpapersize; # set in admin.conf
    }

    if ( $papersize eq 'letterpaper' ) {
	$textwidth = '7.4in';
	$textheight = '9in';
    } elsif ( $papersize eq 'legalpaper' ) {
	$textwidth = '7.4in';
	$textheight = '12in';
    } elsif ( $papersize eq 'a4paper' ) {
	$textwidth = '7.2in';
	$textheight = '9in';
    } 


    # 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{\\textwidth}{$textwidth}
\\setlength{\\textheight}{$textheight}

\\setlength{\\hoffset}{-7.6mm}
\\setlength{\\voffset}{-10mm}

\\setlength{\\headsep}{10pt}
\\setlength{\\headheight}{14pt}
\\setlength{\\topmargin}{0in}
\\setlength{\\parindent}{0pt}
\\setlength{\\evensidemargin}{0mm}
\\setlength{\\oddsidemargin}{0mm}
\\setlength{\\extrarowheight}{4pt}
\\pagestyle{headings}
\\newcolumntype{G}{>{\\columncolor[gray]{ $grayscale }}p{$subjspace cm}}
\\markright{$currdate\\hfill $lex{Gradebook} $lex{'Marks Report'} \\hfill Page }

\\begin{document}
EOS1

} # End of startTex


#----------------
sub showStartPage { # Entry Values for Custom Script
#---------------

    # Now find the subjects for this teacher;
    my @subjsec;
    my $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};


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

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

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

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

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

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

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

    print qq{<tr><th colspan="2">$lex{Select} $lex{Subjects}</th></tr>\n};

    foreach my $s ( @subjsec ) {
	my ($sub, $desc) = split(':',$s);
	print qq{<tr><td class="ra">$desc ($sub)</td>\n<td class="cn">};
	print qq{<input type="checkbox" name="$sub" value="$desc" checked></td></tr>\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{</table></form></body></html>\n};

    exit;

}

