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

#  This file is part of Open Admin for Schools.


my %lex = ('Teacher' => 'Teacher',
	   'Error' => 'Error',
	   'Main' => 'Main',
	   'Report' => 'Report',
	   'Entry' => 'Entry',
	   'Month' => 'Month',
	   'Start' => 'Start',
	   'Months' => 'Months',
	   'Continue' => 'Continue',
	   'Attendance' => 'Attendance',
	   'Week of' => 'Week of',
	   'Administration' => 'Administration',

	   );

my $self = 'rptatttch.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);


# 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 $title = "$lex{Teacher} $lex{Attendance} $lex{Entry} $lex{Report}";
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;">\n};

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


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

    my @months;
    my %months;

    my ($sy, $sm, $sd) = split('-', $schoolstart); # schoolstart is global var from config.
    my $yrmo = "$sy-$sm";
    push @months, $yrmo;
    $months{$yrmo} = "$s_month[$sm], $sy";

    for my $i (1..10) {
	my $mo = $sm + $i;
	my $yr = $sy;
	if ( $mo > 12 ) {
	    $mo = $mo - 12;
	    $yr++;
	}
	my $yrmo = "$yr-$mo";
	push @months, $yrmo;
	$months{$yrmo} = "$s_month[$mo], $yr";
    }


    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 class="ra">$lex{Start} $lex{Month}</td>};
    print qq{<td><select name="startmonth"><option></option>\n}; 

    foreach my $mo ( @months ) {
	print qq{<option value="$mo">$months{$mo}</option>\n};
    }
    print qq{</select></td></tr>\n};


    print qq{<tr><td class="ra">$lex{Months}</td>};
    print qq{<td class="la">};
    print qq{<input type="radio" name="duration" value="1" checked="checked">1 \n};
    for my $i (2..5){
	print qq{<input type="radio" name="duration" value="$i">$i&nbsp;&nbsp;\n};
    }
    print qq{</td></tr>\n};


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


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

    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}; }
    # duration(1-5), startmonth (yyyy-dd)

    # Get dow of first day of month.
    my $firstday = $arr{startmonth}. '-1';
    my $firstjd = julian_day( split('-',$firstday) );
    my $firstdow = day_of_week( $firstjd );
    my $firstmondayjd = $firstjd - ($firstdow - 1);

#    print qq{$firstday DOW:$firstdow <br>\n};
#    print qq{FirstJD:$firstjd   MondayJD:$firstmondayjd<br>\n};

    # Calculate the ending jd based on given duration.
    my ($sy, $sm) = split(/-/, $arr{startmonth});
    $sm += $arr{duration};
    if ( $sm > 12 ) {
	$sm = $sm - 12;
	$sy++;
    }
    my $endjd = julian_day($sy, $sm, '01' );


    my @mondays;
    my %mondays;

    push @mondays, $firstmondayjd;
    $mondays{$firstmondayjd} = join('-', inverse_julian_day( $firstmondayjd ));

    my $mondayjd = $firstmondayjd + 7;
    while ( $mondayjd < $endjd ) {
	push @mondays, $mondayjd;
	$mondays{$mondayjd} = join('-', inverse_julian_day( $mondayjd ));
	$mondayjd += 7;
    }
	
    
#    foreach my $jd ( @mondays ) {
#	print qq{$mondays{$jd}<br>\n};
#    }


    
    # Find current teachers that do attendance, sort by name
    my @teachers;
    my $sth = $dbh->prepare("select userid from staff 
      where doatt = 'Y' or doatt = 1 order by lastname, firstname");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $userid = $sth->fetchrow ) {
	push @teachers, $userid;
    }
    push @teachers, 'admin'; # user for admin site



    # Check for alternate teacher userids with caps in tattend table.
    my %tattuserid;
    my $sth = $dbh->prepare("select userid from tattend");
    $sth->execute;
    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $userid = $sth->fetchrow ) {
	$tattuserid{$userid} = 1;
    }

    # remove duplicates
    foreach my $tuid ( @teachers ) { delete $tattuserid{$tuid}; }
    foreach my $uid ( sort keys %tattuserid ) {
	print qq{<div>Teachers Not Found/Not Marked as Doing Attendance: };
	print qq{<b>$uid</b></div>\n};
    }



    # Get Staff Name
    my $sth1 = $dbh->prepare("select lastname, firstname from staff where userid = ?");


    # Setup Table to Display
    print qq{<table cellspacing="0" border="1" cellpadding="3">\n};
    print qq{<caption style="font-size:120%;font-weight:bold;">};
    print qq{Attendance Date ( Teacher Entry Date/Time ) Periods Entered</caption>\n};

    my $tcount = 0;

    foreach my $userid ( @teachers ) {


	if ( $tcount % 3 == 0 ) {
	    print qq{<tr><th>$lex{Teacher}</th>\n};
	    foreach my $jd ( @mondays ) {
		print qq{<th>$lex{'Week of'}<br>$mondays{$jd}</th>\n};
	    }
	    print qq{</tr>\n};
	}
	$tcount++;


	$sth1->execute( $userid );
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth1->fetchrow;
	if ( $userid eq 'admin') { $lastname = $lex{Administration}; }

	print qq{<tr><td style="vertical-align:top;" class="bla">$lastname};
	if ( $firstname ) { print qq{, $firstname};}
	print qq{ ($userid)</td>\n};

	foreach my $jd ( @mondays ) {
	    my $nextjd = $jd + 7;
	    my $mondate = join('-', inverse_julian_day( $jd ));
	    my $nextdate = join('-', inverse_julian_day( $nextjd ));

	    my $sth = $dbh->prepare("select attdate, currdate, periods from tattend 
				    where userid = ? and
				    to_days( attdate ) >= to_days('$mondate') and
				    to_days( attdate ) < to_days('$nextdate') order by attdate");
	    $sth->execute( $userid );
	    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    print qq{<td style="vertical-align:top;">};
	    while ( my ($d,$cd, $per) = $sth->fetchrow ) {
		print qq{$d ($cd) $per<br>};
	    }
	    print qq{</td>\n};
	}
	print qq{</tr>\n};

    }

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

    exit;

} # end of showReport
