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

#  This file is part of Open Admin for Schools.

# Monthly report for Enrollment change.
# PDF Output

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Attendance' => 'Attendance',
	   
	   );

# 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);



# 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 = qq{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{| <a href="$attpage">$lex{Attendance}</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, %grade);
    my $sth1 = $dbh->prepare("select lastname, firstname, grade 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, $grade) = $sth1->fetchrow;
	    
	    $sort{"$ln$fn$studnum"} = $studnum;
	    $name{$studnum} = "<b>$ln</b>, $fn";
	    $grade{$studnum} = $grade;
	    
	    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};

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

	if ( $first ) {
	    print qq{<input type="submit" value="Delete Attendance Records">\n};
	    print qq{<table cellspacing="0" border="1" cellpadding="4">\n};
	    print qq{<tr><th>Student</th><th>Enrollment Blocks</th><th>Error Dates</th></tr>\n};
	    $first = 0;
	}

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

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

	print qq{<td>};
	foreach my $ref ( @enrolblocks ) {
	    my $startdate = $ref->{start};
	    my $enddate = $ref->{end};
	    print qq{ $startdate to $enddate<br>\n};
	}
	print qq{</td>};
	    
	print qq{<td style="width:60ch;">$errdates{$studnum}</td></tr>\n};

    }

    if ( not $first ) {
	print qq{</table>\n};
	print qq{<input type="submit" value="Delete Attendance Records">\n};
    } else { # no errors found
	print qq{<h3>No Errors Found</h3>\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 yr (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;

}
    
