#!/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',
	   'No Records Found' => 'No Records Found',
	   'Continue' => 'Continue',
	   'Student Group' => 'Student Group',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Last,First/Last/Initials/Studnum' => 'Last,First/Last/Initials/Studnum',
	   'Student' => 'Student',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'Sort by' => 'Sort by',
	   'Font Size' => 'Font Size',
	   'Checked' => 'Checked',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Blank=All' => 'Blank=All',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Last,First/Last/Initials/Studnum' => 'Last,First/Last/Initials/Studnum',
	   'or' => 'or',
	   'Type' => 'Type',
	   'PDF' => 'PDF',
	   'HTML' => 'HTML',
	   'Name' => 'Name',
	   'Next Page' => 'Next Page',
	   'Checked' => 'Checked',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Page' => 'Page',
	   'Cannot open' => 'Cannot open',

	   );

my $self = 'rptmedstudent.pl';

# Width of PDF columns for each field
my $categorywidth = '35mm';
my $descriptionwidth = '145mm';


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

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 $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);



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{Student} $lex{Medical} $lex{Report}};

print qq{$doctype\n<html><head><title>$title</title>
<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>$title</h1>\n};


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

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

    if ( $arr{student} ) {
	searchStudent( $arr{student} );
    } else {
	searchGroup( $arr{group}, $arr{groupid} );
    }

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




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

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

    my $sth = $dbh->prepare("select lastname, firstname, grade, homeroom from studentall 
			    where studnum = ?");
    my $sth1 = $dbh->prepare("select category, description from student_medical where studnum = ?");


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

	print qq{<h1>$lex{Medical} $lex{Report} - $schoolname</h1>\n};
	print qq{<h3>$currdate</h3>\n};

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


	my $first = 1;
	my $curroom = -1;
	my $counter = 1;

	# Loop through all students
	foreach my $key ( sort keys %arr ) {

	    my ($dud, $studnum ) = split(/:/, $key);

	    # Get Student Information
	    $sth->execute( $studnum );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname, $grade, $homeroom ) = $sth->fetchrow;

	    print qq{<tr><td colspan="2" class="bla">};
	    print qq{$firstname $lastname ($studnum) $homeroom/$grade</td></tr>\n};

	    # Get Medical Records
	    $sth1->execute( $studnum );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	    while ( my ( $category, $description ) = $sth1->fetchrow ) {
		print qq{<tr><td>$category</td><td>$description</td></tr>\n};
	    }

#  No sorting done, except by name, currently. Hence no grouping.
#	    $oldroom = $curroom;
#	    if ( $sort eq 'homeroom' ) { $curroom = rec{homeroom}; }
#	    elsif ( $sort eq 'grade' ) { $curroom = $rec{grade}; }

#	    # put in table break if we are starting a new room/grade
#	    if ( $curroom ne $oldroom and not $first and $sort ne 'name' ) {
#		print qq{</table><p></p><table cellspacing="0" cellpadding="3" border="1">\n};
#	    } else { $first = 0; }
	

	}  # End of record printing loop

	print qq{</table>};
	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 = "rptmedstud$$";
	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[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";

	my $first = 1;
	my $curroom = -1;
	my $counter = 1;

	# Loop through all students
	foreach my $key ( sort keys %arr ) {

	    my ($dud, $studnum ) = split(':', $key);

	    # Get Student Information
	    $sth->execute( $studnum );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname, $grade, $homeroom ) = $sth->fetchrow;

	    print TEX "\\begin{tabular}{|p{$categorywidth}|p{$descriptionwidth}|}\\hline\n";
	    print TEX "\\multicolumn{2}{|l|}{ {\\bf $firstname $lastname} ($studnum) $homeroom/$grade}";
  	    print TEX "\\\\ \\hline\n";

	    # Get Medical Records
	    $sth1->execute( $studnum );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	    while ( my ( $category, $description ) = $sth1->fetchrow ) {
		($description) = latex_filter( $description );
		print TEX "$category & $description \\\\ \\hline\n";
	    }
	    print TEX "\\end{tabular}\n\n\\smallskip\n";

  
	}  # End of 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 $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> ]};
	print qq{</body></html>\n};

    } # end of pdf report

    exit;
}



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

    # 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><td class="bra">$lex{Student}</td>};
    print qq{<td><input type="text" name="student" size="30"><br>\n};
    print qq{$lex{'Last,First/Last/Initials/Studnum'}</td></tr>\n};

    print qq{<tr><td></td><td class="bla"><b>$lex{or}</b></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Student Group'}</td>\n<td>};
    print qq{<select name="group"><option>$lex{Grade}</option>\n};
    print qq{<option>$lex{Homeroom}</option></select>\n };
    print qq{<input type="text" name="groupid" size="10"><br>};
    print qq{$lex{'Separate with Spaces'}, $lex{'Blank=All'}</td></tr>\n};

# Hide Sort Order for now
#    print qq{<tr><td class="bra">$lex{'Sort by'}\n};
#    print qq{</td><td><select name="sortorder"><option>$lex{Name}</option>\n};
#    print qq{<option>$lex{Grade}</option>\n};
#    print qq{<option>$lex{Homeroom}</option>\n};
#    print qq{</select></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'Next Page'} $lex{Checked}?</td>\n<td>};
    print qq{<input type="checkbox" name="studcheck" value="1"></td></tr>\n};

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

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


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

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

    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;

}


#----------------
sub searchStudent {
#----------------

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

    my $student = shift;

    # Setup the Search
    if ($student =~ /\d+/) {  # we have a student number
	$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
          where studnum = ?");
	$sth->execute( $student );

    } else { # we have words possibly with a comma
	($lastname,$firstname)  = split /\,/, $student;
	$firstname =~ s/^\s*//;
	$lastname =~ s/^\s*//;
	if ($lastname and $firstname){ # both entered.
	    $sth = $dbh->prepare("select  lastname, firstname, studnum from studentall 
             where lastname = ? and firstname = ?");
	    $sth->execute( $lastname, $firstname );

	} elsif ($lastname and not $firstname){ # only lastname (no comma)
	    if (length($lastname) == 2){ # search by initials: fi, li.
		my $fi = substr($lastname,0,1). '%'; 
		my $li = substr($lastname,1,1). '%';
		$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
                 where lastname $sql{like} ? and firstname $sql{like} ?");
		$sth->execute( $li, $fi );

	    } else {
		$sth = $dbh->prepare("select lastname, firstname, studnum from studentall 
                  where lastname = ? order by firstname");
		$sth->execute( $lastname );
	    }
	} else { # print an error....
	    print qq{<h1>$lex{Error}</h1>\n};
	    print qq{</body></html>\n};
	    exit;
	}

    } # Last Else
    # We should now have a $sth defined.


    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    my $rows = $sth->rows;
    # print qq{Rows: $rows<br>\n};


    if ( $rows < 1 ) { 
	print qq{<h1>$lex{'No Student(s) Found'}</h1>\n};
	print qq{<table cellspacing="0" cellpadding="3" border="0">\n};
	print qq{<form action="$self" method="post">\n};
	print qq{<input type="hidden" name="page" value="1">\n};
	print qq{<input type="hidden" name="transactmode" value="$arr{transactmode}">\n};
	print qq{<table cellspacing="0" cellpadding="3" border="0">\n};

	print qq{<tr><td colspan="2" class="cn">$lex{Student} };
	print qq{($lex{'Last,First/Last/Initials/Studnum'})<br>};
	print qq{<input type="text" name="student" size="30"></td></tr>\n};

	print qq{<tr><td colspan="2" class="cn">\n};
	print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
	print qq{</table></form></body></html>\n};
	exit; 
    }

    my $chk;
    if ( $arr{studcheck} ) {
	$chk = 'checked="checked"';
    }

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="type" value="$arr{type}">\n};
    if ( $arr{type} eq $lex{PDF} ) {
	print qq{<input type="hidden" name="fontsize" value="$arr{fontsize}">\n};
	print qq{<input type="hidden" name="papersize" value="$arr{papersize}">\n};
    }

    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Student}</th><th>$lex{Select}</th></tr>\n};

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

    my $first = 1;
    while ( my ($lastname, $firstname, $studnum) = $sth->fetchrow ) {

	# Find any med records; otherwise skip
	$sth1->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth1->fetchrow;

	print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>\n};
	if ( $count ) {
	    print qq{<input type="checkbox" name="$lastname$firstname:$studnum" value="1" $chk>\n};
	} else {
	    print $lex{'No Records Found'};
	}
	print qq{</td></tr>\n};

    }

    print qq{</table>\n};
    print qq{<input type="submit" value="$lex{'Continue'}">\n};
    print qq{</form></body></html>\n};

    exit;

} # end of searchStudent



#--------------
sub searchGroup {
#--------------
    # search for a group of students (by grade(s) or homeroom(s))
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }


    # Select Students
    my @students = ();
    my $sort = 'name'; # hold type of sort.

    if ( $arr{groupid} ) { # then we have to do something...

	my $group;
	my @groups = ();
	@groups = split /\s+/, $arr{groupid};
	if ( $arr{group} eq $lex{Grade} ) {
	    $group = 'grade';
	    $sort = 'grade';
	} else {
	    $group = 'homeroom';
	    $sort = 'homeroom';
	}

	my $sth = $dbh->prepare("select studnum from student where $group = ? 
         order by $group, lastname, firstname");
	foreach my $grp ( @groups ) {
	    $sth->execute( $grp );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $studnum = $sth->fetchrow ) {
		push @students, $studnum;
	    }
	}

    } else { # all students

	my $sortorder = "lastname, firstname";

# Currently not enabled in showStartPage
#	if ( $arr{sortorder} eq $lex{Homeroom} ) {
#	    $sortorder = "homeroom, lastname, firstname";
#	    # $sort = 'homeroom';
#	} elsif ( $arr{sortorder} eq $lex{Grade} ) {
#	    $sortorder = "grade, lastname, firstname";
#	    # $sort = 'grade';
#	}

	$sth = $dbh->prepare("select studnum from student order by $sortorder");
	$sth->execute;
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $studnum = $sth->fetchrow ) {
	    push @students, $studnum;
	}
    }

    # Start the Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="type" value="$arr{type}">\n};
    if ( $arr{type} eq $lex{PDF} ) {
	print qq{<input type="hidden" name="fontsize" value="$arr{fontsize}">\n};
	print qq{<input type="hidden" name="papersize" value="$arr{papersize}">\n};
    }
    print qq{<input type="submit" value="$lex{'Continue'}">\n};

    # Start the Table
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Student}</th><th>$lex{Select}</th></tr>\n};

    my $chk;
    if ( $arr{studcheck} ) {
	$chk = 'checked="checked"';
    }

    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    my $sth1 = $dbh->prepare("select count(*) from student_medical where studnum = ?");

    my $first = 1;

    # Now loop through all students
    foreach my $studnum ( @students ) {

	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname ) = $sth->fetchrow;

	# Find any medical records
	$sth1->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth1->fetchrow;

	print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td><td>\n};
	if ( $count ) {
	    print qq{<input type="checkbox" name="$lastname$firstname:$studnum" value="1" $chk>\n};
	} else {
	    print $lex{'No Records Found'};
	}
	print qq{</td></tr>\n};

    }

    print qq{</table>\n};
    print qq{<input type="submit" value="$lex{'Continue'}">\n};
    print qq{</form></body></html>\n};

    exit;

} # end of searchGroup
