#!/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 = ('Medical' => 'Medical',
	   'Report' => 'Report',
	   'Select' => 'Select',
	   'Main' => 'Main',
	   'Error' => 'Error',
	   'Category' => 'Category',
	   'Continue' => 'Continue',
	   'Font Size' => 'Font Size',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Type' => 'Type',
	   'PDF' => 'PDF',
	   'HTML' => 'HTML',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Page' => 'Page',
	   'Add' => 'Add',
	   'Page Break' => 'Page Break',
	   'Student' => 'Student',
	   'Cannot open' => 'Cannot open',

	   );

my $self = 'rptmedcategory.pl';


use DBI;
use CGI;
use Number::Format qw(:all);

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

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


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


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


my $title = qq{$lex{Medical} $lex{Report} - $lex{Category}};
print qq{$doctype\n<html><head><title>$title</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> ]\n};

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


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

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




#--------------
sub printReport {
#--------------

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

    my $pagebreak = $arr{pagebreak};
    delete $arr{pagebreak};

    my $sth = $dbh->prepare("select s.studnum, s.lastname, s.firstname, s.grade, s.homeroom 
			    from student as s,
			    student_medical as sm  where s.studnum = sm.studnum and sm.category = ? 
			    order by s.lastname, s.firstname");


    my $sth1 = $dbh->prepare("select category, description from student_medical where studnum = ?");


    if ( $arr{type} eq 'html' ) { # html generation.
	delete $arr{type};

	# Not needed here.
	delete $arr{fontsize};
	delete $arr{papersize};

       
	# Loop through all categories
	foreach my $cat ( sort keys %arr ) {

	    # Start the Table
	    print qq{<table cellspacing="0" cellpadding="3" border="1">\n};
	    print qq{<caption style="font-size:150%;font-weight:bold;line-height:150%;};
	    print qq{letter-spacing:2px;">$cat</caption>\n};

	    # Get the Students with this cat.
	    $sth->execute( $cat );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	    my $count = 0;
	    my $first = 1;
	    while ( my ( $studnum, $lastname, $firstname, $grade, $homeroom ) = $sth->fetchrow ) {
		if ( $count % 4 == 0 ) {
		    if ( $count ) { print qq{</tr>\n}; }
		    print qq{<tr>};
		}
		print qq{<td><b>$lastname</b>, $firstname ($studnum) $homeroom/$grade</td>\n};
		$count++;
	    }

	    if ( $count > 4 ) {
		my $fill = 4 - ($count % 4);
		if ( $fill == 4 ) { $fill = 0; }
		foreach ( 1 .. $fill ) { print qq{<td></td>}; }
	    }
	    print qq{</tr></table><p>&nbsp;</p>\n};

	}

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


    } else { # pdf generation

	delete $arr{type};

	# Start TEX Section.
	my $shortname = "rptmedcat$$";
	my $filename = "$shortname.tex";

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

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


	print TEX "\\documentclass[ $fontsize, $papersize ]{article}
\\usepackage{newcent,graphicx,array,colortbl,inputenc,multicol,fancyhdr}
$a_latex_header
\\renewcommand{\\familydefault}{\\sfdefault}
\\usepackage[pdftex,bookmarks=false,pdfstartview=FitH]{hyperref}
\\setlength{\\textwidth}{ $textwidth }
\\setlength{\\textheight}{ $textheight }
\\setlength{\\hoffset}{-16mm}
\\setlength{\\voffset}{-20mm}
\\setlength{\\topmargin}{0mm}
\\setlength{\\evensidemargin}{0mm}
\\setlength{\\oddsidemargin}{0mm}
\\setlength{\\parindent}{0mm}
\\setlength{\\extrarowheight}{4pt}
\\setlength{\\headsep}{4pt}
\\begin{document}
\\pagestyle{fancy}
\\lhead{$schoolname -- $schoolyear}
\\rfoot{$lex{Page} \\thepage}
\\cfoot{ }
\\thispagestyle{empty}\n";


	print TEX "{\\LARGE $lex{Student} $lex{Medical} $lex{Report}}";
	print TEX " \\hfill $currdate\n\\bigskip\n\n";



	# Loop through all categories
	foreach my $cat ( sort keys %arr ) {

	    # Start the Table
	    print TEX "\\begin{tabular}{|p{45mm}|p{45mm}|p{45mm}|p{45mm}|}\\hline\n";
	    print TEX "\\multicolumn{4}{|c|}{\\cellcolor[gray]{0.92}";
	    print TEX "\\rule[-4pt]{0pt}{20pt}\\LARGE $cat} \\\\ \\hline\n";


	    # Get the Students with this cat.
	    $sth->execute( $cat );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	    my $count = 0;
	    my $first = 1;
	    while ( my ( $studnum, $lastname, $firstname, $grade, $homeroom ) = $sth->fetchrow ) {
		if ( $count % 4 == 0 ) { # End the row
		    if ( $count ) { print TEX "\\\\ \\hline\n"; }
		    if ( $count % 20 == 0 and $count ) { # End the table
			print TEX "\\end{tabular}\n\n";
			print TEX "\\begin{tabular}{|p{45mm}|p{45mm}|p{45mm}|p{45mm}|}\\hline\n";
		    }

		} else { # print the divider
		    print TEX ' & ';
		}
		print TEX "{\\bf $lastname}, $firstname ($studnum) $homeroom/$grade";
		$count++;
	    }

	    my $fill = 4 - ($count % 4);
	    if ( $fill == 4 ) { $fill = 0; }
	    foreach ( 1 .. $fill ) { print TEX '& '; }
	    
	    print TEX "\\\\\\hline\n\\end{tabular}\n\n";
	    if ( $pagebreak ) {
		print TEX "\\newpage\n\n";
	    } else {
		print TEX "\\bigskip\n";
	    }

	}


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


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

	print qq{<h1><a href="$webdownloaddir/$shortname.pdf">};
	print qq{$lex{'View/Download'} $lex{Medical} $lex{Report}</a></h1>\n};

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

    } # end of pdf report

    exit;
}



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

    # Get the Categories
    my @category;
    my $sth = $dbh->prepare("select distinct category from student_medical 
     where category is not NULL and category != ''
     order by category");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $cat = $sth->fetchrow ) {
	push @category, $cat;
    }

    # Get the Grdaes
    my @grades;
    $sth = $dbh->prepare("select distinct grade from student
     where grade is not NULL and grade != ''
     order by grade");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $val = $sth->fetchrow ) {
	push @grades, $val;
    }

    # Get the Homerooms
    my @homerooms;
    $sth = $dbh->prepare("select distinct homeroom from student
     where homeroom is not NULL and homeroom != ''
     order by homeroom");
    $sth->execute;
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $val = $sth->fetchrow ) {
	push @homerooms, $val;
    }

    # Start Form
    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};
    print qq{<tr><th colspan="2" class="cn">$lex{Select} $lex{Category}</th></tr>\n};

    # Loop through all categories
    foreach my $cat ( @category ) {
	print qq{<tr><td class="ra"><input type="checkbox" name="$cat" value="1">\n};
	print qq{</td><td class="la">$cat</td></tr>\n};
    }

    # Blank Row
#    print qq{<tr><td></td><td>&nbsp;</td></tr>\n};

    # Report Type
    print qq{<tr><td class="bra">$lex{Type}</td><td>};
    print qq{<select name="type"><option value="pdf">$lex{PDF}</option>\n};
    print qq{<option value="html">$lex{HTML}</option></select></td></tr>\n};

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

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

    # Add Page Breaks
    print qq{<tr><td class="bra">$lex{Add} $lex{'Page Break'}\n};
    print qq{</td><td><input type="checkbox" name="pagebreak" value="1">};
    print qq{</td></tr>\n};

    # Continue / End of Form
    print qq{<tr><td class="cn" colspan="2">\n};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form>\n};

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

    exit;

}
