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

# Monthly report for Enrollment change.
# PDF Output

my %lex = ('Monthly Enrollment' => 'Monthly Enrollment',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Main' => 'Main',
	   'Blank=Previous Month' => 'Blank=Previous Month',
	   'No Enrollment Changes' => 'No Enrollment Changes',
	   'Student' => 'Student',
	   'Reason' => 'Reason',
	   'Principal' => 'Principal',
	   'Grade' => 'Grade',
	   'Error' => 'Error',
	   'Continue' => 'Continue',
	   'Month' => 'Month',
	   'Paper Size' => 'Paper Size',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Font Size' => 'Font Size',
	   'Report' => 'Report',
	   'Days Open' => 'Days Open',
	   'Homeroom' => 'Homeroom',
	   'Missing' => 'Missing',
	   'Periods Per Day' => 'Periods Per Day',
	   
	   );

# show Principal Signature Line; set to 0 to turn off
my $principalSign = 1;

my $self = 'attenrolfix.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";
}

eval require "../../lib/libattend.pl";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@<br>\n";
}


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


# Database setup
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 $cyear = @tim[5] + 1900;
my $cmonth = @tim[4] + 1;
my $cday = @tim[3];
my $currdate = "$cyear-$cmonth-$cday";
my $currjd = julian_day( split('-', $currdate) );
my $curryrmo = "$cyear-$cmonth";


# Print Page Head.
my $title = "Fix Attendance Outside Enrollments Error";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};

print qq{$chartype\n</head><body style="padding:1em 2em;">\n};
print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};

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

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

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


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

    # Get all students in attendance, check for errors.
    my (%sort, %name, %errdates);
    my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    my $sth = $dbh->prepare("select distinct studentid from attend");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    
    while ( my $studnum = $sth->fetchrow ) {
	
	my @err = checkAttendanceOutsideEnrollment( $studnum, $schoolstart, $schoolend, $dbh, 0);
	
	if ( $err[0] ) {

	    # Get Name
	    $sth1->execute( $studnum );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }	    
	    my ($ln, $fn) = $sth1->fetchrow;
	    
	    $sort{"$ln$fn$studnum"} = $studnum;
	    $name{$studnum} = "<b>$ln</b>, $fn";
	    
	    my $err = join(',',@err);
	    $errdates{$studnum} = $err;
	}
    }

    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="submit" value="Delete Attendance Records">\n};
    
    print qq{<table cellspacing="0" border="1" cellpadding="3">\n};
    print qq{<tr><th>Student</th><th>Enrollment Blocks</th><th>Error Dates</th></tr>\n};

    
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};

	# Get the enrollment blocks.
	my @enrolblocks = findEnrollmentBlocks( $studnum, $schoolstart,$schoolend, $dbh );

	
	print qq{<tr><td><input type="checkbox" name="$studnum" value="$errdates{$studnum}"> $name{$studnum} ($studnum)</td>\n};

	print qq{<td>};
	foreach my $ref ( @enrolblocks ) {
	    my $startdate = $ref->{start};
	    my $enddate = $ref->{end};
	    print qq{ $startdate<b>TO</b>$enddate <b>/</b>};
	}
	print qq{</td>};
	    
	print qq{<td>$errdates{$studnum}</td></tr>\n};

    }

    print qq{</table>\n};
    print qq{<input type="submit" value="Delete Attendance Records">\n};
    print qq{</form>\n};


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

    exit;

}


#---------------
sub deleteErrors {
#---------------

    #foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

     my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
     
     my $sth = $dbh->prepare("delete from attend where absdate = ? and studentid = ?");

     foreach my $studnum ( keys %arr ) {
	 
	 my @dates = split(',',$arr{$studnum});
	 foreach my $date ( @dates ) {
#	     print "SN:$studnum Date:$date<br>\n";
	     $sth->execute($date, $studnum);
	     if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	 }

	 $sth1->execute($studnum);
	 if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	 my ($lastname, $firstname) = $sth1->fetchrow;

	 print qq{<div>$firstname $lastname Fixed</div>\n};
	 
     }

    print qq{[ <a href="$homepage">$lex{Main}</a> ]\n};
    print qq{</body></html>\n};

    exit;
}
    

#-----------------------------------
sub checkAttendanceOutsideEnrollment {  # check errors in the current school year (schoolstart,schoolend)
#-----------------------------------

    # use Time::JulianDay;

    # Passed: student number, start and end dates for period of interest.
    my ( $studnum, $startdate, $enddate, $dbh, $showerror ) = @_;

    # find enrollment blocks for this time period
    my @enrolblocks = findEnrollmentBlocks( $studnum, $startdate,$enddate, $dbh );

    if ( not $enrolblocks[0] ) { # print "No Enrollment for $studnum<br>\n"; 
	return undef; 
    }

    # Loop through each enrollment block
    my @blockjd; 
    foreach my $ref ( @enrolblocks ) {
	my $startdate = $ref->{start};
	my $enddate = $ref->{end};

#	print "Studnum:$studnum Start:|$startdate| End:|$enddate|<br>\n";

	my $startjd = julian_day( split('-', $startdate) );
	my $endjd = julian_day( split('-', $enddate) );

	push @blockjd, "$startjd:$endjd";
    }
    my $bcount = @blockjd; # block count to make sure we have that many attendance errors.

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

    
    my $errorflag;
    my %errdates;
    # now loop through attendance for this student to see if any absences records outside enrollment blocks.
    my $sth = $dbh->prepare("select absdate from attend where studentid = ? and 
       absdate is not NULL and absdate != '0000-00-00' order by absdate");
    $sth->execute( $studnum );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    while ( my $absdate = $sth->fetchrow ) {
	my $absjd = julian_day( split('-', $absdate) );

	my $ecount; # error count
	foreach my $bval ( @blockjd ) {
	    my ($start,$end) = split(':', $bval);
	    if ( $absjd < $start or $absjd > $end ) { # error
		$ecount++;
	    }
	}
	if ( $ecount >= $bcount ) { # date must be outside of all enrollment blocks (ie. errorcount = blockcount)
	    $errdates{$absdate} = 1;
	}
    }

    my @errdates;
    if ( %errdates ) {
	@errdates = sort keys %errdates;
    }
    
    return @errdates;

}
    
