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

#  This file is part of Open Admin for Schools.

my $templatepath = "../../template/";

%lex = ('Report' => 'Report',
	'Eoy' => 'Eoy',
	'Main' => 'Main',
	'Staff' => 'Staff',
	'Preregistration' => 'Preregistration',
	'Unable to open template file' => 'Unable to open template file',
	'Download' => 'Download',
	'View Log File' => 'View Log File',
	'View' => 'View',
	'Error' => 'Error',
	'Continue' => 'Continue',
	'Select' => 'Select',
	'Template' => 'Template',
	'Font Size' => 'Font Size',
	'Emergency' => 'Emergency',
	'Certification' => 'Certification',
	'LDAP' => 'LDAP',

	);

use DBI;
use CGI;
#use strict;

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

# Get Lib Latex for filtering
eval require "../../lib/liblatex.pl";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}


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

# Select table report on; staff or prereg_staff;
my ($table, $tableview);
if ( $arr{tbl} ){ # report prereg_staff table
    $table = 'prereg_staff';
    $tableview = qq{<span style="color:red;">$lex{Preregistration}</span> $lex{Staff}};
} else {
    $table = 'staff';
    $tableview = $lex{Staff};
}


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


# Display page header
print qq{$doctype\n<html><head><title>$tableview $lex{Report}</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> | };
print qq{<a href="$eoypage">$lex{Eoy}</a> ]\n};

print qq{<h1>$tableview $lex{Report}</h1>\n};


my @tim = localtime(time);
my $year = $tim[5] + 1900;
my $month = $tim[4] + 1;
my $day = $tim[3];

if (length($month) == 1){ $month = "0".$month;}
if (length($day) == 1){ $day = "0".$day;}

my $currsdate = "$year$month$day"; 
my $currdate = "$month[$month] $day, $year";


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

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


my $templatefile  = $arr{template};

# Get the report template...
unless ( open ( FH,"<", $templatepath. $templatefile )) {
    print qq{$lex{Error} $lex{Template}: $!\n};
    die qq{$lex{Error} $lex{Template}: $!\n};
}
my $formtext;
{ 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( 'staff' );
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

my %meta;
while ( my ( $fieldid, $fieldname, $required ) = $sth->fetchrow ) {
    if ( $required and $mode eq 'html') { # has any value
	$fieldname = qq{<span style="font-weight:bold;">$fieldname</span>};
    }
    $meta{ $fieldid } = $fieldname;
}

# Add in Other Values on Template.
$meta{Emergency} = $lex{Emergency};
$meta{Certification} = $lex{Certification};
$meta{'LDAP'} = $lex{LDAP};


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

#print qq{FORM: $formtext<br>\n};


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


# Open a TeX file 
my $logfile = "pdflog$$.txt";
my $shortname = "staffrpt$$";
my $filename = "$shortname.tex";
open( TEX,">$filename" ) || die "Can't open tex file";

printTeXStart(); # Setup the start of the file.

# Print Heading.
if ( $arr{tbl} ) {
    print TEX qq{$lex{Preregistration} $lex{Staff} $lex{Report}};
} else {
    print TEX qq{$lex{Staff} $lex{Report}};
}


print TEX "\\hfill{\\LARGE $schoolname} ";
print TEX " \\hfill $currdate \n\\smallskip\n\n";


# Find each staff record (staff or prereg_staff)
$sth = $dbh->prepare("select * from $table order by lastname, firstname");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

$sth1 = $dbh->prepare("select field_value from staff_multi 
  where userid = ? and field_name = ? order by field_value");

while ( my $ref = $sth->fetchrow_hashref ) {

    my %rec = %$ref;
    foreach my $key ( keys %rec ) {
	($rec{$key}) = latex_filter( $rec{$key} );
    }

    # Load the Grade, Homeroom and Position values and assemble into
    # $grade, $position, and $homeroom
    foreach my $type ( qw( grade homeroom position )) {
	$sth1->execute( $rec{userid}, $type);
	my $fieldval;
	while ( my $val = $sth1->fetchrow ) {
	    $fieldval .= $val. ' ';
	}
	$rec{$type} = $fieldval;
    }


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

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

    # Temp: escape underscores in field names
    $text =~ s/[^\\]\_/\\_/g;
    print TEX $text,"\n";
}

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


system("$pdflatex $filename > $logfile");
system("mv $shortname.pdf $downloaddir");
system("mv $logfile $downloaddir");
system("rm $shortname.*");
    
print qq{<p style="font-size: 130%; font-weight:bold;">};
print qq{<a href="$webdownloaddir/$shortname.pdf">$lex{View}/$lex{Download}};
print qq{ $tableview $lex{Report}</a></p>\n};

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



#----------------
sub printTeXStart {
#----------------

    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";
    # $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[bookmarks=false,pdfstartview=FitH]{hyperref}
\\setlength{\\textwidth}{ $textwidth }
\\setlength{\\textheight}{ $textheight }
\\setlength{\\hoffset}{-18mm}
\\setlength{\\voffset}{-25mm}
\\setlength{\\headsep}{10pt}
\\setlength{\\headheight}{14pt}
\\setlength{\\parindent}{0pt}
\\setlength{\\tabcolsep}{5pt}
\\setlength{\\topmargin}{0mm}
\\setlength{\\evensidemargin}{0mm}
\\setlength{\\oddsidemargin}{0mm}
\\setlength{\\extrarowheight}{4pt}
\\markright{$schoolname \\hfill $currdate -- Pg}\n\n";

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

   #print TEX $lex{Staff}. q{ }. $lex{Report};
   #print TEX " \\hfill $currdate -- Pg }\n\\begin{document}\n";


} # End of printTeXStart



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

    # print templates
    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="0">\n};

    # Open the Label Templates

    my @files = glob($templatepath."staffrpt*.tpl");
    # my @desc;
    my @sort;
    my %templates; # templates{filename} = $desc;

    for my $tplfile ( @files ) {

	# read each label file and get description
	unless ( open (FH,"<$tplfile")) {
	    print qq{Unable to open label file: $!\n};
	    die "Unable to open label file: $!\n";
	}
	my $desc = <FH>;
	chomp $desc;
	$desc =~ s/\[//g; #strip any opening square labels
	$desc =~ s/^#//;
	$desc =~ s/^%//;
	#my $formatline = <FH>;
	#my ( $format, $barcode, $table ) = split /,/, $formatline;

	$tplfile =~ s/^.*\///;
	# push @desc, $desc. ' ['.$tplfile.']';
	push @sort, $tplfile;
	$templates{$tplfile} = $desc;
	
    }

    my @sort = sort @sort; # sort 'em

    print qq{<tr><td class="bra">$lex{Select} $lex{Template}</td>\n};
    print qq{<td><select name="template">\n};
    foreach my $tplfile ( @sort ) {
	print qq{<option value="$tplfile">$templates{$tplfile} - $tplfile</option>\n};
    }
    print qq{</select></td></tr>\n};

    # May be wanted later...
    #print qq{<tr><td class="ra">$lex{'Sort by'}\n};
    #print qq{</td><td><select name="sortorder"><option>$lex{'Lastname'}</option>\n};
    #print qq{<option>$lex{'Group'}</option>};
    #print qq{</select></td></tr>\n};

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

}
