#! /usr/bin/perl
#  Copyright 2001-2022 Leslie Richardson

#  This file is part of Open Admin for Schools.

# INAC Report 2 - by Grade only, not band. Uses new library functions.


my %lex = ('Attendance Report' => 'Attendance Report',
	   'Main' => 'Main',
	   'Attendance' => 'Attendance',
	   'Periods Per Day' => 'Periods Per Day',
	   'Error' => 'Error',
	   'Grade' => 'Grade',
	   'Student' => 'Student',
	   'Missing' => 'Missing',
	   'Days Open' => 'Days Open',
	   'Total' => 'Total',
	   'Month' => 'Month',
	   'Average' => 'Average',

	   );

my $self = 'rptinac2.pl';

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


# 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";
my $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
print qq{$doctype\n<html><head><title>INAC $lex{'Attendance Report'} 2</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

print qq{<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>INAC $lex{'Attendance Report'} 2</h1>\n};


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

my $startdate = $schoolstart;


# Functions from LibAttend
%schooldays = mkSchoolDays( $startdate, $enddate, $dbh );
# returns hash of schooldays in month. key is yyyy-mm and value is schooldays in month
#~~ print qq{School Days", %schooldays, "<br>\n};


# Find the Students, first get current students
my %students;
my $sth = $dbh->prepare("select studid, studnum from student");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
while ( my ($id, $studnum) = $sth->fetchrow ) {
    $students{$studnum} = 1;
}

# now find any others in attendance records.
my $sth = $dbh->prepare("select distinct studentid from attend 
			where studentid is not NULL and studentid != '';");
$sth->execute;
if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
while ( my $studnum = $sth->fetchrow ) {
    $students{$studnum} = 1;
}


my %studgrade;
my %gender;
$sth = $dbh->prepare("select grade, sex from studentall where studnum = ?");
foreach my $studnum ( keys %students ) {

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

    
    if ( not $grade ) { 
	print qq{$lex{Missing} $lex{Grade}. $lex{Student}: $studnum<br>\n};
	#delete $students{$studnum}; # No Grade = Remove.
    } else { # put in the grade value
	if ( not $studgrade{$grade} ) { $studgrade{$grade} = []; }
	push @{ $studgrade{$grade} }, $studnum;
	$gender{$studnum} = $gender;
    }
}

# use Data::Dumper;
# print Dumper %studgrade;


my %lexi = ('Absent' => 'Absent',
	    'Late' => 'Late');


# Now Loop through all grades
my %attend;
my %genderatt;
foreach my $grade ( sort {$a <=> $b} keys %studgrade ) {
    my $ppd = $g_ppd{ $grade };
    if ( not $ppd ) {
	print qq{$lex{Missing} $lex{'Periods Per Day'}: $lex{Grade} $grade<br>\n}; 
    }

    # Students in this grade
    foreach my $studnum ( @{ $studgrade{$grade} } ) {

	my $sex = lc( $gender{$studnum});

	my $ref = calcMonthlyEnrollment( $studnum, $startdate, $enddate, $dbh );
	my %enrolYM = %$ref;
	# format:  $enrolYM{yearmonth}-> start, end, days.

	foreach my $ym ( sort keys %enrolYM ) {

	    my $result = calcMonthlyAttendance( $studnum, $ym, $ppd, '',\%lexi, $dbh );
	    # no end date req'd.
	    my ($absent, $late) = split(/:/, $result);

	    my $enrolled = $enrolYM{$ym}->{days};
	    my $present = $enrolled - $absent;

	    $attend{$grade}{$ym}->{attend} += $present;
	    $attend{$grade}{$ym}->{enrol} += $enrolled;

	    $genderatt{$grade}{$ym}{$sex}->{attend} += $present;
	    $genderatt{$grade}{$ym}{$sex}->{enrol} += $enrolled;

	}
    }
}

#use Data::Dumper;
#print Dumper %attend;
#print qq{<p></p>\n};


# Now print it out!
# First Row: Days Open, Then each grade for each month; Year:Month along the top.
print qq{<table cellspacing="0" cellpadding="3" border="1">\n};
print qq{<tr><th></th>};
foreach my $yrmo ( sort keys %schooldays ) {
    print qq{<th>$yrmo</th>};
}
print qq{<th>$lex{Total}</th></tr>\n};


# Days Open
print qq{<tr><td>$lex{'Days Open'}</td>};
my $totaldays;
foreach my $yrmo ( sort keys %schooldays ) {
    print qq{<td>$schooldays{$yrmo}</td>};
    $totaldays += $schooldays{$yrmo};
}
print qq{<td>$totaldays</td></tr>\n};


# Grades
my (%monthAtt, %monthEn);
foreach my $grade ( sort {$a <=> $b} keys %studgrade ) {
    
    my ($totalAttend, $totalEnrolled);
    print qq{<tr><td>$lex{Grade} $grade</td>};

    foreach my $yrmo ( sort keys %schooldays ) {

	my $attend =  $attend{$grade}{$yrmo}->{attend};
	my $enrolled = $attend{$grade}{$yrmo}->{enrol};

	my $boyattend =  $genderatt{$grade}{$yrmo}{'m'}->{attend};
	my $boyenrolled = $genderatt{$grade}{$yrmo}{'m'}->{enrol};

	my $girlattend =  $genderatt{$grade}{$yrmo}{'f'}->{attend};
	my $girlenrolled = $genderatt{$grade}{$yrmo}{'f'}->{enrol};


	$totalAttend += $attend;
	$totalEnrolled += $enrolled;

	$monthAtt{$yrmo} += $attend;
	$monthEn{$yrmo} += $enrolled;

	my ($boyaverage, $girlaverage);
	if ( $boyenrolled ) { 
	    $boyaverage = format_number( $boyattend / $boyenrolled * 100, 1,1); 
	}
	if ( $girlenrolled ) { 
	    $girlaverage = format_number( $girlattend / $girlenrolled * 100, 1,1); 
	}

	my $average;
	if ( $enrolled ) {
	    $average = format_number( $attend / $enrolled * 100, 1,1); 
	}

	print qq{<td>$attend / $enrolled ($average\%)<br>B:$boyaverage\% G:$girlaverage\%</td>};
    }

    # Grade totals
    my $gradeAverage;
    if ( $totalEnrolled ) { 
	$gradeAverage = format_number( $totalAttend / $totalEnrolled * 100, 1,1); 
    }
    print qq{<td>$totalAttend / $totalEnrolled ($gradeAverage\%)</td></tr>\n};

}


# Monthly Stats:
print qq{<tr style="background-color:#DDD;"><td>$lex{Month} $lex{Average}</td>};
foreach my $yrmo ( sort keys %schooldays ) {

    if ( $monthEn{$yrmo} ) { 
	$monthAverage = format_number( $monthAtt{$yrmo} / $monthEn{$yrmo} * 100, 1,1); 
    }
    print qq{<td>$monthAtt{$yrmo} / $monthEn{$yrmo} ($monthAverage\%)</td>\n};

    $gtotalAtt += $monthAtt{$yrmo};
    $gtotalEn += $monthEn{$yrmo};
}

if ( $gtotalEn ) { 
	$gtotalAverage = format_number( $gtotalAtt / $gtotalEn * 100, 1,1); 
}
print qq{<td>$gtotalAtt / $gtotalEn ($gtotalAverage\%)</td></tr>\n};


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