#! /usr/bin/perl
#  Copyright 2001-2020 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.

# ======= FN Attendance Report ======= 

# Get End date; Generate months up to end of enddate month.
# We only print out days enrolled AND that student actually attended.
# Column Format: Grade, Lastname, First, Middlename, Birthdate, Status
# Number (Treaty Number), Reserve, Parent1 Name, then single columns
# for each month (S,O,N,D,J,F,M,A,M,J).
# Sorted by Band, Lastname, Firstname (1 Page per Reserve).

my %lex = ('Attendance Report' => 'Attendance Report',
	   'Main' => 'Main',
	   'Attendance' => 'Attendance',
	   'Periods Per Day' => 'Periods Per Day',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Last Name' => 'Last Name',
	   'First' => 'First',
	   'Middle' => 'Middle',
	   'Birthdate' => 'Birthdate',
	   'Status' => 'Status',
	   'Reserve' => 'Reserve',
	   'Mother' => 'Mother',
	   'School Days' => 'School Days',
	   'Error' => 'Error',
	   'Date' => 'Date',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Continue' => 'Continue',
	   'Records per Page' => 'Records per Page',
	   'Not Defined' => 'Not Defined',
	   'Grade' => 'Grade',
	   'Student' => 'Student',
	   'Not Found' => 'Not Found',
	   'Band' => 'Band',
	   'Font Size' => 'Font Size',
	   'Group' => 'Group',
	   'HTML' => 'HTML',
	   'Homeroom' => 'Homeroom',
	   'PDF' => 'PDF',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Report Type' => 'Report Type',

	   );

my $self = 'rptinac.pl';

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

# Constants
my $defmaxrecords = 28; # Maximum records per PDF page.
my $group = 'band';
my $pdf = '1';
my $html;

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

eval require "../../lib/libattend.pl";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

eval require "../../lib/liblatex.pl";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}


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

my @tim = localtime(time);
my $year = $tim[5] + 1900;
my $month = $tim[4] + 1;
my $day = $tim[3];
if (length($month) == 1){ $month = "0".$month;}
if (length($day) == 1){ $day = "0".$day;}
my $currsdate = "$year-$month-$day";
my $currdate = "$month[$month] $day, $year";


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

# HTML Header
my $title = qq{First Nation/ISC $lex{'Attendance Report'}};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{<style type="text/css">.ra { text-align:right;} .cn {text-align:center;}</style>
<link rel="stylesheet" type="text/css" media="all" href="/js/calendar-blue.css" title="blue">
<script type="text/javascript" src="/js/calendar.js"></script>
<script type="text/javascript" src="/js/lang/calendar-en.js"></script>
<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};

print qq{$chartype\n</head><body>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> | <a href="$attpage">$lex{Attendance}</a> ]\n};
print qq{<a name="top"></a>\n};
print qq{<h1>$title</h1>\n};


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


my $enddate;
if ($arr{date}){
    $enddate = $arr{date};
} else {
    $enddate = $currsdate;
}

my $startdate = $schoolstart;


my %schooldays = mkSchoolDays( $startdate, $enddate, $dbh );
# returns hash of schooldays in month. key is yyyy-mm and value is schooldays in month


if ( $pdf ) { # Open TEX file, and print Header
    $logfile = "pdflog$$.txt";
    $shortname = "inac$$";
    $filename = "$shortname.tex";
    open(TEX, ">", $filename) || die "Can't open tex file";
    print_tex_doc_start(); # Setup the start of the file.
}



my $select;
if ( $arr{reserveres} ) {
    $select = "where reserveres = 1";
}
my $sth = $dbh->prepare("select * from student $select
  order by band, lastname, firstname");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
my $studrows = $sth->rows;

# Setup statement handle to find which table student is in.
my $sth5 = $dbh->prepare("select studnum from student where studnum = ?");

my $curroom = -1; # Watch! Not a value entered for a reason...hopefully.
my $firstflag = 1;  # Flag to watch for first "real" person (not withdrawn)


while ( $sref = $sth->fetchrow_hashref ){

    # LaTeX filter the student record
    foreach my $key ( keys %$sref ) {
	( $sref->{$key} ) = latex_filter( $sref->{$key} );
    }

    my %sr = %$sref;

    $studentname = "<b>$sr{lastname}</b>, $sr{firstname} $sr{initial}";
    $studnum = $sr{studnum};

    # Now let's find which table student from: student or studentwd

    $sth5->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die;}
    my $active = $sth5->rows;  # returns 1 if in student, 0 if not.
    if ( not $active and $html){ 
	$studentname = qq{<span style="color:red;">$studentname</span>};
    }

    $oldroom = $curroom;
    $curroom = $sr{band}; # band

    if ( $curroom ne $oldroom ) { # New Page Heading (band or group changes)
        if ( not $firstflag ) {
	    print TEX "\n\\end{tabular}\n\n";
	    print TEX "\\hfil{\\bf Attended/Enrolled}\\hfil\n";
	    $linecount = 0; 
	} else { $firstflag = 0;}

	if ( $arr{pagebreak} ) {
	    print TEX "\\newpage";
	} else {
	    print TEX "\\smallskip";
	}
	
	print TEX qq{\n\n};
	print_tex_header(); # includes a begin{tabular}

    } # End of Header printing section


    # Print this student's record
    doAttSetup( $sref );
    print_tex_record( $sref );

    $linecount++;
    if ( $linecount >= $arr{maxrecords} ){ # New page.
	print TEX "\\end{tabular}\\newpage\n\n";
	print_tex_header();
	$linecount = 0;
    }

} # End of main loop


print TEX "% print_tex_end here\n";
print TEX "\\end{tabular}\n\n\\end{document}";
close TEX;

system("$pdflatex $filename > $logfile");
system("mv $shortname.pdf $downloaddir");
system("mv $logfile $downloaddir");
system("rm -f $shortname.*");
    
print qq{<h1><a href="$webdownloaddir/$shortname.pdf">};
print qq{$lex{'View/Download'} FN $lex{'Attendance Report'}</a></h1>\n};

print qq{<div>Pages are grouped by the First Nation of the Students</div>\n};

print qq{<p style="font-size:120%;">[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$attpage">$lex{Attendance}</a> | \n};
print qq{<a href="$webdownloaddir/$logfile">$lex{'View Log File'}</a> ]</h1>\n};
print qq{</body></html>\n};



#----------------------
sub print_tex_doc_start {
#----------------------

    print TEX "\\documentclass[10pt,legalpaper,oneside,landscape]{article}
\\usepackage{array,colortbl,rotating,inputenc}
$a_latex_header
\\renewcommand{\\familydefault}{\\sfdefault}
\\pagestyle{empty}
\\setlength{\\textwidth}{13in}
\\setlength{\\textheight}{7.7in}
\\setlength{\\hoffset}{-4.3in}
\\setlength{\\voffset}{-0.8in}
\\setlength{\\headsep}{10pt}
\\setlength{\\headheight}{14pt}
\\setlength{\\topmargin}{0pt}
\\setlength{\\parindent}{0pt}
\\setlength{\\tabcolsep}{5pt}
\\setlength{\\extrarowheight}{3pt}
\\pagestyle{headings}
\\markright{$schoolname - $schoolyear \\hfill 
{\\bf FN $lex{'Attendance Report'} } \\hfill $currdate -- Pg }
\n\n
\\begin{document}\n";
} # End of Print Tex Doc Start



#-------------------
sub print_tex_header {
#-------------------
    # Up to 18 Cols: (8 + 10 months)
    # Grade, Lastname, Firstname, Middlename, Birthdate
    print TEX "\\begin{tabular}{|p{1cm}|p{3cm}|p{1.6cm}|p{2cm}|p{1.8cm}";
    # Treaty, Band, Parent, Up to 10 Months.
    print TEX "|p{1.7cm}|p{2.2cm}|p{3.2cm}|";

    foreach my $yrmo ( sort keys %schooldays ){
	print TEX "p{9mm}|";
    }
    print TEX "}\\hline\n\n";

    # Now print the column header line.
    print TEX "\\rowcolor[gray]{0.90}{\\bf Grade}";
    print TEX "& {\\bf ". $lex{'Last Name'}. "} & {\\bf ". $lex{First}. "} &";
    print TEX "{\\bf ". $lex{Middle}. "} &{\\bf ". $lex{Birthdate}. "} &";
    print TEX "{\\bf ". $lex{Status}. "\\#} &{\\bf Band} & \n";
    print TEX "{\\bf ". $lex{Mother}. "}";

    foreach my $yrmo ( sort keys %schooldays ){
	my ($ty,$tm) = split(/-/,$yrmo);
	print TEX "& {\\bf $s_month[$tm]}";
    }
    print TEX "\\\\ \\hline\n\n";

    # Now print the schooldays in month
    print TEX "\\rowcolor[gray]{0.90}";
    print TEX "& & & & & & & ". $lex{'School Days'};

    foreach my $yrmo ( sort keys %schooldays ){
	print TEX "& {\\bf $schooldays{$yrmo}}";
    }
    print TEX "\\\\ \\hline\n\n";

}



#---------------
sub doAttSetup {  # Version with monthly attendance info
#---------------
    # Needs globals: @schoolmonths - ordering of school months.
    #  %schooldays - days in each month in hash.
    #  $periodsperday - number of periods in the school day.

    my $sref = shift;
    %sr = %$sref;

    my $studnum = $sr{studnum};

    %absent = ();
    %tardy = ();
    %enrol = ();


    my $periodsperday = $g_ppd{ $sr{grade} };

    if ( not $periodsperday ){
	if ( not $sr{grade} ){ $sr{grade} = $lex{'Not Found'}; }
	print qq{<h1>$lex{'Periods Per Day'} $lex{'Not Defined'}<br>};
	print qq{$lex{Grade}:$sr{grade} $lex{Student}:$studentname</h1>\n};
	print qq{</body></html>\n};
	exit;
    }
 

    # Pass Absent/Late strings to the library.
    my %lexi = ('Absent' => $absentString,
		'Late' => $lateString
	);

    # calculate attendance, one for each month.
    foreach my $yrmo ( sort keys %schooldays ) {
	$absrec = calcMonthlyAttendance( $studnum, $yrmo, $periodsperday,
					 $enddate, \%lexi, $dbh );

	( $absent{$yrmo}, $tardy{$yrmo} ) = split(/:/,$absrec);
	$absent{ $yrmo } = format_number( $absent{ $yrmo }, 1);
    }
    
    # calculate enrollment, one for each month
    my $ymref = calcMonthlyEnrollment( $studnum, $schoolstart, $currsdate, $dbh );
    %enrol = %$ymref;  # yyyy-mm -> start,end,days

    # just used to set zero values.
    foreach my $yrmo ( sort keys %schooldays ) { 
	$enrol{ $yrmo }{'days'} = format_number( $enrol{ $yrmo }{'days'}, 1);
    }
   
}


#-------------------
sub print_tex_record {
#-------------------

    my $sref = shift;
    my %sr = %$sref;

    # Grade, Lastname, Firstname, Middlename
    print TEX "\\hfil $sr{grade}\\hfill& $sr{lastname} & $sr{firstname}";
    print TEX "& $sr{initial} ";

    # Birthdate, Treaty#, 
    print TEX "& $sr{birthdate} & $sr{treaty} ";

    # Band Name, Mother Name
    print TEX "& $sr{band} & $sr{maiden} ";

    my $days = $schooldays - $absentdaytot;

    #Now print Monthly Records
    foreach my $yrmo ( sort keys %schooldays ) {
	my $present = format_number($enrol{$yrmo}{'days'} - $absent{$yrmo}, 1);

	print TEX "& {\\footnotesize $present/$enrol{$yrmo}{'days'}}";
    }
    print TEX " \\\\ \\hline\n";

}



#----------------
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" cellpadding="3" border="0">\n};


    print qq{<tr><td class="bra">$lex{Date}</td><td>\n};
    print qq{<input type="text" id="monthatt_date" name="date" value="$currsdate" size="10">\n};
    print qq{<button type="reset" id="monthatt_trigger">...</button></td></tr>\n};

    
    print qq{<tr><td class = "bra">Only Living on Reserve</td>\n};
    print qq{<td><input type="checkbox" name="reserveres" value="1"></td></tr>\n};

    
    print qq{<tr><td class="bra">$lex{'Records per Page'}</td>\n<td>};
    print qq{<input type="text" name="maxrecords" size="4" value="$defmaxrecords"></td></tr>\n};

    print qq{<tr><td class="bra">Page Break when First Nation Changes</td>\n<td>};
    print qq{<input type="checkbox" name="pagebreak" value="1" checked></td></tr>\n};
    
    print qq{<tr><td></td><td><input type="submit" value="$lex{Continue}"></td></tr>\n};

    print qq{</table></form>\n};

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "monthatt_date",
        ifFormat       :    "%Y-%m-%d",
        button         :    "monthatt_trigger",
        singleClick    :    false,
        step           :    1
    })\n  };

    print qq{</script>\n};

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

    exit;

}

