#!/usr/bin/perl
#  Copyright 2001-2020 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 = ('Edit' => 'Edit',
	   'Teacher' => 'Teacher',
	   'Attendance' => 'Attendance',
	   'Main' => 'Main',
	   'Delete' => 'Delete',
	   'Error' => 'Error',
	   'Student' => 'Student',
	   'Grade' => 'Grade',
	   'Select' => 'Select',
	   'Records' => 'Records',
	   'Updated' => 'Updated',
	   'Continue' => 'Continue',

	   'All' => 'All',
	   'Fields' => 'Fields',
	   'Students' => 'Students',
	   'Homeroom' => 'Homeroom',
	   'Check' => 'Check',
	   'Next Page' => 'Next Page',
	   'Blank=All' => 'Blank=All',
	   'Name' => 'Name',
	   'Moved' => 'Moved',
	   'Not Found' => 'Not Found',
	   'Record' => 'Record',
	   'Group' => 'Group',
	   'Save' => 'Save',

	   'Months' => 'Months',
	   
	   );


use DBI;
use CGI;

my $self = 'tattEdit.pl';

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

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


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

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



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

my $userid;  # no need for session, just get userid.
if ( not defined $arr{userid} ) {
    $userid = $ENV{'REMOTE_USER'};
} else {
    $userid = $arr{userid};
}


# Print Page Header
my $title = "$lex{Edit}/$lex{Delete} $lex{Attendance}";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$tchcss" type="text/css">\n};

if ( $arr{page} == 2 ) {
    # Setup for Calendar popup.
    print qq{<link rel="stylesheet" type="text/css" media="all" href="/js/calendar-blue.css" };
    print qq{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{<style type="text/css">input { margin:0.4em; }</style>\n};
print qq{$chartype\n</head><body>\n};

print qq{[ <a href="$tchpage">$lex{Main}</a> ] Userid:$userid\n};
print qq{<h1>$title</h1>\n};


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

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    selectStudents();

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    delEditStudents(); # delete immediately, then show Edit forms.

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    updateRecords(); # update any record edits.
}



#----------------
sub showStartPage { # Select Month or Student.
#----------------

    # get teacher's homerooms.
    my @homerooms;
    my $sth = $dbh->prepare("select field_value from staff_multi where userid = ? 
      and field_name = 'homeroom'");
    $sth->execute( $userid );
    while ( my $hr = $sth->fetchrow ) {
	push @homerooms, $hr;
    }

    if ( not @homerooms ) {
	print qq{<h3>No Homerooms Found</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    my $sth = $dbh->prepare("select studnum from student where homeroom = ?");
    my $sth1 = $dbh->prepare("select distinct year(absdate), month(absdate) 
      from attend where studentid = ?");
    
    my (@students, %yrmo); # select attendance by student or year-month.
    foreach my $hr ( @homerooms ) {
	$sth->execute($hr);
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	while ( my $studnum = $sth->fetchrow ) {
	    push @students, $studnum;

	    # get their year-month absences.
	    $sth1->execute($studnum);
	    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my ($year,$month) = $sth1->fetchrow ) {
		if ( length $month == 1 ) { $month = '0'. $month; }
		my $yrmo = qq{$year-$month};
		$yrmo{$yrmo} = 1;
	    }
	}
    }

    my $hrooms = join(',',@homerooms); # for passing to next script.

    
    # get sorted students and names.
    my (%sort, %name);
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    foreach my $studnum ( @students ) {
	$sth->execute($studnum);
	my ($lastname, $firstname) = $sth->fetchrow;
	$sort{"$lastname$firstname$studnum"} = $studnum;
	$name{$studnum} = qq{<b>$lastname</b>, $firstname};
    }
    

    # Notes
    print qq{<div>If you select:<ul style="margin:0.4em;">\n};
    print qq{<li><b>Students Only</b>, you will see all his/her records.</li>\n};
    print qq{<li><b>Months Only</b>, you will see all homeroom records for those months.</li>\n};
    print qq{<li><b>Both Students and Months</b>, you will see the students records for };
    print qq{those months, split by student.</li>\n};
    print qq{</ul></div>\n};
   
 
    # Start the form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="homerooms" value="$hrooms">\n};
    

    print qq{<div style="text-align:left"><input type="submit" value="$lex{Continue}"></div>\n};

        
    # Display Students
    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;">\n};
    print qq{<tr><th>$lex{Select} $lex{Students}</th></tr>\n};
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	print qq{<tr><td><input type="checkbox" name="s:$studnum">$name{$studnum}</td></tr>\n};
    }
    print qq{</table>\n};

    
    # Display Year-Months.
    print qq{<table cellpadding="3" cellspacing="0" border="1" style="float:left;">\n};
    print qq{<tr><th>$lex{Select} $lex{Months}</th></tr>};
    foreach my $yrmo ( sort keys %yrmo ) {
	my ($yr,$mo) = split '-', $yrmo;
	print qq{<tr><td><input type="checkbox" name="yrmo:$yrmo">$month[$mo] $yr</td></tr>\n};
    }
    print qq{</table>\n};
    
   
    # Continue
    print qq{<br clear="left">\n};
    print qq{<p style="text-align:left"><input type="submit" value="$lex{Continue}"></p>\n};
    print qq{</form></body></html>\n};

    exit;

}


#-----------------
sub selectStudents {
#-----------------

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


    # values passed:yrmo type is year-month, s is student;

    my $hrooms = $arr{homerooms};
    delete $arr{homerooms};
    my @homerooms = split(',',$hrooms);
    

    my (@yrmo, @students, %sort, %studname );


    foreach my $key ( keys %arr ) {
	my ($type, $val) = split(':', $key);
	if ( $type eq 's' ) { push @students, $val; }
	if ( $type eq 'yrmo' ) { push @yrmo, $val; }
    }

    
    if ( not @students and not @yrmo ) {
	print qq{<h3>No Selection</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    my $mode = 'student'; # student, month, both
    if ( @students and @yrmo ) {
	$mode = 'both';
    } elsif ( @yrmo ) {
	$mode = 'month';
    }
    
    # Students.
    if ( $mode eq 'month' )  { # no students selected; we'll need all students for search by month
	
	my $sth = $dbh->prepare("select studnum from student where homeroom = ?");
	foreach my $hr ( @homerooms ) {
	    $sth->execute($hr);
	    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $studnum = $sth->fetchrow ) {
		push @students, $studnum;
	    }
	}

    }

    # get names, sort order.
    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    foreach my $studnum ( @students ) {
	$sth->execute( $studnum );
	if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname ) = $sth->fetchrow;
	$sort{"$lastname$firstname$studnum"} = $studnum;
	$studname{$studnum} = "<b>$lastname</b>, $firstname";
    }


	
    # Students and Year-Month.
    my %attendance; # attendance{studnum}{date}{id};

    if ( $mode eq 'both' or $mode eq 'month' ) {

	my $sth = $dbh->prepare("select attid, absdate from attend where studentid = ? and 
           year(absdate) = ? and month(absdate) = ?");
	
	foreach my $studnum ( @students ) {
	    foreach my $yrmo ( @yrmo ) {
		my ($year,$month) = split('-', $yrmo);
	
		$sth->execute( $studnum, $year, $month );
		if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		while ( my ($id, $date) = $sth->fetchrow ) {
		    $attendance{$studnum}{$date}{$id} = 1;
		}
	    }
	}
	
        
    } else  { # Students Only; no months selected; all records for each.

	my $sth = $dbh->prepare("select attid, absdate from attend 
           where studentid = ? order by absdate"); 
	
	foreach my $studnum ( @students ) {
	    $sth->execute( $studnum );
	    if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ($id, $date) = $sth->fetchrow;

	    $attendance{$studnum}{$date}{$id} = 1;
	}

    } # end of students only
	

=head
    foreach my $studnum ( sort keys %attendance ) {
	foreach my $date ( sort keys %{ $attendance{$studnum} } ) {
	    foreach my $id ( sort {$a <=> $b} keys %{ $attendance{$studnum}{$date} } ) {
		print "SN:$studnum Date:$date ID:$id<br>\n";
	    }
	}
    }
=cut


    # Start the form.
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};

    
    # Get Records for Edit/Delete
    my $first = 1;
    my $count = 1;
    
    my $sth = $dbh->prepare("select * from attend where attid = ?");
    
    # Loop over all students.
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};

	foreach my $date ( sort keys %{ $attendance{$studnum} } ) {

	    foreach my $id ( sort {$a <=> $b} keys %{ $attendance{$studnum}{$date} } ) {

#		print qq{Studnum:$studnum Date:$date ID:$id<br>\n};

		if ( $first ) { # start table layout.
		    print qq{<div><input type="submit" value="Continue"></div>\n};
		    print qq{<table cellpadding="3" border="1" cellspacing="0">\n};
		    print qq{<caption>No Confirmation on Delete. Immediately Removed.</caption>\n};
		    print qq{<tr><th>$lex{Student}</th><th>Edit</th><th>Delete</th>};
		    print qq{<th>Date/Period</th><th>Reason</th></tr>\n};
		    $first = 0;
		}

		$sth->execute( $id );
		if ( DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		my $ref = $sth->fetchrow_hashref;
		my %r = %$ref;

		print qq{<tr><td>$count. $studname{$studnum} ($studnum)</td>};
		print qq{<td class="cn"><input type="radio" name="$id" value="E"></td>\n};
		print qq{<td class="cn"><input type="radio" name="$id" value="D"></td>\n};
		print qq{<td>$r{absdate} / $r{period}</td><td>$r{reason}</td></tr>\n};

		$count++;
		if ( $count % 10 == 0 ) { # put in title line
		    print qq{<tr><th>$lex{Student}</th><th>Edit</th><th>Delete</th>};
		    print qq{<th>Date/Period</th><th>Reason</th></tr>\n};
		}
		
	    } # end of id loop
	} # end of date loop
    } # end of student loop


    print qq{</table>\n};
    print qq{<div><input type="submit" value="Continue"></div>\n};

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


} # end of selectStudents / months



#------------------
sub delEditStudents {
#------------------

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

    # setup selects
    my $sth = $dbh->prepare("select * from attend where attid = ?");
    my $sth1 = $dbh->prepare("delete from attend where attid = ?");
    my $sth2 = $dbh->prepare("select lastname, firstname, grade from studentall where studnum = ?");

    print qq{<h2>Delete Attendance Records</h2>\n};
    my $first = 1;
    foreach my $id ( keys %arr ) {
	if ( $arr{$id} eq 'D' ) { # delete
	    
	    # get record
	    $sth->execute($id);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth->fetchrow_hashref;
	    my %r = %$ref;

	    # get name, grade (not needed yet)
	    $sth2->execute( $r{studentid} );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname,$firstname, $grade) = $sth2->fetchrow;

	    # delete record from attend table.
	    
	    $sth1->execute($id);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    print qq{<div><b>Deleted $firstname $lastname</b> on $r{absdate}, period $r{period} };
	    print qq{for $r{reason}</div>\n};

	    # delete from %arr hash
	    delete $arr{$id};
	    
	}
    }
    if ( $first ) { print qq{<h3>No Attendance Deletion</h3>\n}; }
    
    
    # now do the edits.

    print qq{\n\n<h2>Edit Attendance Records</h2>\n};
    my $first = 1;
    my %absdate; # $absdate{$id} = $absdate
    
    foreach my $id ( keys %arr ) {
	if ( $arr{$id} eq 'E' ) { # edit, likely redundant since deletes are done.
    
	    # get record
	    $sth->execute($id);
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth->fetchrow_hashref;
	    my %r = %$ref;
	    $absdate{$id} = $r{absdate}; # used below for calendar

	    # get name, grade
	    $sth2->execute( $r{studentid} );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname,$firstname, $grade) = $sth2->fetchrow; # grade used below

	    if ( $first ) { # start the form
		print qq{<form action="$self" method="post">\n};
		print qq{<input type="hidden" name="page" value="3">\n};
		$first = 0;
	    }

	    print qq{<table cellpadding="3" border="1" cellspacing="0" style="margin:0.5em;">\n};

	    print qq{<tr><td class="bra">Name</td>};
	    print qq{<td><b>$lastname</b>, $firstname ($r{studentid})</td></tr>\n};
	    
	    print qq{<tr><td class="bra">Date</td>\n};
	    print qq{<td><input type="text" style="width:12ch;" name="$id:absdate" id="$id:absdate"};
	    print qq{ value="$r{absdate}"> };
	    print qq{<button type="reset" id="$id:date_trigger">...</button>\n};

	    
	    print qq{</td></tr>\n};

	    print qq{<tr><td class="bra">Reason</td>\n};
	    print qq{<td><select name="$id:reason"><option>$r{reason}</option>\n};
	    foreach my $rsn ( @attend ) { # @attend is global array from configuration
		if ( $rsn eq $r{reason} ) { next; }
		print qq{<option>$rsn</option>\n};
	    }
	    print qq{</select></td></tr>\n};

	    my $ppd = $g_ppd{$grade}; # attendance periods from grade of student; g_ppd is from conf
	    print qq{<tr><td class="bra">Period</td>\n};
	    print qq{<td><select name="$id:period"><option>$r{period}</option>\n};
	    foreach my $per ( 1..$ppd ) { # $g_ppd hash is global from configuration system
		if ( $per == $r{period} ) { next; }
		print qq{<option>$per</option>\n};
	    }
	    print qq{</select></td></tr>\n};

	    print qq{<tr><td class="bra">Minutes Late</td>\n};
	    print qq{<td><input type="text" style="width:4ch;" name="$id:late" };
	    print qq{value="$r{late}"></td></tr>\n};
	    
	    print qq{</table>\n\n};

	} # end of if an edit
    } # end of edit loop

    if ( not $first ) { # we had some edits.
	print qq{<input type="submit" value="Update Records">\n};
	print qq{</form>\n};

    } else {
	print qq{<h3>No Attendance Edits</h3>\n};
    }

    # now calendar javascript
    foreach my $id ( keys %arr ) {
	if ( $arr{$id} eq 'E' ) { # edit, likely redundant since deletes are done.

	    print qq{<script type="text/javascript">
 Calendar.setup({
   date        : "$absdate{$id}",
   inputField  : "$id:absdate",
   ifFormat    : "%Y-%m-%d",
   button      : "$id:date_trigger",
   singleClick : false,
   step : 1
 });
</script>\n};
	} # end of IF
    } # end of %arr loop



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

    exit;

}


#----------------
sub updateRecords {
#----------------

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

    foreach my $key ( sort keys %arr ) {

	my ( $id, $field ) = split(':', $key);

	# Update Record
	my $sth = $dbh->prepare("update attend set $field = ? where attid = ?");
	$sth->execute( $arr{$key}, $id );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	print qq{<div>$id - $field - $arr{$key} Updated</div>\n};

    }

    print qq{<h1>$lex{Records} $lex{Updated}</h1>\n};

    print qq{<p>[ <a href="$self">$lex{Edit}/$lex{Delete} Attendance</a>};
    print qq{ | <a href="$homepage">$lex{Main}</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;

}
