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

my %lex = ('Attendance' => 'Attendance',
	   'Perfect Attendance' => 'Perfect Attendance',
	   'Report' => 'Report',
	   'Not Found' => 'Not Found',
	   'Name' => 'Name',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Error' => 'Error',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Main' => 'Main',
	   'Unexcused' => 'Unexcused',

	   );

my $self = 'rptAttPerf.pl';

# Get passed date for perfect attendance (inclusive)

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

# Get Current 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 $q = new CGI;
my %arr = $q->Vars;
print $q->header( -charset, $charset );


my $startdate = $arr{startdate};
my $enddate = $arr{enddate};

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


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

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;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> | <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};
    showPerfect();
}


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

    # Get start/end dates, and reasons to skip

    # Start Form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    
    # Table and Heading
    print qq{<table cellpadding="3" border="0" cellspacing="0" };
    print qq{style="border:1px solid gray;margin:0.5em;padding:0.5em;">\n\n};
    print qq{<tr><th colspan="3">Dates / Reasons to Skip</th></tr>\n};

    # Start Date
    print qq{<tr><td class="bla">Start Date \n};
    print qq{<input type="text" name="sdate" id="sdate" style="width:10ch;" value="">\n};
    print qq{<button type="reset" id="start_trigger">...</button></td></tr>\n\n};

    # End Dates
    print qq{<tr><td class="bla">End Date \n};
    print qq{<input type="text" name="edate" id="edate" style="width:10ch;" value="$currdate">\n};
    print qq{<button type="reset" id="end_trigger">...</button></td></tr>\n\n};

    my %skip;  # most have the configuration of @ignore_reason wrong, so turning this OFF.
    foreach my $idx ( @ignore_reason ) { # from configuration
	my $rsn = $attend[$idx];
	$skip{$rsn} = 1;
    }

    
    # Reasons to Skip
    print qq{<tr><td class="bla">Select Reasons to Skip</td></tr>\n};
    
    my $sth = $dbh->prepare("select distinct reason from attend order by reason");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $rsn = $sth->fetchrow ) {
	if ( $rsn =~ m/Excused/ ) { $skip{$rsn} = 1; } # skip this one, too.
	my $val = qq{R:$rsn};
	my $checked;
	if ( $skip{$rsn} ) { $checked = qq{checked="checked"}; }
	print qq{<tr><td><input type="checkbox" name="$val" value="1" $checked> $rsn</td></tr>\n};
    }

    print qq{</table>\n};
    print qq{<div><input type="submit" value="Continue"></div>\n};

    print qq{</form>\n};

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

    print qq{<script type="text/javascript">
    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 
    })};
    print qq{</script>\n};

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

    exit;

}


#--------------
sub showPerfect {
#--------------

    # foreach my $key ( sort keys %arr ) { print "K:$key V:$arr{$key}<br>\n"; }
    
    if ( not $arr{sdate} or not $arr{edate} ) {
	print qq{<h3>Missing Date</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    my $startdate = $arr{sdate};
    delete $arr{sdate};
    my $enddate = $arr{edate};
    delete $arr{edate};
    # Now only reasons to skip are left;

    my %skip;
    foreach my $key ( keys %arr ) {
	my ($dud,$reason) = split(':',$key);
	$skip{$reason} = 1;
    }

    print qq{<p><b>$lex{'Start Date'}</b>: $startdate };
    print qq{<b>$lex{'End Date'}</b>: $enddate</h3>\n};


    my $reason_string;
    print qq{<p><b>Reasons ignored</b> - \n};
    foreach my $reason ( sort keys %skip ) {
	print qq{$reason, };
	$reason_string .= "and reason != '$reason' ";
    }
    print qq{</p>\n};

    my $first = 1;

    my $sth = $dbh->prepare("select lastname, firstname, studnum, grade, homeroom from student 
			    order by lastname, firstname");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    my $noperfect = 1;  # flag in case no perfect attendance

    my %studname; # studname{studnum} = "lastname, firstname";
    my %students; # students{grade}{homeroom}{studnum} = 1;
    while ( my ($lastname, $firstname, $studnum, $grade, $homeroom ) = $sth->fetchrow ) {

	# Now do the query to find student numbers.
	$sth1 = $dbh->prepare("select count(*) from attend where studentid = ? and
			      to_days(attend.absdate) >= to_days('$startdate') and 
			      to_days(attend.absdate) <= to_days('$enddate')
			      $reason_string");
	$sth1->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth1->fetchrow;
	if ( $count < 1) {
	    $noperfect = 0;
	    if (not $homeroom) { $homeroom = 'None'; }
	    if ( not $grade) { $grade = 'Missing!'; }
	    $students{$grade}{$homeroom}{$studnum} = 1;
	    $studname{$studnum} = qq{<b>$lastname</b>, $firstname};
	}
    }

    # Loop over students hash.
    foreach my $grade ( sort {$a <=> $b} keys %students ) {
	if ( not $first ) { print qq{</table>\n}; }
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:0.5em;">\n};
	print qq{<tr><th>$lex{Name}</th><th>$lex{Grade}</th><th>$lex{Homeroom}</th></tr>\n};

	foreach my $hr ( sort {$a cmp $b} keys %{ $students{$grade}} ) {
	    my %sort;
	    foreach my $studnum ( keys %{ $students{$grade}{$hr}} ) {
		$sort{"$studname{$studnum}$studnum"} = $studnum;
	    }
	    foreach my $key ( sort keys %sort ) {
		my $studnum = $sort{$key};
		print qq{<tr><td>$studname{$studnum} / $studnum</td><td>$grade</td><td>$hr</td></tr>\n};
	    }
	}
	print qq{</table>\n};
    }
			 
    
    # In case of no perfect attendance...
    if ( $noperfect ) {
	print qq{<tr><td><b>$lex{'Perfect Attendance'} $lex{'Not Found'}</b></td></tr>\n};
    }

    print qq{</table><p>[ <a href="$attpage">$lex{Attendance}</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;
    
} # end of showPerfect;
