#! /usr/bin/perl
#  Copyright 2001-2022 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 = ('Main' => 'Main',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'View/Download' => 'View/Download',
	   'Student Pictures Report' => 'Student Pictures Report',
	   'View Log File' => 'View Log File',
	   'Continue' => 'Continue',
	   'Homeroom' => 'Homeroom',
	   'Grade' => 'Grade',
	   'Report Type' => 'Report Type',
	   'HTML' => 'HTML',
	   'Pictures per Row' => 'Pictures per Row',
	   'Students' => 'Students',
	   'Error' => 'Error',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Font Size' => 'Font Size',
	   'Gray Shade' => 'Gray Shade',
	   'Smaller=Darker' => 'Smaller=Darker',
	   'No Picture' => 'No Picture',
	   'PDF' => 'PDF',
	   'Full Size' => 'Full Size',
	   'Thumbnail' => 'Thumbnail',
	   'Picture' => 'Picture',
	   'All' => 'All',
	   'Export' => 'Export',
	   'Select by' => 'Select by',

	   );

my $self = 'rptpicstudent.pl';

use DBI;
use CGI;
use Cwd;

# Configurable settings
my $defaultgrayshade = '0.95';  # shading for alternate rows
my $defaultPicsPerRow = 6; # number of pictures per row.
my $heightadjust = 13;  # increase page height by this amount (mm).


# Get current dir so know what path for config files.
my $configpath;
my $teachermode;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.
} else {
    $configpath = '../..'; # go back two to get to etc.
}

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


eval require "$configpath/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;

# Set location of student images.
my $imagepath;
if ( $arr{piclocation} eq $lex{'Full Size'} ) {
    $imagepath = $picdir;
} else { # use thumbnails.
    $imagepath = $tndir;
}


my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $iddst) =
localtime(time);

$year = $year + 1900;
$wday++; $mon++;
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";

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



# Get current dir so know what CSS to display;
if ( $teachermode ){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
}

my $title = qq{$lex{'Student Pictures Report'} - PDF};
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{<div>[ <a href="$homepage">$lex{Main}</a>\n};
if ( not $teachermode ) { # show export page link
    print qq{ | <a href="$exppage">$lex{Export}</a> ]\n};
} else { print qq{ ]\n}; }

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


# Get values
if ( not $arr{page} ) {
    showStartPage();
    
} else {
    delete $arr{page};
    selectStudents();
}


#-----------------
sub selectStudents  {
#-----------------

    my $select;
    my $tableheader;    # = "$arr{groupname} $arr{groupvalue}";
    my $group;
    my $value;

    if ( $arr{homeroom} )  {
	$select = "where homeroom = ?";
	$group = 'homeroom';
	$value = $arr{homeroom};
	
    } elsif ( $arr{grade} ) {
	$select = "where grade = ?";
	$group = 'grade';
	$value = $arr{grade};

    } else { # no selection
	print qq{<h3>No Selection. Please select a Grade or Homeroom</h3>\n};
	print qq{</body></html>\n};
	exit;
    } 

    
    if ( $select and $arr{skipnopic} ) { # Skip if no picture
	$select .= ' and pic is not NULL';
    }
    
    my @students;

    if ( $select ) { # we have some grade/homeroom entered.
	my $sth = $dbh->prepare("select studnum from student $select 
				order by lastname, firstname");

	$sth->execute( $value );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $stud = $sth->fetchrow ) {
	    push @students, $stud;
	}
	
    
    } else { # just get all students

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

    if ( not @students ){ # No students found...
    	print qq{<h3>$lex{'No Student(s) Found'}!</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    if ( $arr{reporttype} eq $lex{PDF} ) {
	showPdfReport( $group, $value, \@students );

    } else { # no html report yet.
#	showHtmlReport( \@students );
    }



}



#----------------
sub showPdfReport  {
#----------------

    # Get Student Number list
    my ($group, $value, $studref) = @_;
    my @students = @$studref;

    #print qq{GRP:$group<br>\n};
    #print qq{VAL:$value<br>\n};
    #print qq{Students:", @students, "<br>\n};


    # Set Font/Papersize
    # The tabcolsep is 1mm 
    my $fontsize = $arr{fontsize}. 'pt';

    # Set Paper Size, text width and height
    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};
    
    # Adjust Text Height.
    $textheight =~ s/mm//;
    $textheight += $heightadjust;
    $textheight .= 'mm';

    # Restrict Gray Shading values
    if ( $arr{grayshade} > 1 ) { $arr{grayshade} = 1; }
    if ( $arr{grayshade} < 0.5 ) { $arr{grayshade} = 0.5; }

    # Set the Picture Width (in mm)
    my $wi = $textwidth;
    $wi =~ s/mm//; # strip mm.
    my $cellwidth = ( $wi - ( $arr{picsperrow} - 1 ) ) / $arr{picsperrow};
    $cellwidth = int $cellwidth;
    $picwidth = $cellwidth - 1;

    $picwidth = $picwidth. 'mm';
    $cellwidth = $cellwidth. 'mm';
    # print qq{Text:$textwidth  WI:$wi  PPR:$arr{picsperrow} PW:$picwidth<br>\n};


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

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

    print TEX "\\documentclass[$fontsize,$papersize ]{article}
\\usepackage{array,colortbl,graphicx,inputenc,fancyhdr}
$a_latex_header
\\pagestyle{empty}
\\setlength{\\textwidth}{$textwidth}
\\setlength{\\textheight}{$textheight}
\\setlength{\\hoffset}{-36mm}
\\setlength{\\voffset}{-26mm}
\\addtolength{\\evensidemargin}{0mm}
\\addtolength{\\oddsidemargin}{0mm}
\\setlength{\\tabcolsep}{1mm}
\\setlength{\\parindent}{0mm}
\\setlength{\\footskip}{2mm}
\\setlength{\\headsep}{2mm}
\\setlength{\\extrarowheight}{2mm}
\\pagestyle{fancy}
\\lhead{$schoolname -- $schoolyear}
\\rhead{Page \\thepage}\n";

    if ( $tableheader ) {
	print TEX "\\chead{\\bf\\Large $tableheader}\n";
    }

    print TEX "\\rfoot{ $currdate }\n\\thispagestyle{fancy}\n\\cfoot{ }\n";

    #}{>{\\columncolor[gray]{1.00}}p{$namewidth mm}}\n";
    # Note above... a columncolor of 1.00 means white, smaller number is darker.

    print TEX "\\begin{document}\n\n";


    my $sth = $dbh->prepare("select lastname, firstname, $group from student where studnum = ?");

    my $curroom = "$lex{All} $lex{Students}";
    my $count;
    my @studentprint = ();
    my $first = 1;

    foreach my $studnum ( @students ) {


	$sth->execute( $studnum );
	my ($lastname, $firstname, $groupval ) = $sth->fetchrow;

	$oldroom = $curroom;
	if ( $value ) { # only change room if we have group values (otherwise it's all students
	    $curroom = $groupval;
	}

	if ( $first ) {
	    print TEX "\\chead{\\bf\\Large ". ucfirst( $group). " $curroom}\n";
	}

	if ( $curroom ne $oldroom and not $first ) { # flush buffer, new page, etc.
	    printPictureRow( $arr{picsperrow}, $group, $picwidth, $cellwidth, \@studentprint );
	    @studentprint = ();
	    print TEX "\\newpage\n\n";
	    print TEX "\\chead{\\bf\\Large ". ucfirst( $group). " $curroom}\n";

	}
	$first = 0;


	$count++;
	push @studentprint, $studnum;

	# Print Picture Row if @studentprint full
	if ( ( $#studentprint + 1  == $arr{picsperrow}  ) 
	     or ( $count == $#students + 1 ) ) {

	    printPictureRow( $arr{picsperrow}, $group, $picwidth, $cellwidth, \@studentprint );
	    @studentprint = ();

	} # end of if student print row
	
    }  # End of Loop for all students


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

    # Solve download location issues with cgi vs tcgi..
    # Get current dir so know what CSS to display;
    if (getcwd() =~ /tcgi/){ # we are in tcgi
	$downloaddir = $tchdownloaddir;
	$webdownloaddir = $tchwebdownloaddir;
    }

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

} # end of showPdfReport



#----------------
sub showStartPage { # Get Custom Values
#----------------

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

    # Get Grades
    $sth = $dbh->prepare("select distinct grade from student 
      where grade is not NULL and grade != ''");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $gr = $sth->fetchrow ) {
	push @grades, $gr;
    }
    @grades = sort {$a <=> $b} @grades;

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

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


    # Select Grade or Homeroom
    print qq{<tr><td class="bra">$lex{'Select by'}</td>\n};
    print qq{<td>$lex{Grade} <select name="grade"><option></option>\n};
    foreach my $gr ( @grades ) {
	print qq{<option>$gr</option>\n};
    }
    print qq{</select> <b>or</b> };

    print qq{$lex{Homeroom} };
    print qq{<select name="homeroom"><option></option>\n};
    foreach my $hr ( @homerooms ) {
	print qq{<option>$hr</option>\n};
    }
    print qq{</select></td></tr>\n};


    
    # Get Student Pictures per Row
    print qq{<tr><td class="bra">$lex{'Pictures per Row'}</td><td>\n};
    print qq{<input type="text"  name="picsperrow" value="$defaultPicsPerRow" style="width:5ch;">};
    print qq{</td></tr>\n};

    # Picture Directory to use
    print qq{<tr><td class="bra">$lex{Picture}</td><td>};
    print qq{<select name="piclocation"><option>$lex{Thumbnail}</option>\n};
    print qq{<option>$lex{'Full Size'}</option></select></td></tr>\n};


    # Get 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>\n};
    print qq{<option>$lex{A4}</option>\n};
    print qq{</select></td></tr>\n};

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

    # Get Gray Shading
    print qq{<tr><td class="bra">$lex{'Gray Shade'}</td><td>\n};
    print qq{<input type="text"  name="grayshade" value="$defaultgrayshade" style="width:5ch;">};
    print qq{ (0-1) $lex{'Smaller=Darker'}</td></tr>\n};

    # Get Report Type, only PDF so far.
    print qq{<tr><td class="bra">$lex{'Report Type'}</td><td>};
    print qq{ <select name="reporttype">\n};
    print qq{<option>$lex{PDF}</option>\n};
#    print qq{<option>$lex{HTML}</option>\n};
    print qq{</select></td></tr>\n};

    print qq{<tr><td class="bra">Missing Pictures</td>\n<td>};
    print qq{<input type="checkbox" name="skipnopic" value="1" checked>};
    print qq{Skip Students without Pictures</td></tr>\n};

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

    exit;

}


#------------------
sub printPictureRow  {
#------------------

    my ( $picsPerRow, $group, $picwidth, $cellwidth, $ref ) = @_;
    my @studentprint = @$ref;

    # print table header (only doing 1 row)
    print TEX "\\begin{tabular}{|";
    for ( 1 .. $picsPerRow ) { 
	print TEX "p{$cellwidth}|";
    }
    print TEX "}\\hline\n";

    my $sth = $dbh->prepare("select lastname, firstname, homeroom, $group from student 
			    where studnum = ?");

    # print picture rows.
    my $first = 1;
    for ( 1 .. $picsPerRow ) { # do the row.
	
	my $studnum = shift @studentprint;

	if ( not $first ) {
	    print TEX ' & ';
	} else { 
	    $first = 0; 
	}
	
	if ( $studnum ) {

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

	    if ( -e "$imagepath/$studnum.jpg" ) {
		print TEX "\\hfil\\includegraphics[width=$picwidth]{$imagepath/$studnum.jpg}";
	    } else {
		print TEX "\\hfil\\raisebox{16mm}{". $lex{'No Picture'}. "}";
	    }
	    print TEX "\n\n{\\footnotesize\\sf $firstname $lastname}\\hfil\n\n";
	    print TEX "{\\footnotesize\\sf($studnum) $homeroom}\\hfil";

	}
		
    } # next picture

    print TEX "\\\\\\hline\n";
    print TEX "\\end{tabular}\n";


} # end of printBuffer
