#! /usr/bin/perl
#  Copyright 2001-2020 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 $templatepath = '../template/';

my %lex = ('Main' => 'Main',
	   'Student Roster' => 'Student Roster',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Cannot open' => 'Cannot open',
	   'Error' => 'Error',
	   'Homeroom' => 'Homeroom',
	   'Sort by' => 'Sort by',
	   'Continue' => 'Continue',
	   'Grade' => 'Grade',
	   'Select by' => 'Select by',
	   'Font Size' => 'Font Size',
	   'Records per Page' => 'Records per Page',
	   'Name' => 'Name',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Blank=All' => 'Blank=All',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Select' => 'Select',
	   'Mode' => 'Mode',
	   'Missing' => 'Missing',
	   'Template' => 'Template',
	   'Creator' => 'Creator',
	   'Band' => 'Band',

	   );

my $self = 'rptstudrost.pl';

use DBI;
use CGI;
use Cwd;


# Read config variables
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;
my %arr = $q->Vars;
print $q->header( -charset, $charset );

# setup for teacher site, if called from there.
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
    $downloaddir = $tchdownloaddir;
    $webdownloaddir = $tchwebdownloaddir;
}


my $recordsPerPage = 2;
if ( $arr{recordsperpage} ) {
    $recordsPerPage = $arr{recordsperpage}; 
}


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


# Page Header
my $title = "$lex{'Student Roster'} - Print Student Templates";
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
$chartype\n</head><body>\n};

print qq{<div>[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="templatecreator.pl">$lex{Template} $lex{Creator}</a> | };
print qq{<a href="templatecreator.pl?page=3">Delete Templates</a> ]</div>\n};

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

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



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


# Get the report template...
my $templatefile =  $arr{template};


unless ( open ( FH,"<", $templatepath. $templatefile )) {
    print qq{$lex{Error} $lex{Template}: $!\n};
    die qq{$lex{Error} $lex{Template}: $!\n};
}

my $formtext;
my $desc = <FH>;

my $modeline = <FH>;
chomp $modeline; # remove trailing CR/LF.
$modeline =~ s/^\s*//; # strip any leading spaces.
my ($mode, $fmtstart,$fmtend) = split /::/, $modeline;

my $header = <FH>;  # header information for both pdf or html.
$header =~ s/^\s*//; # strip any leading spaces

my $line4 = <FH>; # for future expansion, if required.
my $line5 = <FH>;
# Now load rest of template for layout.
{ local $/; $formtext = <FH>; close FH;}


# Create hash for fieldnames from meta.
my $sth = $dbh->prepare("select fieldid, fieldname, required 
 from meta where tableid = ?");
$sth->execute( 'student' );
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
my %fieldnames;
while ( my ( $fieldid, $fieldname, $required ) = $sth->fetchrow ) {
    if ( $required ) { # has any value
	if ( $mode eq 'html' ) {
	    $fieldname = qq{<span style="font-weight:bold;">$fieldname</span>};
	} else { # pdf format
	    $fieldname = "{\\bf $fieldname}";
	}
    }
    $fieldnames{$fieldid} = $fieldname;
}


# Now put replacement fieldnames back in.
$formtext =~ s{\<\*(.*?)\*\>}
  { exists( $fieldnames{$1} ) 
	? $fieldnames{$1} 
	: $1
  }gsex;


# Replace other non-meta values in formtext.
my %nonmeta;
while ( $formtext =~ m/\<\#(.*)\#\>/g){
    if ( $lex{ $1 } ) { # if we have a translation....
	$nonmeta{$1} =  $lex{$1};
    } else { # no translation.
	$nonmeta{$1} = 'NT:'. $1;
    }
}

# now put them back in...
$formtext =~ s{\<\#(.*?)\#\>}
  { exists( $nonmeta{$1} ) 
	? $nonmeta{$1} 
	: $1
  }gsex;


# Update translation in header.
%lex = ( %lex, %fieldnames ); # join %lex and %fieldnames

#foreach my $key ( keys %lex ) {
#    ( $lex{$key} ) = latex_filter( $lex{$key} );
#}

if ( $header ) {

    $header =~ s{\<\*(.*?)\*\>}
    { exists( $lex{$1} ) 
	? $lex{$1} 
	: $1
	}gsex;
}

# Find all fields , so we only wrap forms around them
# ( faster than doing all fields in the table )
my @fields = ();
while ( $formtext =~ m/\<\@(.*)\@\>/g){
    push @fields, $1;
}

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


# Now select Students
my @students;
my $sort1 = $arr{sortorder1};
my $sort2 = $arr{sortorder2};
my $sorttext = "order by $sort1, $sort2";

my $selecttext;

if ( $arr{groupvalue} ) { # then we have to do something...
    my $group;
    my @groups;
    @groups = split('\s+', $arr{groupvalue});
    if ( $arr{grouptype} eq 'grade' ) {
	$group = 'grade';
    } else {
	$group = 'homeroom';
    }

    $selecttext = 'where ';
    my $first = 1;

    foreach my $grp ( @groups ) {

	$grp = $dbh->quote( $grp );

	if ( not $first ) { # put in OR
	    $selecttext .= ' or '; 
	} else { $first = 0; }

	$selecttext .= $group. ' = '. $grp. ' ';
    }
}

#print qq{Select Text: $selecttext<br>\n};
#print qq{Sort Text: $sorttext<br>\n};


my $sth = $dbh->prepare("select studnum from student $selecttext $sorttext");

$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while ( my $studnum = $sth->fetchrow ) {
    push @students, $studnum;
}


# Now print output based on mode (html or pdf)
if ( $mode eq 'pdf' ) {
    printPDF();

} elsif ( $mode eq 'html' ) {
    printHTML();

} else { # error;
    print qq{$lex{Error}: $lex{Mode} $lex{Missing}\n};
    print qq{</body></html>\n};
    exit;
}




#-----------
sub printPDF {
#-----------

    # Start TEX Section.
    my $shortname = "studrost$$";
    my $filename = "$shortname.tex";

    open(TEX,">$filename") || die $lex{'Cannot open'}. " tex file\n";

    # Set Paper Size, text width and height, fontsize
    my ( $papersize, $textwidth, $textheight );

    if ( $arr{papersize} eq $lex{Letter} ) {
	$papersize = 'letterpaper';
	$textwidth = $g_letterpaper_textwidth;
	$textheight = $g_letterpaper_textheight;
    } elsif ( $arr{papersize} eq $lex{Legal} ) {
	$papersize = 'legalpaper';
	$textwidth = $g_legalpaper_textwidth;
	$textheight = $g_legalpaper_textheight;
    } elsif ( $arr{papersize} eq $lex{A4} ) {
	$papersize = 'a4paper';
	$textwidth = $g_a4paper_textwidth;
	$textheight = $g_a4paper_textheight;
    } 
    # print qq{Papersize: $papersize  TW: $textwidth  TH: $textheight<br>\n};
    # Not required here, perhaps
    # $textheight =~ s/mm//;# $textheight += 16;# $textheight .= 'mm';

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

    print TEX "\\documentclass[ $fontsize, $papersize ]{article}
\\usepackage{newcent,graphicx,array,colortbl,inputenc,multicol}
$a_latex_header
\\renewcommand{\\familydefault}{\\sfdefault}
\\usepackage[pdftex,bookmarks=false,pdfstartview=FitH]{hyperref}
\\setlength{\\textwidth}{ $textwidth }
\\setlength{\\textheight}{ $textheight }
\\setlength{\\hoffset}{-20mm}
\\setlength{\\voffset}{-25mm}
\\setlength{\\topmargin}{0mm}
\\setlength{\\evensidemargin}{0mm}
\\setlength{\\oddsidemargin}{0mm}
\\setlength{\\parindent}{0mm}
\\setlength{\\extrarowheight}{4pt}
\\begin{document}
\\pagestyle{empty}\n";


    print TEX $lex{'Student Roster'}. " - {\\LARGE $schoolname }";
    print TEX " \\hfill $currdate\n\\bigskip\n\n";

    if ( $fmtstart ) {
	print TEX $fmtstart, "\n";
    }

    $header =~ s/\_//g; # filter underscores
    if ( $header ) {
	print TEX $header, "\n";
    }


    my $sth = $dbh->prepare("select * from student where studnum = ?");

    my $counter = 1;

    foreach my $studnum ( @students ) {

	$sth->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
    
	my %rec = %$ref;
	foreach my $key ( keys %rec ) {
	    ( $rec{$key} ) = latex_filter( $rec{$key});
	}
				       
  
	my $text = $formtext; # make a new blank record to plug in...

	# Now put replacement text back in.
	$text =~ s{\<\@(.*?)\@\>}
  	  { $rec{$1} }gsex;

	$text =~ s/\_/ /g; # remove underscores in field names.
	$text =~ s/([^\\])\#/$1\\\#/g; # filter any octothorpes, except those already done.

	print TEX $text,"\n";
 
	if ( not ( $counter % $recordsPerPage)) { 
	    if ( $fmtend ) { print TEX $fmtend, "\n"; }
	    print TEX "\\newpage\n\n"; 
	    if ( $fmtstart ) { print TEX $fmtstart, "\n"; }
	    if ( $header ) { print TEX $header, "\n";}
	} 

	$counter++;

    }  # End of For loop

    if ( $fmtend ) {
	print TEX $fmtend;
    }
    print TEX "\\end{document}";
    close TEX;


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

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

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

    exit;

} # end of printPDF.



#------------
sub printHTML {
#------------


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

    print qq{<h3><span style="font-size:120%;">$desc</span> $currdate</h3>\n};

    if ( $fmtstart ) {
	print $fmtstart, "\n";
    }
    if ( $header ) {
	print $header, "\n";
    }

    my $sth = $dbh->prepare("select * from student where studnum = ?");

    my $counter = 1;

    my ($currfield,$prevfield);
    my $brk = $arr{pagebreak};
    
    foreach my $studnum ( @students ) {

	$sth->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	my %rec = %$ref;

	$prevfield = $currfield;
	$currfield = $rec{$brk};
	if ( $currfield ne $prevfield and $prevfield ) { # pagebreak
	    print qq{</table><table cellpadding="3" cellspacing="0" border="1" };
	    print qq{style="page-break-before:always;">\n};
	}
	

	my $text = $formtext; # make a new blank record to plug in...

	# Now put replacement text back in.
	$text =~ s{\<\@(.*?)\@\>}
  	  { $rec{$1} }gsex;

	print $text,"\n";

    }  # End of record printing loop

    print qq{</table>};
    print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};
    print qq{</body></html>\n};

}


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

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

    # Open the Report Templates
    my @files = glob($templatepath."rptstudrost*.tpl");

    my %desc;
    for my $tplfile ( @files ) {
	# read each label file and get description
	unless ( open (FH,"<$tplfile")) {
	    print qq{$lex{Error} $lex{Template}: $!\n};
	    die "$lex{Error} $lex{Template}: $!\n";
	}

	# read first 2 lines of the template only.
	my $desc = <FH>;
	chomp $desc;
	$desc =~ s/\[//g;  # strip any opening square labels, just in case.

	my $modeline = <FH>;
	$modeline =~ s/^\s*//; # strip any leading spaces
	my ($mode, $fmtstart,$fmtend) = split /::/, $modeline;
	# ignore rest of the file, not required.

	$tplfile =~ s/^.*\///; # strip leading path
	$desc{$tplfile} = "$desc ($mode)";
    }

    # Table of Templates
    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="float:left;border:1px solid gray;margin:1em;padding:0.5em;">\n};
    print qq{<tr><th>$lex{Select} $lex{Template}</th></tr>\n};
    my $passed = $arr{tpl};
    foreach my $key ( sort keys %desc ) {
	if ( $key eq $passed ) { $checked = qq{checked="checked"}; }
	print qq{<tr><td><input type="radio" name="template" value="$key" $checked>};
	print qq{$desc{$key}</td></tr>\n};
    }
    print qq{</table>\n};
    
#    print qq{</td><td><select name="template"><option value="$passed">$desc{$passed}</option>\n};
#    foreach my $key ( sort keys %desc ) {
#	print qq{<option value="$key">$desc{$key}</option>\n};
#    }
#    print qq{</select></td></tr>\n};


    # Create hash for fieldnames from meta.
    my $sth = $dbh->prepare("select fieldid, fieldname
     from meta where tableid = ?");
    $sth->execute( 'student' );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my %fieldnames = ();
    while ( my ( $fieldid, $fieldname ) = $sth->fetchrow ) {
	$fieldnames{$fieldid} = $fieldname;
    }

    # Second table.
    print qq{<table cellpadding="3" cellspacing="3" border="0" };
    print qq{style="float:left;border:1px solid gray;margin:1em;padding:0.5em;">\n};
    print qq{<tr><th colspan="2">Printing Options</th></tr>\n};
    
    # Primary Sort
    print qq{<tr><td class="bra">Primary Sort</td>};
    print qq{<td class="la">};
    print qq{<select name="sortorder1"><option value="lastname">$fieldnames{lastname}</option>\n};
    foreach my $fieldid ( sort keys %fieldnames ) {
	if ( $fieldid eq 'lastname' ) { next; } # skip this one.
	print qq{<option value="$fieldid">$fieldnames{$fieldid}</option>\n};
    }
    print qq{</select></td></tr>\n};

    # Secondary Sort
    print qq{<tr><td class="bra">Secondary Sort</td><td class="la"><select name="sortorder2">};
    print qq{<option value="firstname">$fieldnames{firstname}</option>\n};
    foreach my $fieldid ( sort keys %fieldnames ) {
	# if ( $fieldid eq 'firstname' ) { next; } # skip this one.
	print qq{<option value="$fieldid">$fieldnames{$fieldid}</option>\n};
    }
    print qq{</select></td></tr>\n};

    # Select Students
    print qq{<tr><td class="bra">$lex{'Select by'}</td>\n};
    print qq{<td class="la"><select name="grouptype"><option value="grade">$lex{Grade}</option>\n};
    print qq{<option value="homeroom">$lex{Homeroom}</option></select>\n};
    print qq{<input type="text" name="groupvalue" size="12"> };
    print qq{$lex{'Separate with Spaces'}, $lex{'Blank=All'}</td></tr>\n};

    # Page Break
    print qq{<tr><td class="bra">Page Break on Field</td>\n};
    print qq{<td><select name="pagebreak"><option></option>\n};
    foreach my $fieldid ( sort keys %fieldnames ) {
	print qq{<option value="$fieldid">$fieldnames{$fieldid}</option>\n};
    }
    print qq{</select></td></tr>\n};

    # Rest of Options for PDF
    print qq{<tr><td></td><td class="bla">};
    print qq{The following have no effect on HTML (webpage) reports</td></tr>\n};
    
    print qq{<tr><td class="bra">$lex{'Paper Size'}</td>\n};
    print qq{<td class="la"><select name="papersize">\n};
    print qq{<option>$lex{Letter}</option>\n};
    print qq{<option>$lex{Legal}</option><option>$lex{A4}</option>};
    print qq{</select></td></tr>\n};

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

    print qq{<tr><td class="bra">$lex{'Records per Page'}\n};
    print qq{</td><td><input type="text" size="3" name="recordsperpage" };
    print qq{value="$recordsPerPage"></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;

}

