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

#  This file is part of Open Admin for Schools.


# File: rpttransmon.pl
# Monthly report for Enrollment change.
# PDF Output

my %lex = ('Monthly Transfer Report' => 'Monthly Transfer Report',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Main' => 'Main',
	   'Blank=Previous Month' => 'Blank=Previous Month',
	   'No Enrollment Changes' => 'No Enrollment Changes',
	   'Student' => 'Student',
	   'Reason' => 'Reason',
	   'Principal' => 'Principal',
	   'Grade' => 'Grade',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Month' => 'Month',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Font Size' => 'Font Size',

	   );

# show Principal Signature Line; set to 0 to turn off
my $principalSign = 1;

my $self = 'rpttransmon.pl';


use DBI;
use CGI;

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}. " $@<br>\n";
}

# Used for the category titles
my $shortname = "rpttransfer$$";
my $fileName = "$shortname.tex";

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


# Set Dates
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday,
    $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$year-$mon-$mday";


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



# Print Page Head.
print qq{$doctype\n<html><head><title>$lex{'Monthly Transfer Report'}</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

if ( not $arr{page} ) {
    print qq{<link rel="stylesheet" type="text/css" media="all" };
    print qq{href="/js/calendar-blue.css" title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};
}

print qq{$chartype\n</head><body style="padding:1em 2em;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};

print qq{<h1>$schoolname<br>$lex{'Monthly Transfer Report'}</h1>\n};

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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    showReport();
}


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

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

    print qq{<table cellspacing="0" border="0" cellpadding="3">\n};

    print qq{<tr><td class="bra">$lex{Month}</td><td class="la">\n};
    print qq{<input type="text" name="date" size="12" id="date">\n};
    print qq{<button type="reset" id="start_trigger">...</button> $lex{'Blank=Previous Month'}};
    print qq{</td></tr>\n};

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

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


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

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "date", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "start_trigger", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // show all years in drop-down boxes 
    })};

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

    exit;

}



#--------------
sub showReport {
#--------------

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

    # Date Setup
    my ($yr, $mo, $da);
    if ( not $arr{date} ) { # We'll go back 1 month.
	if ( $mon > 1 ){ # if not January (ie. 1)
	    $mo = $mon - 1;
	    $yr = $year;
	} else {  # month is 1, go to prev dec.
	    $mo = 12;
	    $yr = $year - 1;
	}
	$da = "01";
    } else { # We have been passed a date.
	($yr, $mo, $da) = split /-/, $arr{date};
	$da = "01";
    }

    my $agingdate = "$yr-$mo-$da";

    print qq{<h1>$month[$mo], $year</h>\n};


    open(TEX,">$fileName") || die "Failed tex file open";

    # Set Sizes
    # Letter paper size is 279mm x 216mm
    # 200mm wide - 50mm name, 20mm extra fld, leaves 130mm for columns.
    # a4 paper is 297mm x 210mm; legal is 356mm x 216mm

    my $fontsize = $arr{fontsize}. 'pt';
    my ($papersize, $textwidth, $textheight);
    if ( $arr{papersize} eq $lex{Letter} ) {
	$textwidth = '200mm';
	$textheight = '270mm';
	$papersize = 'letterpaper';
    } elsif ( $arr{papersize} eq $lex{A4} ) {
	$textwidth = '194mm';
	$textheight = '286mm';
	$papersize = 'a4paper';
    } else { # must be legal
	$textwidth = '200mm';
	$textheight = '340mm';
	$papersize = 'legalpaper';
    }
    delete $arr{papersize}; # no longer needed.

    print TEX "\\documentclass[$fontsize,$papersize]{article}
\\usepackage{array,colortbl,helvet,inputenc}
$a_latex_header
\\renewcommand{\\familydefault}{\\sfdefault}
\\pagestyle{empty}
\\setlength{\\textwidth}{$textwidth}
\\setlength{\\textheight}{$textheight}
\\setlength{\\hoffset}{-25mm}
\\setlength{\\voffset}{-25mm}
\\setlength{\\parindent}{0pt}
\\setlength{\\tabcolsep}{5pt}
\\renewcommand{\\familydefault}{\\sfdefault}
\\setlength{\\extrarowheight}{6pt}\n";

    print TEX "\\begin{document}\\begin{center}\n";
    print TEX "{\\LARGE\\sf $schoolname ". $lex{'Monthly Transfer Report'};
    print TEX "}\n\n\\medskip\n{\\Large\\sf  $month[$mo], $yr}\n\n";
    print TEX "\\hrulefill\n\\medskip\n\n";


    # Now select transfer records in month of interest
    my $sth = $dbh->prepare("select studnum, date, type, description, 
     lastname, firstname from transfer
     where month(date) = month(?) and 
     year(date) = year(?) 
     order by type, date desc");
    $sth->execute( $agingdate, $agingdate );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my $rows = $sth->rows;

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

    my $currcat = 0;
    my $lc = 0;

    for ( my $i=1; $i <= $rows; ++$i ) {
	my ($studnum, $date, $type, $description, $lastname, $firstname) = $sth->fetchrow;

	($description, $lastname, $firstname) = latex_filter( $description, $lastname, $firstname );

	$sth1->execute( $studnum );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $grade = $sth1->fetchrow;

	$oldcat = $currcat;
	$currcat = $type;

	if ($currcat ne $oldcat) { # We have a new category; print head/tabular
	    if ($i != 1){  # close up previous tabular
		print TEX  "\\end{tabular}\n\\bigskip\n\n";
	    }
	    my $currcat =~ s/\-//;
	    my $title = $type;

	    print TEX "{\\Large\\sf $title}\n\n \\medskip\n\n";
	    # Row format: Lastname,firstname | Reason  | Date
	    print TEX "\\begin{tabular}{|p{6cm}|p{1.4cm}|p{8cm}|p{2.2cm}|}\n\\hline\n";

	    print TEX "\\rowcolor[gray]{0.90}{\\bf ". $lex{Student}. "} & {\\bf ";
	    print TEX $lex{Grade}. "} & {\\bf ". $lex{Reason}. "} & {\\bf Date}\\\\ \\hline\n";
	    $lc = 0; # reset line counter;
	}

	# Now print the row
	print TEX "{\\bf $lastname}, $firstname & $grade & $description & $date \\\\ \\hline\n";
	$lc++;  #increment line counting.

	if ( $lc % 5 == 0) {
	    print TEX "\\end{tabular}\n";    
	    print TEX "\\begin{tabular}{|p{6cm}|p{1.4cm}|p{8cm}|p{2.2cm}|}\n\\hline\n";
	}

    }

    if ( $rows > 0 ){ # If we have some records...
	print TEX "\\end{tabular} \\\\ \n";
    } else {
	print TEX  $lex{'No Enrollment Changes'}. "\n\n";
    }

    print TEX "\\end{center}\n";

    if ( $principalSign ) {
	print TEX "\n\\bigskip\n\\medskip\n\\underline{\\hspace{3in}}\n\n";
	print TEX "{\\footnotesize ". $lex{Principal}. " }\n\n";
    }

    print TEX "\\end{document}\n";
    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">\n};
    print qq{$lex{'View/Download'} $lex{'Monthly Transfer Report'}</a></h1>\n};
    print qq{[ <a href="$webdownloaddir/pdflog$$.txt">$lex{'View Log File'}</a> |\n};
    print qq{<a href="$homepage">$lex{Main}</a> ]\n};
    print qq{</body></html>\n};

    exit;
}
    
