#! /usr/bin/perl
#  Copyright 2001-2021 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 = ('Main' => 'Main',
	   'No Staff Found' => 'No Staff Found',
	   'View/Download' => 'View/Download',
	   'Custom Staff List' => 'Custom Staff List',
	   'Main' => 'Main',
	   'View Log File' => 'View Log File',
	   'Continue' => 'Continue',
	   'Grade' => 'Grade',
	   'Cell Width' => 'Cell Width',
	   'Max Staff/Page' => 'Max Staff/Page',
	   'Repeat Col Headings' => 'Repeat Col Headings',
	   'Staff List' => 'Staff List',
	   'Grade' => 'Grade',
	   'Rm' => 'Rm',
	   'Select Staff Positions' => 'Select Staff Positions',
	   'Select Sort Order' => 'Select Sort Order',
	   'Position' => 'Position',
	   'Name' => 'Name',
	   'Column Heading' => 'Column Heading',
	   'Other Settings' => 'Other Settings',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'A4' => 'A4',
	   'Legal' => 'Legal',
	   'No Positions Selected' => 'No Positions Selected',
	   'Error' => 'Error',

	   );

my $self = 'rptcustomstafflist.pl';

use DBI;
use CGI;

# Configurable settings
my $maxstaff = 28; # maximum staff per page.
my $maxstaffpositions = 20; # max type of staff types in admin.conf;
my $width = 8;  # default width of columns, 8mm;

my $entrylimit = 15; # Max entries allowed for rotated text.
my $maxentrysize = 14; # Maximum number of characters for the entry

my $namewidth = 50; # Width of the first 'Name' column in mm.
my $extracolwidth = 10; # Width of the second column in mm. Done in
# in case I need this for another field later...

# No longer used: my $margins = 26; # leave 0.5in (13mm) for each side margin.

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


# Date set after pulling in month and dow array.
my ($sec, $min, $hour, $mday, $mon, $year, $wday, 
 $yday, $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$s_dow[$wday], $s_month[$mon] $mday, $year";


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


my $title = $lex{'Custom Staff List'};
print qq{<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
$chartype\n</head>\n};

print qq{<body style="padding:1em 2em;">\n};

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


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

# Filter for Passed values that might crash LaTeX 
foreach $key (sort keys %arr){
    #print "K:$key V:$arr{$key}<br>\n";
    ( $arr{$key} ) = latex_filter( $arr{$key} );
}

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


my $wi = $arr{width} - 1; # width of each col desired (in mm)
# take away 1 for 1mm tabcolsep.

# Get width for papersize
# Letter paper size is 279mm x 216mm
# Legal is 356mm x 216mm; a4 is 297 x 210 (skinny and longer)

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

my $paperwidth;
if ( $textwidth =~ m/(\d+)/ ) { $paperwidth = $1; }

my $totalcolwidth = $paperwidth - $namewidth - $extracolwidth; # no longer: - $margins;
my $colcount = $totalcolwidth / ($arr{width} + 1);
$colcount = int $colcount; # truncate
#print "Column Count: $colcount Total: $totalcolwidth \n";


# push entry text into array.
for ( 1..$entrylimit ){
    my $entryname = 'entry'.$_;
    if ($arr{$entryname}){ # if it exists...push into array
	push @entry,$arr{$entryname};
    }
}
my $entrysize = $#entry + 1;
#print "Entry size: $entrysize\n";

if ( $arr{repeat} and $entrysize ){
    $repeatcount = $colcount / $entrysize;
    $repeatcount = int $repeatcount;
} elsif ($entrysize){
    $repeatcount = 1; # only do it once if not repeat.
} else { $repeatcount = 0;}


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


# Select the staff to include...
my $select = qq{where s.userid = sm.userid and field_name = 'position' and (};
my $first = 1;
foreach my $idx ( 1 .. $maxstaffpositions ) {  # max different types of staff positions
    my $field = 'position'. $idx;
    if ( $arr{$field} ) {
	$arr{$field} = $dbh->quote( $arr{$field} );

	if ( not $first ) { # append an 'or' 
	    $select .= ' or ';
	} else { 
	    $first = 0; 
	}

	$select .= " field_value = $arr{$field} ";
    }
}

$select .= ')';
# print "Select: $select<br>\n";


if ( $first ) { # nothing checked
    print qq{<h1>$lex{'No Positions Selected'}</h1>\n};
    print qq{</body></html>\n};
    exit;
}


my $sortorder;
if ( $arr{sortorder} eq 'posname' ) {
    $sortorder = 'field_value, lastname, firstname';
} else {
    $sortorder = 'lastname, firstname';
}


$sth = $dbh->prepare("select distinct s.userid from staff s, staff_multi sm $select 
  order by $sortorder ");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
$rows = $sth->rows;


if ( $rows < 1 ){ # No staff found...
    print qq{<h1>$lex{'No Staff Found'}!</h1>\n};
    print qq{</body></html>\n};
    system("rm -f $shortname.*"); #cleanup
    exit;
}

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

print TEX "\\documentclass[12pt,$papersize]{article}
\\usepackage{array,newcent,rotating,colortbl,inputenc}
$a_latex_header
\\pagestyle{empty}
\\setlength{\\textwidth}{$textwidth}
\\setlength{\\textheight}{$textheight}
\\setlength{\\hoffset}{-36mm}
\\setlength{\\voffset}{-36mm}
\\addtolength{\\evensidemargin}{0mm}
\\addtolength{\\oddsidemargin}{0mm}
\\setlength{\\tabcolsep}{1mm}
\\setlength{\\extrarowheight}{2mm}
\\renewcommand{\\familydefault}{\\sfdefault}
\\newcolumntype{G}{>{\\columncolor[gray]{1.00}}p{$namewidth mm}}\n";
# Note above... a columncolor of 1.00 means white, smaller number is darker.

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

prHeader(); # do the first header.
while ( my $userid = $sth->fetchrow ) {
#    print qq{Userid:$userid<br>\n};
    $linecount++;
    if ($linecount > $maxlines) { # We'll print a new page header here
	# New Page Header
	$linecount = 0;
	print TEX "\\end{tabular}\\\\ \\newpage\n";
	prHeader();
    }
    prRecord( $userid );

}  # End of Loop for all staff

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


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

print qq{<h1><a href="$webdownloaddir/$shortname.pdf">};
print qq{$lex{'View/Download'} $lex{'Custom Staff List'}</a></h1>\n};
print qq{<p>[ <a href="$homepage">Main</a> |\n <a href="$webdownloaddir/pdflog$$.txt">};
print qq{$lex{'View Log File'}</a>\n ]</p>\n};
print qq{</body></html>\n};



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

    # Get default papersize
    my $papersize = $defaultpapersize;
    $papersize =~ s/paper//; # strip off the 'paper' ending;
    $papersize = ucfirst( $papersize );


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

    # Outermost Table
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr valign="top"><td>\n};

    # First Cell as Table
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr><td class="bla">$lex{'Select Staff Positions'}</td></tr>\n};

    # Find the distinct positions in the staff table
    $sth = $dbh->prepare("select distinct field_value from staff_multi
     where field_name = 'position' order by field_value");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my $poscount;

    while ( my $position = $sth->fetchrow ) {
	$poscount++;
	print qq{<tr><td class="la">};
	print qq{<input type="checkbox" name="position$poscount" value="$position">};
	print qq{ $position</td></tr>\n};
    }
    print qq{</table><p></p>\n};


    # Start New Table for Sort Order Selection: Second Table as cell
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr><td class="bla">$lex{'Select Sort Order'}</td></tr>\n};

    print qq{<tr><td class="la">};
    print qq{<input type="radio" name="sortorder" value="name" checked>};
    print qq{$lex{Name}</td></tr>\n};

    print qq{<tr><td class="la"><input type="radio" name="sortorder" value="posname">};
    print qq{$lex{Position}, $lex{Name}</td></tr>\n};

# Not Used.
#    print qq{<tr><td class="la"><input type="radio" name="sortorder" value="posgrade">};
#    print $lex{Position}. ',' . $lex{Grade}. "</td></tr>\n};

    print qq{<tr><td class="la">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table>\n};

    print qq{</td><td valign="top">\n}; # table #3

    # Now Set Width and Column Headings,
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr><td></td><td><b>$lex{'Other Settings'}</b></td></tr>\n};
    print qq{<tr><td class="ra">$lex{'Cell Width'}</td>\n<td class="la">};
    print qq{<input type="text" name="width" size="2" value="$width"> mm</td></tr>\n};

    print qq{<tr><td class="ra">$lex{'Paper Size'}</td>\n<td class="la">};
    print qq{<select name="papersize">};
    if ( $papersize ) { print qq{<option>$papersize</option>\n}; }
    print qq{<option>$lex{Letter}</option>};
    print qq{<option>$lex{A4}</option>};
    print qq{<option>$lex{Legal}</option>};
    print qq{</select></td></tr>\n};
        

    print qq{<tr><td class="ra">$lex{'Max Staff/Page'}</td>\n<td class="la">};
    print qq{<input type="text" name="maxstaff" size="3" value="$maxstaff">};


    print qq{</td></tr>\n<tr><td class="ra">$lex{'Repeat Col Headings'}};
    print qq{?</td>\n<td  class="la"><input type="checkbox" name="repeat"></td></tr>\n};

    for my $id ( 1..$entrylimit ) {
	my $entrytxt = "entry$id";
	print qq{<tr><td class="ra">$lex{'Column Heading'} $id</td>\n};
	print qq{<td  class="la"><input type="text" name="$entrytxt" }; 
	print qq{size="$maxentrysize" maxlength="$maxentrysize"></td></tr>\n};
    }

    print qq{<tr><td></td><td class="la">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table>\n};

    print qq{</td></tr></table>\n}; # end of outer table.
    print qq{</form></body></html>\n};

    exit;
}


#-----------
sub prHeader {
#-----------

    # Done at the start of a new page.
    print TEX "\\begin{tabular}{G|p{$extracolwidth mm}|";
    for (1..$colcount){	print TEX "p{$wi mm}|"; }
    print TEX "}\n";

    print TEX "\\raggedright\\bf $schoolname ". $lex{'Staff List'};
    for (1..$colcount + 1){ print TEX "& ";}
    print TEX "\\\\ \n";

    print TEX "\\small\\raggedright $currdate\n\\bigskip ";

    for (1..$colcount + 1){ print TEX "& ";}

    print TEX "\\\\ \n";

    if ($arr{group} eq $lex{Grade} ){
	print TEX "\\Large\\raggedright ". $lex{Grade}. " $curroom & ";
    } else {
	#print TEX "\\bf\\raggedright $teachername ";
	#print TEX $lex{Rm}. " $curroom & ";
	print TEX ' & ';
    }

    my $remainder = $colcount - ( $repeatcount * $entrysize );

    if ( $repeatcount ) {
	for (1..$repeatcount){ # times to loop to print rotated text.
	    foreach my $txt ( @entry ) {
		print TEX "&\\hfil\\rule{6pt}{0pt}\\begin{rotate}{90}$txt";
		print TEX "\\end{rotate}\\hfil";
	    }
	}
    }
    for (1..$remainder){ print TEX "& ";}
    print TEX "\\\\ \\hline\n";

} # End of prHeader


#-----------
sub prRecord { # print normal record (ie. line)
#-----------

    my $userid = shift;
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth->execute( $userid );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my ( $lastname, $firstname ) = $sth->fetchrow;

    if ($alternatingcolor == 0){
	print TEX "\\rowcolor[gray]{0.93}";
	$alternatingcolor = 1;
    } else { $alternatingcolor = 0;}

    print TEX "\\raggedright {\\bf $lastname}, $firstname";

    print TEX " & ";

    for (1..$colcount){ print TEX "& ";}
    print TEX "\\\\\\hline\n";
}
