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

#  This file is part of Open Admin for Schools.


use DBI;
use CGI;


my %lex = ( 'View' => 'View',
	    'Download' => 'Download',
	    'Log File' => 'Log File',
	    'Main' => 'Main',
	    'Student Confirmation' => 'Student Confirmation',
	    'Cannot open' => 'Cannot open',
	    'Error' => 'Error',
	    'Font Size' => 'Font Size',
	    'Paper Size' => 'Paper Size',
	    'Letter' => 'Letter',
	    'Legal' => 'Legal',
	    'A4' => 'A4',
	    'Use Page Break (if present)' => 'Use Page Break (if present)',
	    'Continue' => 'Continue',
	    'Grade' => 'Grade',
	    'Homeroom' => 'Homeroom',	    
	    'Blank=All' => 'Blank=All',
	    'Group' => 'Group',
	    'Values' => 'Values',
	    'Separate with Spaces' => 'Separate with Spaces',
	    'Lastname, Firstname' => 'Lastname, Firstname',
	    'Homeroom, Lastname, Firstname' => 'Homeroom, Lastname, Firstname',
	    'Grade, Lastname, Firstname' => 'Grade, Lastname, Firstname',
	    'Sort by' => 'Sort by',
	    'Record' => 'Record',
	    'Not Found' => 'Not Found',
	    'Nominal Roll' => 'Nominal Roll',
	    'Records' => 'Records',
	    'Report' => 'Report',

	    );


my $self = 'rptnomrollconf.pl';

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

# Load Latex Filter
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;

my $sort = $arr{sortorder};  # Do we sort by any order but Lastname, firstname?


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 heading.
my $title = "$lex{'Nominal Roll'} $lex{Report}";

print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
$chartype\n</head>\n};

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

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


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

} else {
    delete $arr{page};
}

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

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;
}
 
delete $arr{papersize}; # no longer needed.


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


# Get passed group values
my @values = split /\s/, $arr{groupValue}; # split into array based on spaces
delete $arr{groupValue};
#print qq{Group", @group, "<br>\n};
     
my $groupType;
if ( $arr{groupType} eq $lex{Grade} ) {
    $groupType = 'grade';
} else {
    $groupType = 'homeroom';
}
delete $arr{groupType};

# Select students, sorted by lastname, firstname,
my $select;
if ( @values ) {
    $select = 'where ';
    $first = 1;
    foreach my $value ( @values ) {
	$value = $dbh->quote( $value );
	if ( not $first ) { $select .= ' or '; }
	$select .= "$groupType = $value ";
	$first = 0;
    }
}

if ($select) { print qq{Select: $select<br>\n}; }

my $sortorder = "lastname, firstname";
if ( $arr{sortorder} eq $lex{'Lastname, Firstname'} ) {
    $sortorder = "lastname, firstname";
} elsif ( $arr{sortorder} eq $lex{'Grade, Lastname, Firstname'} ) {
    $sortorder = "grade,lastname, firstname";
} elsif ( $arr{sortorder} eq $lex{'Homeroom, Lastname, Firstname'} ) {
    $sortorder = "homeroom, lastname, firstname";
}




# Read in Template
unless (open (FH,"<../../template/inacconf.tpl")) {
    print $lex{'Cannot open'}. " template - $!\n";
    die $lex{'Cannot open'}. " template - $!\n";
}
my $text;
{ local $/; $text = <FH>; close FH;}

if ( $arr{pagebreak} ) {
    $text =~ s/%\\newpage/\\newpage/g;
}

my %fieldname = ();
my @meta = ();

# Get Meta values: fieldid and arrayidx
$sth = $dbh->prepare("select fieldid, arrayidx, fieldname from meta
		     where tableid = 'student_inac' order by arrayidx");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
while ( my ($fieldid, $arrayidx, $fieldname) = $sth->fetchrow ) {
    $meta[$arrayidx] = $fieldid;
    $fieldname{$fieldid} = $fieldname;
}

# If using newer tablename:fieldname format.... do that here before
# replacement process


# Parse and put in Fieldnames (descriptors)
$text =~ s{\<\*(.*?)\*\>}
       { exists( $fieldname{$1} ) 
	     ? $fieldname{$1} 
	     : $1
       }gsex;

my $shortname = "nomrollconf$$";
my $filename = "$shortname.tex";


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

print TEX "\\documentclass[$fontsize,$papersize,oneside]{article}
\\usepackage{graphicx,array,newcent,colortbl,inputenc}
$a_latex_header
\\renewcommand{\\familydefault}{\\sfdefault}
\\usepackage[bookmarks=false,pdfstartview=FitH]{hyperref}

\\setlength{\\textwidth}{$textwidth}
\\setlength{\\textheight}{$textheight}

\\setlength{\\hoffset}{-1.5in}
\\setlength{\\voffset}{-1in}
\\setlength{\\topmargin}{0.2in}
\\addtolength{\\evensidemargin}{0in}
\\addtolength{\\oddsidemargin}{0in}
\\setlength{\\extrarowheight}{2pt}
\\setlength{\\parindent}{0in}
\\pagestyle{myheadings}";

print TEX "\\markright{$schoolname\\hfill ",
$lex{'Student Confirmation'},"\\hfill $currdate -- Pg }
\\begin{document}\n";

if ( not $select ) { 
    $sortorder = 'grade, lastname, firstname';
} else {
    $sortorder = 'lastname, firstname';
}

$sth = $dbh->prepare("select lastname, firstname, studnum from student 
		     $select order by $sortorder");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

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


while ( my @stud = $sth->fetchrow ) {

    my $studnum = $stud[2];
    @stud = latex_filter( @stud );

    my %rec = ();
    $rec{'student:lastname'} = $stud[0];
    $rec{'student:firstname'} = $stud[1];


    # now load the student_inac data for this student.
    $sth1->execute( $studnum );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my @arr = $sth1->fetchrow;

    if ( not @arr ) {
	#print TEX "\n\\medskip\n";
	# print TEX "INAC $lex{Record} $lex{'Not Found'}: $stud[1] $stud[0] ($stud[0])\\medskip\n\n";
	print qq{<div>INAC $lex{Record} $lex{'Not Found'}: $stud[1] $stud[0] ($stud[0]</div>\n};
	next; 
    }; # no record

    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    @arr = latex_filter( @arr );

    # populate rec hash with rec{fieldid} = fieldvalue
    # @meta holds the fieldid's and @arr holds current record vals.
    for (0..$#arr) {
	$rec{$meta[$_]} = $arr[$_];
    }

    #print qq{</center>\n};
    #print qq{TEXT is:", $text, "<br><br>\n};
    #print qq{REC is: ", %rec, "<br><br>\n};
    #print qq{META: ", @meta, "<br><br>\n};
    #print qq{ARR is: ", @arr, "<br><br>\n};
    #print qq{<center>\n};

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

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

    print TEX $template,"\n";
    print TEX "\n\\medskip\n";


}  # End of Student For loop

print TEX "\\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}/$lex{Download} $lex{'Nominal Roll'} $lex{Records}</a></h1>\n};
print qq{<p style="margin:1em;">[ <a href="$webdownloaddir/pdflog$$.txt">};
print qq{$lex{View} $lex{'Log File'}</a> |};
print qq{<a href="$homepage">$lex{Main}</a> ]</p>\n};
print qq{</body></html>\n};



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

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

    print qq{<tr><td class="bra">$lex{Group}</td><td class="la">\n};
    print qq{<select name="groupType"><option>$lex{Grade}</option>\n};
    print qq{<option>$lex{Homeroom}</option></select>\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="bra">$lex{Values}</td><td class="la">\n};
    print qq{<input type="text" name="groupValue" style="width:15ch;">\n};
    print qq{$lex{'Separate with Spaces'}, $lex{'Blank=All'}</td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Sort by'}\n};
    print qq{</td><td><select name="sortorder"><option>$lex{'Lastname, Firstname'}</option>};
    print qq{<option>$lex{'Homeroom, Lastname, Firstname'}</option>\n};
    print qq{<option>$lex{'Grade, Lastname, Firstname'}</option>\n};
    print qq{</select></td></tr>\n};

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

    print qq{<tr><td class="bra">$lex{'Use Page Break (if present)'}</td>};
    print qq{<td class="la">\n};
    print qq{<input type="checkbox" name="pagebreak" value="1" CHECKED>\n};
    print qq{</td></tr>\n};

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

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

    exit;

}
