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

my %lex = ('Teacher' => 'Teacher',
	   'Error' => 'Error',
	   'Main' => 'Main',
	   'Attendance' => 'Attendance',
	   'Report' => 'Report',
	   'Entry' => 'Entry',
	   'Month' => 'Month',
	   'Start' => 'Start',
	   'Months' => 'Months',
	   'Date' => 'Date',
	   'Start Date' => 'Start Date',
	   'End Date' => 'End Date',
	   'Continue' => 'Continue',
	   'Missing' => 'Missing',
	   'Grade' => 'Grade',
	   'Student' => 'Student',
	   'Enrollment' => 'Enrollment',
	   'Absent' => 'Absent',
	   'Attendance' => 'Attendance',
	   'Absent' => 'Absent',
	   'Total' => 'Total',
	   'Week of' => 'Week of',
	   'School' => 'School',
	   'Administration' => 'Administration',
	   'Please Log In' => 'Please Log In',

	   );


my $self = 'rpttattend_tch.pl';

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


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


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



# Get Session
my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

if ( not $session->param('logged_in') ){
    my $userid = $session->param('userid');
    print $session->header( -charset, $charset );
    print qq{$doctype\n<html><body>\n};
    print qq{<h1>$lex{'Please Log In'}</h1>\n};
    print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};
    exit;
}

my $userid = $session->param('userid');
my $duration = $session->param('duration');
$session->expire('logged_in', $duration );

print $session->header( -charset, $charset );


my $q = new CGI;
my %arr = $q->Vars;


# 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="$tchcss" type="text/css">\n};

print qq{$chartype\n</head><body style="padding:1em;">\n};

print qq{[ <a href="$tchpage">$lex{Main}</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{School}</td><td class="la">};
#    print qq{<select name="db"><option></option>\n};
#    foreach my $db ( @dbase ) { print qq{<option value="$db">$dbase{$db}</option>}; }
#    print qq{</select></td></tr>\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 \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{</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)

    if ( not $arr{startmonth} or not $arr{duration} ) {
	print qq{<h3>Missing Start Month or Duration</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # Get dow of first day of month.
    my $firstday = $arr{startmonth}. '-01';
    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;
    }
	
    
    # 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
    push @teachers, $userid; # from login.


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

    my $first = 1;


    foreach my $userid ( @teachers ) {

	$sth1->execute( $userid );
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname, $doatt ) = $sth1->fetchrow;
	if ( $doatt ne 'Y' or not $doatt ) { 
	    print qq{<h3>Teacher doesn't do attendance</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
	if ( $userid eq 'admin') { $lastname = $lex{Administration}; }

	if ( $first ) {
	    print qq{<table cellspacing="0" border="1" cellpadding="3">\n};
	    print qq{<caption><b>Cell Format</b> Attendance Date (Entry Date Time) Periods</caption>\n};
	    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};
	    $first = 0;
	}


	print qq{<tr><td style="vertical-align:top;"><b>$lastname</b>};
	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 * 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; }

	    my $first = 1;
	    print qq{<td style="vertical-align:top;">};
	    while ( my $r = $sth->fetchrow_hashref ) {
		if ( not $first ) { print qq{<br>\n}; } else { $first = 0; }
		print qq{$r->{attdate} };
		if ( $r->{currdate} ) { print qq{($r->{currdate}) }; }
		print qq{$r->{periods} $r->{subjects}\n};
	    }
	    print qq{</td>\n};
	}
	print qq{</tr>\n};

    }

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

    exit;

} # end of showReport
