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

#  This file is part of Open Admin for Schools.


use DBI;
use CGI;


my %lex = ( 'View/Download' => 'View/Download',
	    'Demographic Confirmations' => 'Demographic Confirmations',
	    'View Log File' => 'View 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' => 'Lastname',
	    'Firstname' => 'Firstname',
	    'Sort by' => 'Sort by',
	    'Select by' => 'Select by',

	    );

# 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 ($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{'Demographic Confirmations'};
print qq{$doctype\n<html><head><title>$title</title>\n};

print qq{<link rel="stylesheet" href="$css" type="text/css">
$chartype\n</head><body>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};

print qq{<h1>$lex{'Demographic Confirmations'}</h1>\n};

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


my $fontsize = $arr{fontsize}. 'pt';
my ($papersize, $textwidth, $textheight);
if ( $arr{papersize} eq 'letter' ) {
    $papersize = 'letterpaper';
    $textwidth = $g_letterpaper_textwidth;
    $textheight = $g_letterpaper_textheight;

} elsif ( $arr{papersize} eq 'legal' ) {
    $papersize = 'legalpaper';
    $textwidth = $g_legalpaper_textwidth;
    $textheight = $g_legalpaper_textheight;

} elsif ( $arr{papersize} eq 'a4' ) {
    $papersize = 'a4paper';
    $textwidth = $g_a4paper_textwidth;
    $textheight = $g_a4paper_textheight;
}


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

    
my $groupType;
if ( $arr{groupType} eq '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 'name' ) {
    $sortorder = "lastname, firstname";
} elsif ( $arr{sortorder} eq 'grade' ) {
    $sortorder = "grade,lastname, firstname";
} elsif ( $arr{sortorder} eq 'homeroom' ) {
    $sortorder = "homeroom, lastname, firstname";
}


# Read in Template
unless (open (FH,"<../template/democonf.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;
}


# Get Meta values: fieldid and fieldname (possibly translated)
my %meta = ();
my $sth = $dbh->prepare("select fieldid, fieldname from meta
  where tableid = 'student'");
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
while ( my ( $fieldid, $fieldname ) = $sth->fetchrow ) {
    $meta{ $fieldid } = $fieldname;
}


my $shortname = "democonf$$";
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}{-25mm}
\\setlength{\\voffset}{-25mm}
\\setlength{\\topmargin}{5mm}
\\addtolength{\\evensidemargin}{0mm}
\\addtolength{\\oddsidemargin}{0mm}
\\setlength{\\extrarowheight}{2pt}
\\setlength{\\parindent}{0mm}
\\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 * from student 
  $select order by $sortorder");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }


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

    my %rec = %$ref;

    # LaTeX Filter
    foreach my $val ( values %rec ) {
	($val) = latex_filter( $val );
    }

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


}  # 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/Download'} $lex{'Demographic Confirmations'}\n};
print qq{</a></h1>\n<p>[ <a href="$webdownloaddir/pdflog$$.txt">$lex{'View Log File'}</a> |
<a href="$homepage">$lex{Main}</a> ]</p>\n};

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



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

    # Setup the form and start of table.

    print qq{<h3>Report to show to parents at Parent-Teacher Interviews</h3>\n};
    
    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{'Sort by'}</td>\n};
    print qq{<td class="la"><select name="sortorder">\n};
    print qq{<option value="name">$lex{Lastname}, $lex{Firstname}</option>\n};
    print qq{<option value="homeroom">$lex{Homeroom}, $lex{Lastname}, $lex{Firstname}</option>\n};
    print qq{<option value="grade">$lex{Grade}, $lex{Lastname}, $lex{Firstname}</option>\n};
    print qq{</select></td></tr>\n};


    print qq{<tr><td class="bra">$lex{'Select by'}</td>\n};
    print qq{<td class="la"><select name="groupType">\n};
    print qq{<option value="grade">$lex{Grade}</option>\n};
    print qq{<option value="homeroom">$lex{Homeroom}</option></select>\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{'Font Size'}</td><td class="la">\n};
    print qq{<select name="fontsize"><option>12</option>\n};
    print qq{<option>11</option><option>10</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 value="letter">$lex{Letter}</option>\n};
    print qq{<option value="legal">$lex{Legal}</option><option value="a4">$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="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;
}
