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

#  This file is part of Open Admin for Schools.

my %lex = ('Daily Attendance' => 'Daily Attendance',
	   'Error' => 'Error',
	   'Main' => 'Main',
	   'Date' => 'Date',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Continue' => 'Continue',
	   'Missing' => 'Missing',
	   'Grade' => 'Grade',
	   'Student' => 'Student',
	   'Enrollment' => 'Enrollment',
	   'Attendance' => 'Attendance',
	   'Absent' => 'Absent',
	   'Total' => 'Total',

	   );

my $self = 'rptattdaily.pl';

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

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

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


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

# Set Date
my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
my $day = @tim[3];
my $currdate = "$year-$month-$day";
my $currdate1 = "$month[$month] $day, $year";

my $title = $lex{'Daily Attendance'};
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="padding:1em;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{ <a href="$attpage">$lex{Attendance}</a> ] $currdate1\n};
print qq{<h1>$title</h1>\n};

if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    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" border="0" cellspacing="0">\n};

    print qq{<tr><td>$lex{'Start Date'}</td><td>};
    print qq{<input type="text" name="sdate" id="sdate" size="12">\n};
    print qq{<button type="reset" id="start_trigger">...</button></td></tr>\n};

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

    print qq{<tr><td colspan="2" style="text-align:center;">};
    print qq{<input type="submit" value="$lex{Continue}">\n};
    print qq{</td></tr>\n};

    print qq{</table></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",
        ifFormat       :    "%Y-%m-%d",
        button         :    "end_trigger",
        singleClick    :    false,
        step           :    1
    })};

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

    exit;

}


#-------------
sub showReport {
#-------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    my $schoolstartjd = julian_day( split '-', $schoolstart );
    my $schoolendjd = julian_day( split '-', $schoolend );

    my $startjd = julian_day( split '-', $arr{sdate} );
    my $endjd = julian_day( split '-', $arr{edate} );
    my $currjd = julian_day( split '-', $currdate );

    # Check Dates
    if ( $startjd < $schoolstartjd or $startjd > $schoolendjd ) {
	print qq{<h3>Starting Date is outside of school year</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    if ( $endjd < $schoolstartjd or $endjd > $schoolendjd ) {
	print qq{<h3>Ending Date is outside of school year</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    if ( $endjd < $startjd ) {
	print qq{<h3>Date Error</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # Find current enrollment.
    my $sth = $dbh->prepare("select count(*) from student");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $currenrol = $sth->fetchrow;


    # Find total transfers back to start date (including that day).
    $sth = $dbh->prepare("select count(*) from transfer where 
      to_days(date) >= to_days('$arr{sdate}')");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $transfers = $sth->fetchrow;


    # Find withdrawals back to start date (including that day).
    $sth = $dbh->prepare("select count(*) from transfer where 
      to_days(date) >= to_days('$arr{sdate}') and type = 'withdraw'");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    my $withdraws = $sth->fetchrow;

    my $enrols = $transfers - $withdraws;
    my $startenrol = $currenrol + $withdraws - $enrols;

    # print qq{Curr: $currenrol Trans: $transfers  WD: $withdraws  };
    # print qq{EN: $enrols STartEN:$startenrol<br>\n};


    # Setup Table to Display
    print qq{<table cellspacing="0" border="1" cellpadding="3">\n};
    print qq{<tr><th>$lex{Date}</th><th>$lex{Enrollment}</th><th>};
    print qq{$lex{Absent}</th><th>% $lex{Attendance}</th><th> % $lex{Absent}</tr>\n};

    # Find Max ppd to fall back on.
    my $maxppd;
    foreach my $key ( keys %g_ppd ) {
	if ( $g_ppd{$key} > $maxppd ) {
	    $maxppd = $g_ppd{$key};
	}
    }

    my $attenrol = $startenrol;

    my ( $totalenrol, $totalabsent );

    # Loop through all dates
    foreach my $attjd ( $startjd .. $endjd ) {

	my $attdate = join('-',inverse_julian_day( $attjd ) );

	# Any enrollment changes? (These could be done ANY day...)
	$sth = $dbh->prepare("select count(*) from transfer where 
          to_days(date) = to_days('$attdate')");
	$sth->execute;	
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $transfers = $sth->fetchrow;

	my ($withdraws, $enrols, $tomorrowenrol ); 
	# tomorrowenrol: enrollment at end of today, consider withdraw at end of day
 
	if ( $transfers ) { # find withdrawals
	    $sth = $dbh->prepare("select count(*) from transfer where 
              to_days(date) = to_days('$attdate') and type = 'withdraw'");
	    $sth->execute;
	    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    $withdraws = $sth->fetchrow;
	    $enrols = $transfers - $withdraws;
	}

	# update Enrollment
	$attenrol = $attenrol + $enrols; # don't consider withdraws until end of day.
	$tomorrowenrol = $attenrol - $withdraws;


	# Is today a weekday?  - Do after enrol/withdraw since they could be entered then.... 
	my $dow = day_of_week( $attjd );
	if ( $dow == 0 or $dow == 6 ) { 
	    $attenrol = $tomorrowenrol; # update enrollment for tomorrow
	    next; 
	} # skip Saturday and Sunday;


	# Is today a non session day (school is out)
	# More needed here for new dates system....
	$sth = $dbh->prepare("select count(*) from dates where to_days(date) = to_days('$attdate')");
	$sth->execute;
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $daycount = $sth->fetchrow;
	if ( $daycount ) { next; }  # skip today is not in session.
	
	# We have a school day, count the unexcused absences and their day fraction.
	$sth = $dbh->prepare("select s.grade, a.studentid from attend as a, studentall as s
			     where s.studnum = a.studentid and 
			     to_days(a.absdate) = to_days('$attdate')
			     and a.reason = '$absentUnexcused'");
	$sth->execute;
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my $absentvalue;
	while ( my ( $grade, $studnum ) = $sth->fetchrow ) {
	    my $ppd = $g_ppd{ $grade };
	    if ( not $grade ) {
		print qq{$lex{Missing} $lex{Grade} $lex{Student}: $studnum<br>\n};
		$ppd = $maxppd;
	    }
	    if ( $ppd ) {
		$absentvalue += ( 1 / $ppd );
	    }
	}

	my $fmtdate = $dow[ $dow + 1]. ", $attdate";

	$totalabsent += $absentvalue;
	$totalenrol += $attenrol;

	my $absent = format_number( $absentvalue, 2, 2);


	my $pctatt; # percent attendance
	if ( $attenrol ) {
	    $pctatt = $absentvalue / $attenrol * 100;
	} else { 
	    $pctatt = 0; 
	}
	$pctabs = format_number( $pctatt, 2, 2);
	$pctatt = 100 - $pctabs;


	# Now print attendance line;
	if ( $pctatt == 100 ) { 
	    print qq{<tr style="color:red;">}; 
	} else { 
	    print '<tr>';
	}
	print qq{<td>$fmtdate</td><td><span style="font-weight:bold;">};
	print qq{$attenrol</span> (E:$enrols W:$withdraws)</td>};
	print qq{<td>$absent</td><td>$pctatt\%</td><td>$pctabs\%</td></tr>\n};

	$attenrol = $tomorrowenrol; # update with withdrawals for tomorrow.

    }

    # Print Totals
    my $totpctatt;
    if ( $totalenrol ) {
	$totpctatt = $totalabsent / $totalenrol * 100;
    } else { 
	$totpctatt = 0; 
    }
    my $totpctabs = format_number( $totpctatt, 2, 2);
    $totpctatt = 100 - $totpctabs;

    $totalabsent = format_number( $totalabsent, 2, 2);

    print qq{<tr style="background-color:#CCC;"><td>$lex{Total}</td><td>$totalenrol</td>};
    print qq{<td>$totalabsent</td><td>$totpctatt\%</td><td>$totpctabs\%</td></tr>\n};

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

    exit;

} # end of showReport
