#! /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 $schooldays = 198; # change to suit. only a default.

my %lex = ('Report' => 'Report',
	   'Main' => 'Main',
	   'Attendance' => 'Attendance',
	   'No Records Found' => 'No Records Found',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Year End Attendance' => 'Year End Attendance',
	   'Bdate' => 'Bdate',
	   'Grade' => 'Grade',
	   'Sex' => 'Sex',
	   'Enrollment Changes' => 'Enrollment Changes',
	   'School Days' => 'School Days',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Homeroom' => 'Homeroom',
	   'Select' => 'Select',
	   'Sort by' => 'Sort by',
	   'Lastname, Firstname' => 'Lastname, Firstname',
	   'Homeroom, Lastname, Firstname' => 'Homeroom, Lastname, Firstname',
	   'Grade, Lastname, Firstname' => 'Grade, Lastname, Firstname',
	   'Continue' => 'Continue',
	   'Error' => 'Error',

	   );

my $self = 'rptattyear.pl';

use DBI;
use CGI;

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

my $maxlines = 28;
my $shortname = "attyear$$";
my $filename = "$shortname.tex";
my $logfile = "pdflog$$.txt";

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

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

my $sortorder = "homeroom, lastname, firstname";
if ( $arr{sortorder} eq $lex{'Lastname, Firstname'} ) {
    $sortorder = "s.lastname, s.firstname";
} elsif ( $arr{sortorder} eq $lex{'Grade, Lastname, Firstname'} ) {
    $sortorder = "grade,lastname, firstname";
} elsif ( $arr{sortorder} eq $lex{'Homeroom, Lastname, Firstname'} ) {
    $sortorder = "homeroom, lastname, firstname";
}
if ( $arr{sortorder} ) { delete $arr{sortorder}; }


my $select;
if ( $arr{group} ) {
    if ( $arr{select} eq $lex{Grade} ) { # Find this grade;
	my $grp = $dbh->quote( $arr{group} );
	$select = "and grade = $grp";
    } elsif ( $arr{select} eq $lex{Homeroom} ) {
	my $grp = $dbh->quote( $arr{group} );
	$select = "and homeroom = $grp";
    } 
}

my $title = qq{$lex{'Year End Attendance'} $lex{Report}};
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

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="margin:1em;">[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$attpage">$lex{Attendance}</a> ]\n};


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



# Set Date format.
my ($year,$mo, $day) = split('-', $arr{startdate});
$startdate = "$month[$mo] $day, $year";

my ($eyear,$emo,$eday) = split( '-', $arr{enddate});
$enddate = "$month[$emo] $eday, $eyear";


if ($arr{schooldays}) {
    $schooldays = $arr{schooldays};
    delete $arr{schooldays};
}

my @students;
my $sth = $dbh->prepare("select distinct a.studentid, s.lastname, s.firstname 
			from attend as a, studentall as s 
			where a.studentid = s.studnum $select order by $sortorder");

#print qq{SEL: $select<br>\n};
#print qq{SORT: $sortorder<br>\n};

$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
while ( my ($studnum, $ln, $fn) = $sth->fetchrow ) {
    push @students, $studnum;
}

if ( not @students ){
    print qq{<h3>$lex{'No Records Found'}</h3>\n};
    print qq{</body></html>\n};
    exit;
}

# Setup Tex File 
open(TEX,">$filename") || die "Cannot open tex file";
prTexHeader(); # print TeX file header defaults.
$prevstud = -1;


my $sth = $dbh->prepare("select absdate, reason, period, subjsec, late from attend
  where studentid = ? and to_days(absdate) >= to_days('$arr{startdate}') and 
  to_days(absdate) <= to_days('$arr{enddate}') order by absdate");

my $sth1 = $dbh->prepare("select lastname, firstname, birthdate, grade, sex 
 from studentall where studnum = ?");

my $first = 1;


# Main Loop - once for each student.
foreach  my $studnum ( @students ) {

    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    my $latetot = 0;
    my $absenttot = 0;
   
    my $lateu = 0;
    my $absentu = 0;
    my $totalu = 0;

    # end student record
    if (not $first) {
	print TEX "\\end{multicols}\\hrulefill\\\\ \n\\bigskip";
    } else { 
	$first = 0;
    }


    # Fetch Student's Info
    $sth1->execute($studnum);
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname, $birthdate, $grade, $sex) = $sth1->fetchrow;
   
    # Print Student Info
    print TEX "{\\Large\\bf $lastname, $firstname} ($studnum) ";
    print TEX "{\\bf ". $lex{Bdate}. ":} $birthdate {\\bf ". $lex{Grade};
    print TEX ":} $grade {\\bf ". $lex{Sex}. ":} $sex\\\\ \n";

    # Fetch Enrollment/Withdrawal Changes
    my $sth1 = $dbh->prepare("select date, type, description from transfer 
     where studnum = ? order by date");
    $sth1->execute( $studnum );
    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
   
    my $entryrecs = $sth1->rows;
    if ($entryrecs > 0 ) {  # then print enrollment change records
	print TEX "\\hrulefill\n\n{\\large\\sf ". $lex{'Enrollment Changes'};
	print TEX "}\n\n \\begin{tabular}{lll}\n";
	for ($i=1; $i<=$entryrecs; $i++) {
	    my ($date, $type, $description) = $sth1->fetchrow;
	    $description =~ s/[^0-9A-Za-z ]//g; #strip nontext from desc field  
   	    print TEX "$date & $type & $description\\\\ \n";   
	}
	print TEX "\\end{tabular}\n\n\\medskip \n";
    }

    print TEX "\\hrulefill\n\n\\setlength{\\premulticols}{5pt}\n\n";
    print TEX "\\setlength{\\postmulticols}{5pt}\\begin{multicols}{3}\\raggedright\n";

    # Loop through all attendance records.
    while ( my ( $absdate, $reason, $period, $subjsec, $late ) = $sth->fetchrow ) {

	$reason =~ s/[^0-9A-Za-z ]//g;  # strip any non text from reason field
	print TEX  "$absdate P$period $reason\\\\ \n";

    }  

} # End of Main Student Loop


print TEX "\\end{multicols}\n\\end{center}\\end{document}\n";
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">\n};
print qq{$lex{'View/Download'} $lex{'Year End Attendance'} $lex{Report}};
print qq{</a></h1>\n[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$webdownloaddir/$logfile">$lex{'View Log File'}};
print qq{</a> ]</body></html>\n};


#--------------
sub prTexHeader {
#--------------

    my $papersize;
    if ( $defaultpapersize ) {
	$papersize = $defaultpapersize;
    } else {
	$papersize = 'letterpaper';
    }

    print TEX "\\documentclass[12pt,$papersize]{article}\\usepackage{array,multicol,inputenc}\n";
    print TEX "$a_latex_header\n\\renewcommand{\\familydefault}{\\sfdefault}\n";
    print TEX "\\setlength{\\textwidth}{7.5in}\n \\setlength{\\textheight}{10in}\n";
    print TEX "\\setlength{\\hoffset}{-1.2in}\n\\setlength{\\voffset}{-1.4in}\n";
    print TEX "\\setlength{\\extrarowheight}{2pt}\n\\setlength{\\parindent}{0pt}\n";

    print TEX "\\begin{document}\n\\begin{center}\n{\\sf\\huge $schoolname}\n\n{\\sf\\LARGE ";
    print TEX  $lex{'Year End Attendance'};
    print TEX "} \n\n\\bigskip\n";

}


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

    # print sortorder and selection input form.
    print qq{<h1>$title</h1>\n};
    print qq{<div><form action="$self" method="post">\n};
    print qq{<input type="hidden" name="startflag" value="1">\n};

    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
    print qq{<tr><td class="bra">$lex{'Sort by'}</td>\n};
    print qq{<td><select name="sortorder"><option>$lex{'Lastname, Firstname'}</option>\n};
    print qq{<option>$lex{'Homeroom, Lastname, Firstname'}</option>\n};
    print qq{<option>$lex{'Grade, Lastname, Firstname'}</option>\n};
    print qq{</select></td></tr>\n};

    print qq{<tr><td class="bra">$lex{Select}</td>\n};
    print qq{<td><select name="select"><option>$lex{Grade}</option>\n};
    print qq{<option>$lex{Homeroom}</option>\n};
    print qq{</select>\n};
    print qq{<input type="text" name="group" style="width:6ch;"></td></tr>\n};
    
    print qq{<tr><td class="bra">$lex{'Start Date'}</td><td><input type="text" };
    print qq{name="startdate" id="sdate" style="width:10ch;" value="$schoolstart">\n};
    print qq{<button type="reset" id="start_trigger">...</button>\n};
    print qq{</td></tr>\n};

    print qq{<tr><td class="bra">$lex{'End Date'}</td><td><input type="text" };
    print qq{name="enddate" id="edate" style="width:10ch;" value="$schoolend">\n};
    print qq{<button type="reset" id="end_trigger">...</button></td></tr>\n};

    print qq{<tr><td class="bra">$lex{'School Days'}</td><td>};
    print qq{<input type="text" name="schooldays" value="$schooldays" size="4"></td></tr>\n};

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


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

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "sdate", // 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
    });

    Calendar.setup({
        inputField     :    "edate", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "end_trigger", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // 
    });
   </script>\n};

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

    exit;


}
