#!/usr/bin/perl
#  Copyright 2001-2010 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 = ('Attendance Confirmation' => 'Attendance Confirmation',
	   'Main' => 'Main',
	   'Student' => 'Student',
	   'Subject' => 'Subject',
	   'Reason' => 'Reason',
	   'Period' => 'Period',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'Attendance Reasons' => 'Attendance Reasons',
	   'Date' => 'Date',
	   'Error' => 'Error',
	   'Late' => 'Late',
	   'Minutes' => 'Minutes',
	   'Continue' => 'Continue',
	   'Add' => 'Add',
	   'Missing' => 'Missing',
	   'Save' => 'Save',
	   'Duplicate' => 'Duplicate',
	   'Attendance Records' => 'Attendance Records',
	   'Method' => 'Method',
	   
	   );

my $self = 'tattentry1.pl';

use DBI;
use CGI;

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;

# Database setup
my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;


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


my $date;
if ( $arr{date} =~ m/,/ ) { #if it contains a comma
    ( my $dud, $date ) = split(/,/ ,$arr{date} );
    $date =~ s/^\s*//;  # strip leading space
} else {
    $date = $arr{date};
}
delete $arr{date};



my $method = $arr{method};
delete $arr{method};

my $latemode = $arr{latemode};
delete $arr{latemode};

# Not sure if any role for this...
my $userid = $arr{name};
delete $arr{name};


# Print Start of HTML Page
print "$doctype\n<html><head><title>$lex{'Attendance Confirmation'}</title>
<link rel=\"stylesheet\" href=\"$tchcss\" type=\"text/css\">
</head><body>[ <a href=\"$tchpage\">$lex{Main}</a> ]\n";

print "<center><h1>$lex{'Attendance Confirmation'}</h1>\n";
print "<p><b>$date</b></p>\n";

# Test Section
#print "</center>\n";
#foreach $key ( sort keys %arr ) { 
#   if ( $arr{$key} ) { print "K:$key V:$arr{$key}<br>\n"; }
#}


if ( $latemode ) { # Add Lates/Reasons
    addLates();
}


# Start of Form
print "<form action=\"tattentry2.pl\" method=\"post\">
<input type=\"hidden\" name=\"method\" value=\"$method\">
<input type=\"hidden\" name=\"date\" value=\"$date\">\n";


my $noReasonFlag;
my $duplicateRecordFlag;

print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"5\">\n";
print "<tr><th>$lex{Student}</th><th>$lex{Subject}</th>\n";
print "<th>$lex{Reason}</th><th>$lex{Period}</th><th>$lex{Date}</th>\n";
print "<th>$lex{Late}</th></tr>\n";


my $sth1 = $dbh->prepare("select count(*) from attend where studentid = ? and absdate = ? and period = ?");

# === SUBJECT Method ===========
if ( $method eq 'subject' ) {

SUBKEY:
    foreach $key ( sort keys %arr ) {
	if ( $arr{$key} ) {
	    my ( $studnum, $subjsec, $period, $val ) = split(/:/,$key);
	    if ( $val eq 'Reason' or $val eq 'Late' ) { next; } # skip these

	    # get reason 
	    my $rsnindex = "$studnum:$subjsec:$period:Reason";
	    my $reason = $arr{$rsnindex};

            if ( not $reason ) { # use undefined period mode
	      $rsnindex = "$studnum:$subjsec". "::Reason"; # Watch ::
	      $reason = $arr{$rsnindex};
            }       

	    # print "SN:$studnum SUB:$subjsec PER:$period  RSN:$reason<br>\n";

	    if (not $reason) {
		$noReasonFlag = 1;
		push @noReason, "$key:$date";  # studnum:subjsec:period:date
	    }

	    # get any late minutes
	    my $lateindex = "$studnum:$subjsec:$period:Late";
	    my $late = $arr{$lateindex};


	    # Check for an existing attendance record.
	    $sth1->execute( $studnum, $date, $period );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; } 
	    my $count = $sth1->fetchrow;
	    # print "Count: $count  SN:$studnum D:$date  P:$period<br>\n";
	    
	    if ( $count > 0 ) { # we have an existing record...  
		$duplicateRecordFlag = 1; 
		push @duplicateRecords, "$studnum:$period:$date:$subjsec";
	    }

	    if ( $count > 0 or not $reason ) { # skip to next record
		next SUBKEY;
	    }


	    # Now find the student name, not studentall since won't show for attendance anyway
	    $sth = $dbh->prepare("select lastname,firstname from student where studnum = ?");
	    $sth->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname, $firstname) = $sth->fetchrow;

	    my $studname;
	    if ( not $lastname ) { # No student found....
		$studname = "<span style=\"color:red;\">$lex{'No Student(s) Found'}</span>";
	    } else { # we have a student
		$studname = "<b>$lastname</b>, $firstname ($studnum)";
	    }

	    # Now find the subject description
	    $sth = $dbh->prepare("select description from subject where subjsec = ? ");
	    $sth->execute( $subjsec );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $description = $sth->fetchrow;


	    print "<tr><td>$studname</td><td>$description</td><td>$reason</td>\n";
	    print "<td>$period</td><td>$date</td><td>$late</td></tr>\n";
	    print "<input type=\"hidden\" name=\"$studnum:$period:$subjsec:$reason:$late:$date\" value=\"1\">\n";
	    
	} # End of If: we have a passed value

    } # End of ForEach Loop (each value in %arr hash)

} # end of SUBJECT method


# === Homeroom Method ===========
if ( $method eq 'hroom' ) {

    foreach my $key ( sort keys %arr) {
	if ( $arr{$key} ) { # if we have a value

	    my ( $studnum, $period, $val ) = split(/:/,$key );
	    if ( $val eq 'Reason' or $val eq 'Late' ) { next; } # skip these	    

	    my ( $reason, $last, $reasonidx, $lateidx );
	    if ( $arr{"$studnum:\:Reason"} ) {
		$reason = $arr{"$studnum:\:Reason"};
		$lateidx = "$studnum:\:Late";
		$late = $arr{$lateidx};

	    } elsif ( $arr{"$studnum:$period:Reason"} ) {

		$reason = $arr{"$studnum:$period:Reason"};
		$lateidx = "$studnum:$period:Late";
		$late = $arr{$lateidx};
	    } else {
		print "<p>$lex{Error}: $lex{Missing} Index</p>\n";
		exit;
	    }


#	    print "R: $reasonidx $reason L:$lateidx $late<br>\n";

	    if ( not $reason ) {
		$noReasonFlag = 1;
		push @noReason, "$studnum:\:$period:$date";  # studnum:subjsec:period:$date
	    }

	    # Check for an existing attendance record.
	    $sth1->execute( $studnum, $date, $period ); 
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; } 
	    my $count = $sth1->fetchrow;
	    # print "Count: $count  SN:$studnum D:$date  P:$period<br>\n";

	    if ( $count > 0 ) { # we have an existing record...  
		$duplicateRecordFlag = 1; 
		push @duplicateRecords, "$studnum:$period:$date:$subjsec"; 
	    }

	    if ( $count > 0 or not $reason ) {
		next;
	    }

	    $sth = $dbh->prepare("select lastname, firstname from student where studnum = ?");
	    $sth->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname ) = $sth->fetchrow;

	    if ( not $lastname ) { # No student found....
		$studname = "<span style=\"color:red;\">$lex{'No Student(s) Found'}</span>";
	    } else { # we have a student
		$studname ="$lastname, $firstname ($studnum)";
	    }

	    print "<tr><td>$studname</td><td></td><td>$reason</td><td>$period</td>";
	    print "<td>$date</td><td>$late</td></tr>\n";
	    print "<input type=\"hidden\" name=\"$studnum:$period:\:$reason:$late:$date\" ";
	    print "value=\"1\">\n";
    
	} # End of If
    } # End of %arr Loop

} # end of homeroom method



# === Multi-Day Method ===========
if ($method eq 'multiday') {

MULTIKEY:
    foreach $key ( sort keys %arr ) {
	if ( $arr{$key} ) {

	    my ($studnum,$date,$period, $val) = split(/:/,$key);
	    if ( $val eq 'Reason' or $val eq 'Late' ) { next; } # skip these

	    # get reason 
	    my $rsnindex = "$studnum:$date:$period:Reason";
	    my $reason = $arr{$rsnindex};

	    # get any late minutes
	    my $lateindex = "$studnum:$date:$period:Late";
	    my $late = $arr{$lateindex};
	    

	    # Check for reason.
	    if ( not $reason ) {
		$noReasonFlag = 1;
		push @noReason, "$studnum:\:$period:$date";  # studnum:subjsec:period:date
	    }

	    # Check for an existing attendance record.
	    $sth1->execute( $studnum, $date, $period ); 
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; } 
	    my $count = $sth1->fetchrow;
	    # print "Count: $count  SN:$studnum D:$date  P:$period<br>\n";

	    if ( $count > 0 ) { # we have an existing record...  
		$duplicateRecordFlag = 1; 
		push @duplicateRecords, "$studnum:$period:$date:$subjsec"; 
	    }

	    if ( $count > 0 or not $reason ) { # skip to next record.
		next MULTIKEY;
	    }

	    my $sth = $dbh->prepare("select lastname, firstname from student where studnum = ?");
	    $sth->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname ) = $sth->fetchrow;

	    if ( not $lastname ) { # No student found....
		$studname = "<span style=\"color:red;\">$lex{'No Student(s) Found'}</span>";
	    } else { # we have a student
		$studname ="$lastname, $firstname ($studnum)";
	    }

	    print "<tr><td>$studname</td><td></td><td>$reason</td><td>$period</td>";
	    print "<td>$date</td><td>$late</td></tr>\n";
	    print "<input type=\"hidden\" name=\"$studnum:$period:\:$reason:$late:$date\" ";
	    print "value=\"1\">\n";

	} # 
    } # each value in %arr hash
} # end of Multi-Day method


# Sequence for the colon separated fields above:
# Studnum:Period:Subjsec:Reason:Late:Date



# If missing reason, fail here....
if ( $noReasonFlag ) {

    print "<tr><td colspan=\"6\" align=\"center\" style=\"color:red;\"><b>";
    print "$lex{Missing} $lex{'Attendance Reasons'}</b></td></tr>\n";

    my $sth = $dbh->prepare("select lastname,firstname from student where studnum = ?");
    my $sth1 = $dbh->prepare("select description from subject where subjsec = ?");

    foreach my $rec ( @noReason ) {
	my ($studnum, $subjsec, $period, $date) = split(/:/, $rec );

	# Now find the student name
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;

	# Now find the subject name ( if subjsec exists )
	my $description;
	if ( $subjsec ) {
	    $sth1->execute( $subjsec );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    $description = $sth1->fetchrow;
	}

	print "<tr><td><b>$lastname</b>, $firstname ($studnum)</td>\n";
	print "<td>$description ($subjsec)</td>\n"; 
	print "<td></td><td>$period</td><td>$date</td><td>$late</td></tr>\n";
	
    }

} # End of noReasonFlag


if ( $duplicateRecordFlag ) {

    print "<tr><td colspan=\"6\" align=\"center\" style=\"color:red;\"><b>";
    print "$lex{Duplicate} $lex{'Attendance Records'}</b></td></tr>\n";

    my $sth = $dbh->prepare("select lastname,firstname from student where studnum = ?");
    my $sth1 = $dbh->prepare("select description from subject where subjsec = ?");

    foreach my $rec ( @duplicateRecords ) {
	my ($studnum, $period, $date, $subjsec) = split(/:/, $rec );

	# Now find the student name
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;

	# Now find the subject name (if subjsec exists)
	my $description;
	if ( $subjsec ) {
	    $sth1->execute( $subjsec );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    $description = $sth1->fetchrow;
	}

	print "<tr><td><b>$lastname</b>, $firstname ($studnum)</td>\n";
	if ($subjsec) {  
	    print "<td>$description ($subjsec)</td>\n"; 
	} else { 
	    print "<td></td>"; 
	}

	print "<td></td><td>$period</td><td>$date</td><td>$late</td></tr>\n";
	
    }

} # End of duplicateRecords



# If we have one or both above.... close forms and finish page
if ( $duplicateRecordFlag or $noReasonFlag ) {
    print "</table></form></center></body></html>\n";

} else {    
    print "<tr><td colspan =\"6\" style=\"text-align:center;\">\n";
    print "<input type=\"submit\" value=\"$lex{Save} $lex{'Attendance Records'}\"></td></tr>\n";
    print "</table></form></center></body></html>\n";

}



#-----------
sub addLates {
#-----------

    # Test Section
    # print "</center>\n";
    # foreach my $key ( sort keys %arr ) {
    # 	if ( $arr{$key} ) { print "K:$key V:$arr{$key}<br>\n"; }
    # }

    print "<div style=\"font-weight:bold;font-size:120%;\">". $lex{Add}. q{ };
    print $lex{Minutes}. q{ }. $lex{Late}. "</div>\n";

    # Start Form
    print "<form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"method\" value=\"$method\">\n";
    print "<input type=\"hidden\" name=\"date\" value=\"$date\">\n";

    # Print Table Header.
    print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"5\">\n";
    print "<tr><th>". $lex{Student}. "</th>";
    print "<th>". $lex{Subject}. "</th>\n"; 
    print "<th>". $lex{Reason}. "</th><th>". $lex{Period}. "</th>";
    print "<th>". $lex{Date}. "</th><th>\n"; 
    print $lex{Minutes}. q{<br>}. $lex{Late}. "</th></tr>\n";


    my $sth = $dbh->prepare("select lastname,firstname from student where studnum = ?");
    my $sth1 = $dbh->prepare("select description from subject where subjsec = ? ");

    # Format: $studnum:$subjsec:$period:$reason -- we add the late or alt reason
    foreach my $key ( sort keys %arr ) {

	if ( $arr{$key} ) { # if we have a value

	    # Setup variables
	    my ( $studnum, $subjsec, $period, $reason );
	    my ($reasonkey, $lastkey );

	    if ( $method eq 'hroom' ) {
		( $studnum, $period, $val ) = split(/:/, $key);
		if ( $val eq 'Reason' ) { next; }
		$reasonkey = "$studnum:\:Reason";
		$reason = $arr{$reasonkey};
		
		$reasonkey = "$studnum:$period:Reason";
		$latekey = "$studnum:$period:Late";

	    } elsif ( $method eq 'subject' ) {

		( $studnum, $subjsec, $period, $val ) = split(/:/, $key );
		if ( $val eq 'Reason' ) { next; }
		$reasonkey = "$studnum:$subjsec:$period:Reason";
		$reason = $arr{$reasonkey};

		$latekey = "$studnum:$subjsec:$period:Late";

	    } elsif ( $method eq 'multiday' ) {

		( $studnum, $date, $period ) = split(/:/, $key);

		$reasonkey = "$studnum:$date:$period:Reason";
		$latekey = "$studnum:$date:$period:Late";

	    } else { # an error
		print "<p>$lex{Error}: $lex{Missing} $lex{Method}</p>\n";
		print "</body></html>\n";
		exit;
	    }

	    # print original record, w/o change.
	    print "<input type=\"hidden\" name=\"$key\" value=\"$arr{$key}\">\n";


	    # Get student name
	    my $studname;
	    $sth->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname, $firstname) = $sth->fetchrow;
	    if ( not $lastname ) { # No student found....
		$studname = "<span style=\"color:red;\">$lex{'No Student(s) Found'}</span>";
	    } else { # we have a student
		$studname = "<b>$lastname</b>, $firstname ($studnum)";
	    }

	    # Now find the subject description
	    my $description;
	    if ( $subjsec ) {
		$sth1->execute( $subjsec );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		$description = $sth1->fetchrow;
	    }

	    print "<tr><td>$studname</td><td>$description</td>\n";
	    print "<td><select name=\"$reasonkey\">";
	    print "<option>$reason</option>\n";
	    foreach my $rsn ( @attend ) { 
		if ( $rsn ne $reason ) { print "<option>$rsn</option>\n";}
	    }
	    print "</select></td><td>$period</td><td>$date</td>\n";
	    print "<td><input type=\"text\" name=\"$latekey\" size=\"6\"></td></tr>\n";
	    
	} # end of %arr loop.
    }

    print "<tr><td colspan=\"6\" style=\"text-align:center;\">\n";
    print "<input type=\"submit\" value=\"";
    print $lex{Continue}. "\"></td></tr>\n";
    print "</table></form>\n";

    print "</body></html>\n";

    exit;
    
} # end of addLates
