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

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

# Check for any missing homeroom attendance up to end date.


my %lex = ('Attendance Report' => 'Attendance Report',
	   'Attendance' => 'Attendance',
	   'Continue' => 'Continue',
	   'Details' => 'Details',
	   'End Date' => 'End Date',
	   'Error' => 'Error',
	   'Homeroom' => 'Homeroom',
	   'Main' => 'Main',
	   'Missing' => 'Missing',
	   'Teacher' => 'Teacher',
    );
	     

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

# Constants
my $self = 'rptatttch2.pl';


# Get current dir so know what path for config files.
my $configpath;
my $teachermode;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.

} else {
    $configpath = '../..'; # go back two to get to etc.
}

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

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

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


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

my @tim = localtime(time);
my $year = $tim[5] + 1900;
my $month = $tim[4] + 1;
my $day = $tim[3];
my $currjd = julian_day($year,$month,$day);
if (length($month) == 1){ $month = "0".$month;}
if (length($day) == 1){ $day = "0".$day;}
my $currsdate = "$year-$month-$day";
# unused: my $currdate = "$month[$month] $day, $year";

my $schoolendjd = julian_day(split('-',$schoolend));
if ( $currjd > $schoolendjd ) {
    $currsdate = join('-', inverse_julian_day($schoolendjd));
}


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


# Get current dir so know what CSS to display and shift to teacher settings.
if ( getcwd() =~ /tcgi/ ) { # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
    $downloaddir = $tchdownloaddir;
    $webdownloaddir = $tchwebdownloaddir;
}


# HTML Header
my $title = "$lex{Teacher} $lex{'Attendance Report'} 2 (Homeroom Attendance Check)";
print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">\n};


if ( not $arr{page} ) {
    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> };
if (not $teachermode ) { 
    print qq{| <a href="$attpage">$lex{Attendance}</a> ]\n}; } else { print qq{]\n};
}
print qq{<h1>$title</h1>\n};


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

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


#------------
sub showReport {
#-------------
    
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    
    my $enddate;
    if ($arr{enddate}){
	$enddate = $arr{enddate};
    } else {
	$enddate = $currsdate;
    }


    print qq{<div><b>$lex{'End Date'}</b> $enddate</div>\n};


    # Get Homerooms
    my $sth = $dbh->prepare("select distinct homeroom from student 
      where homeroom != '' and homeroom is not NULL order by homeroom");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    my @homerooms;

    # Homeroom teacher for a particular homeroom value
    my $sth1 = $dbh->prepare("select userid from staff_multi where field_name = 'homeroom' 
       and field_value = ?");

    # Get grade(s) for particular homeroom
    my $sth2 = $dbh->prepare("select distinct grade from student where homeroom = ?");

HOMEROOM:
    while ( my $hr = $sth->fetchrow ) {

	# Do we have a teacher for this homeroom?
	$sth1->execute( $hr );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $userid = $sth1->fetchrow;
	if ( not $userid ) {
	    print qq{<div>$lex{Missing} $lex{Teacher} - $lex{Homeroom} $hr</div>\n};
	    next HOMEROOM;
	}


	# Get Grade(s) of homeroom and check that they use 'homeroom' attendance entry method
	$sth2->execute( $hr );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $gr = $sth2->fetchrow ) {
	    if ( $g_AttendanceEntryMethod{$gr} ne 'homeroom' ) { 
		print qq{<div>$lex{Error} Homeroom $hr (grade $gr) not marked for homeroom attendance.};
		print qq{</div>\n};
		next HOMEROOM; 
	    }
	}

	push @homerooms, $hr;

    } # end of homeroom loop


    @homerooms = sort {$a <=> $b} @homerooms;
    
#    print "Homerooms: @homerooms<br>\n";
    
    # print qq{<h3>Checking for Missing Attendance Entries</h3>\n};
    my $first = 1;
    my $count = 1;
    
    # Loop Through All homerooms, checking attendance
    foreach my $homeroom ( sort {$a <=> $b} @homerooms ) {

	# Check that Teacher attendance was done up to this date.
	my $res = checkAttEntry( $enddate, $homeroom );

#	print qq{<div>RES:$res End Date:$enddate HR:$homeroom</div>\n};

	if ( $res ) {
	    $count++; $first = 0; 
	    if ( $count % 5 == 1 ) { print qq{<br clear="left"><p></p>\n} };
	}
    }

    if ( $first ) { print qq{<h3>No Missing Attendance Found</h3>\n}; }
    
    print qq{</body></html>\n};

    exit;

} # end of showReport



#----------------
sub showStartPage {  # get End Date for Checking.
#----------------

    
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<table cellspacing="0" cellpadding="3" border="0">\n};


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


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

    print qq{</table></form>\n};

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

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

    exit;

}


#--------------
sub viewDetails {
#--------------

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

    print qq{<h3>View Single Teacher</h3>\n};
   
    # Check that Teacher attendance was done up to this date.
    my $res = checkAttEntry( $arr{enddate}, $arr{homeroom} );

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

    exit;

}



#----------------
sub checkAttEntry { # check attendance entry for all year to date.
#----------------

    my ($enddate, $homeroom) = @_;  # pass end date to stop at, and homeroom


    # Find partial day closures from dates_periods for entire year.
    my %pclosed;

    my $sth = $dbh->prepare("select * from dates_periods");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

    while ( my $ref = $sth->fetchrow_hashref ) {
	my %r = %$ref; # date, grades, period
	
	my $cref = parseGradesPeriod( $r{date}, $dbh);
	%cl = %$cref; # periods closed for this date cl{grade}{period} = 1
	foreach my $gr ( keys %cl ) {
	    foreach my $per ( sort keys %{ $cl{$gr} } ) { # if we have a value.
		$pclosed{ $r{date} }{ $gr }{$per} = 1;
	    }
	}
    }
    # we now have %pclosed{date}{grade}{period} = 1;

    # Test %pclosed;
=head
    foreach my $date ( sort keys %pclosed ) {
	foreach my $grade ( sort keys %{ $pclosed{$date} } ) {
	    foreach my $period ( sort keys %{ $pclosed{$date}{$grade} } ) {
		print qq{Date:$date Grade:$grade Period:$period<br>\n};
	    }
	}
    }
=cut


    # Check if attendance done by teacher
    my @missing = checkHomeroomAttEntry( $enddate, $homeroom, \%pclosed, $dbh );
    my $retval;

    if ( @missing ) {

	$retval = 1;

	# Get Teacher Name
	my $sth = $dbh->prepare("select s.lastname, s.firstname from staff s, staff_multi m 
          where s.userid = m.userid and m.field_name = 'homeroom' and m.field_value = ?");
	$sth->execute( $homeroom );
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;
	# print qq{<div>HR:$homeroom Name:$firstname $lastname</div>\n};
	
	print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;margin:0.5em;">\n};
	print qq{<caption style="font-weight:bold;width:25ch;font-size:120%;">};
	print qq{$firstname $lastname ($homeroom)</caption>\n};	
	print qq{<tr><th>Date</th><th>Period</th></tr>\n};
	
	foreach my $val ( @missing ) {
	    my ($date,$period) = split(':', $val);
	    print qq{<tr><td class="la">$date</td><td class="cn">$period</td></tr>\n};
	}

	print qq{<tr><td colspan="2">\n};
	print qq{<form action="$self" method="post" style="display:inline;">\n};
	print qq{<input type="hidden" name="page" value="2">\n};
	print qq{<input type="hidden" name="homeroom" value="$homeroom">\n};
	print qq{<input type="hidden" name="userid" value="$userid">\n};
	print qq{<input type="hidden" name="enddate" value="$enddate">\n};
	print qq{<input type="submit" value="$lex{Details}"></form>\n};
	print qq{</td></tr>\n};

	
	print qq{</table>\n};

    }

    
    return $retval;
    
}
