#!/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.

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

my %lex = ('Missing Days' => 'Missing Days',
	   'or' => 'or',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Continue' => 'Continue',
	   'Days Open' => 'Days Open',
	   'Ethnic Category' => 'Ethnic Category',
	   'Students' => 'Students',
	   'Student-Days' => 'Student-Days',
	   'Absent' => 'Absent',
	   'Enrolled' => 'Enrolled',
	   'Percentage' => 'Percentage',
	   'Attendance' => 'Attendance',
	   'Periods per Day' => 'Periods per Day',
	   'Error' => 'Error',
	   'Ethnic Attendance' => 'Ethnic Attendance',
	   'Date' => 'Date',
	   'Days' => 'Days',
	   'Main' => 'Main',

	   );


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

my $periods;
# Find largest Periods per Day (PPD) and use that.
foreach my $pd (keys %g_ppd) { # %g_ppd defined in admin.conf
    if ( $g_ppd{$pd} > $periods ) { $periods = $g_ppd{$pd}; }
}


my ($sec, $min, $hour, $mday, $mon, $year, $wday, 
 $yday, $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$year-$mon-$mday";


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

my $title = $lex{'Ethnic Attendance'};

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

if ( not $arr{page} ) { # load javascript library
    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>\n};
print qq{<body>[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$attpage">$lex{Attendance}</a> ]\n};

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


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

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

}



#-------------
sub showReport {
#-------------
    
    my $days = $arr{days};
    my $startdate = $arr{startdate};
    my $enddate = $arr{enddate};

    if ( not $days or not $startdate or not $enddate ) {
	print qq{<h3>$lex{'Missing Days'} $lex{or} $lex{Date}</h3>\n};
	print "</body></html>\n";
	exit;
    }

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


    # First Count Ethnic Categories and stuff into ethnic hash.
    my %ethnic;
    my $sth1 = $dbh->prepare("select ethnic, count(*) from student 
       where ethnic != '' and ethnic is not null group by ethnic");
    $sth1->execute;
    while ( my ( $eth, $count ) = $sth1->fetchrow ) {
	$ethnic{$eth} = $count; 
    }
    # foreach my $key ( sort keys %ethnic ) { print "K:$key  V:$ethnic{$key}<br>\n"; }


    # Now count attendance 
    my $sth = $dbh->prepare("select s.ethnic, count(a.attid) from student as s, attend as a 
			    where a.studentid = s.studnum and 
			    to_days(a.absdate) >= to_days('$startdate') and 
			    to_days(a.absdate) <= to_days('$enddate') and
			    a.reason = '$absentUnexcused'
			    group by s.ethnic");

    $sth->execute;
    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
    my %attend;
    while ( my ( $eth, $count ) = $sth->fetchrow ) {
	$attend{$eth} = $count; 
    }
    # foreach my $key ( sort keys %attend ) { print "K:$key  V:$attend{$key}<br>\n"; }


    # Print Dates, etc.
    print qq{<h1>$schoolname</h1><h3>$currdate</h3>\n};
    print qq{<p><b>$lex{'Start Date'}</b>: $startdate };
    print qq{<b>$lex{'End Date'}</b>: $enddate \n};
    print qq{<b>$lex{Days}</b>: $days\n };
    print qq{<b>$lex{'Periods per Day'}</b>: $periods</p>\n};


    # Print Attendance Table head
    print qq{<table border="0" cellspacing="0" cellpadding="4" style="border:1px solid gray;">\n};
    print qq{<tr><th>$lex{'Ethnic Category'}</th>};
    print qq{<th>$lex{Students}<br>$lex{Enrolled}</th>\n};
    print qq{<th>$lex{'Student-Days'}<br>$lex{Absent}</th>\n};
    print qq{<th>$lex{'Student-Days'}<br>$lex{Enrolled}</th>\n};
    print qq{<th>$lex{Percentage}<br>$lex{Attendance}</th></tr>\n};

    if ( not $periods) { $periods = 1; }
    foreach my $key ( sort keys %ethnic ) {
	#print "K:$key A:$attend{$key} E:$ethnic{$key}<br>\n";
	my $daysabsent = round  ( $attend{$key} / $periods), 2;
	my $daysenrol =  $ethnic{$key} * $days;
	if ( not $daysenrol ) { 
	    print qq{Days Enrol $lex{Error}: K:$key  V:$ethnic{$key}<br>\n}; 
	    $daysenrol = 100;
	}
	my $adjusted = (( $daysenrol - $daysabsent ) / $daysenrol ) * 100;
	my $percent = round $adjusted, 2;
	print qq{<tr><td class="la">$key</td><td class="cn">$ethnic{$key}</td>\n};
	print qq{<td class="cn">$daysabsent</td><td class="cn">$daysenrol</td>};
	print qq{<td class="cn">$percent</td></tr>\n};
    }

    print "</table></body></html>\n";

    exit;

} # end of showReport



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

    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{'Start Date'}</td>\n<td><input type="text" };
    print qq{name="startdate" id="sdate" size="10">};
    print qq{<button type="reset" id="start_trigger">...</button>};
    print qq{</td></tr>\n};

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

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


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

    print qq{</table>\n};
    print qq{</form>\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             // show all years in drop-down boxes
    });
   </script>\n};

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

    exit;

}
