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

#  This file is part of Open Admin for Schools.

# Passed as "group": Accept Grade, Class, or All for group to 
# find for attendance.
# Passed as "mode": Weekly or Biweekly Mode. (or Date Range?)
# Passed as "class": The value of the group: ie. 8c, 10.

my %lex = ( 'Add' => 'Add',
	    'Multi-Day' => 'Multi-Day',
	    'Attendance' => 'Attendance',
	    'Date' => 'Date',
	    'Name' => 'Name',
	    'Continue' => 'Continue',
	    'Error' => 'Error',
	    'Weekly' => 'Weekly',
	    'Select by' => 'Select by',
	    'Grade' => 'Grade',
	    'Homeroom' => 'Homeroom',
	    'Weekly' => 'Weekly',
	    'Biweekly' => 'Biweekly',
	    'Continue' => 'Continue',
	    'Mode' => 'Mode',
	    'Blank=All' => 'Blank=All',
	    'Sort by' => 'Sort by',
	    'Separate with Spaces' => 'Separate with Spaces',
	    'No Student(s) Found' => 'No Student(s) Found',
	    'Start Date' => 'Start Date',
	    'Period' => 'Period',
	    'Reason' => 'Reason',
	    'Late' => 'Late',
	    'Subject' => 'Subject',
	    'Record(s) Stored' => 'Record(s) Stored',
	    'Contact' => 'Contact',
	    'Missing' => 'Missing',
	    'Reason' => 'Reason',
	    'Skipping' => 'Skipping',
	    'Save' => 'Save',
	    'Start Page' => 'Start Page',
	    'Previous Week' => 'Previous Week',
	    'Next Week' => 'Next Week',
	    'AM' => 'AM',
	    'PM' => 'PM',
	    'Show' => 'Show',
	    'Withdrawn' => 'Withdrawn',
	    'Students' => 'Students',
	    'WD' => 'WD',

	    );

my $self = 'attadd_multiday.pl';


use DBI;
use CGI;
use Time::JulianDay;

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);
$dbh->{mysql_enable_utf8} = 1;


# Set Default 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{Add} $lex{Attendance} - $lex{'Multi-Day'}";
print "$doctype\n<html><head><title>$title</title>\n";
print "<link rel=\"stylesheet\" href=\"$css\" type=\"text/css\">\n";


if ( not $arr{page} ) { # calendar popup is on start page.
    print "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" ";
    print "href=\"/js/calendar-blue.css\" title=\"blue\">\n";
    print "<script type=\"text/javascript\" src=\"/js/calendar.js\"></script>\n";
    print "<script type=\"text/javascript\" src=\"/js/lang/calendar-en.js\"></script>\n";
    print "<script type=\"text/javascript\" src=\"/js/calendar-setup.js\"></script>\n";
}


print "$chartype\n</head><body>[ <a href=\"$attpage\">$lex{Attendance}</a> ]\n";
print "<center><h1>$title</h1>\n";

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

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

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    setReasons();

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    writeRecords();
}



#-------------
sub setReasons {
#-------------

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

    # Form start
    print "<form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"3\">\n";
    print "<input type=\"submit\" value=\"$lex{Save}\">\n";

    # Table and Heading
    print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n";
    print "<tr><th>$lex{Name}</th><th>$lex{Date}/$lex{Period}";
    print "</th><th>$lex{Reason}</th><th>$lex{Late}</th></tr>\n";
    # Not used, yet.<th>$lex{Subject}</th></tr>\n";

    my $sth = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");
    my $sth1 = $dbh->prepare("select distinct subjcode from eval where studnum = ?");
    my $sth2 = $dbh->prepare("select description from subject where subjsec = ?");
    my %subjects = ();


    foreach my $key ( sort keys %arr ) {

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

	# print "SN:$studnum DT:$date PER:$period<br>\n";
	if ( not $period ) {
	    print "<input type=\"hidden\" name=\"$key\" value=\"$arr{$key}\">\n";
	    next; 
	} # skip 5 other passed values; pass through to next function.

	
	my $jd = julian_day( split(/-/, $date));
	my $dow = day_of_week( $jd ) + 1; # since not 0-6,but 1-7 for @dow

	# Get Name
	$sth->execute($studnum);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	my ($lastname, $firstname) = $sth->fetchrow;

=head
	# Check/Get Subjects
	if ( not $subjects{$studnum} ) {
	
	    $sth1->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
	    $subjects{$studnum} = [ ]; # create array
	
	    while ( my $subjsec = $sth1->fetchrow ) {

		# Get Description
		$sth2->execute( $subjsec );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
		my $desc = $sth2->fetchrow;
		$desc =~ s/\(/ /g;

		push @{$subjects{$studnum}}, "$desc ($subjsec)";
	    }
	}
=cut

	print "<tr><td><b>$lastname</b>, $firstname</td><td>$dow[$dow] $date ";
	print "<i>$lex{Period}:</i> $period</td>";

	# Reasons
	print "<td><select name=\"R:$key\"><option></option>\n";
	foreach my $reason ( @attend ) {
	    print "<option>$reason</option>\n";
	}
	print "</select></td>";

	# Late
	print "<td><input type=\"text\" size=\"6\" name=\"L:$key\"></td>\n";

=head	
	# Subjects
	print "<td><select name=\"S:$key\"><option></option>\n";
	foreach my $subj ( @{ $subjects{$studnum} } ) {
	    print "<option>$subj</option>\n";
	}
	print "</select></td></tr>\n";
=cut
    print "</td></tr>\n";

    }

    print "</table><input type=\"submit\" value=\"$lex{Save}\">\n";
    print "</form></center></body></html>\n";

    exit;

} # end of setReasons();



#---------------
sub writeRecords {
#---------------

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

	my ( $type,$studnum,$date,$period ) = split( /:/,$key);
	if ( $type eq 'L' or $type eq 'S' or not $period ) { next; } # skip Late, Subject, and additional vars in loop
 
	# Check for Missing Reason
	if ( not $arr{$key} ) { # missing reason
	    print "<div style=\"color:red;font-weight:bold;\">$lex{Missing} $lex{Reason} - $lex{Skipping}</div>\n";
	    next;
	}

	my $lkey = "L:$studnum:$date:$period";
	my $skey = "S:$studnum:$date:$period";

	my $late;
	if ( $arr{$lkey} ) { $late = $arr{$lkey}; }

	my $subject;
	if ( $arr{$skey} ) {
	    my ($dud, $subjsec ) = split(/\(/, $arr{$skey});
	    chop $subjsec; # remove trailing parens
	    $subject = $subjsec;
	}

	$sth = $dbh->prepare("insert into attend ( studentid, absdate, reason, period, late, subjsec )
         values ( ?, ?, ?, ?, ?, ? )");
	$sth->execute( $studnum, $date, $arr{$key}, $period, $late, $subject );
	
    } # End of Record Entry loop


    if ( not $DBI::errstr ) {
	print "<h3>$lex{'Record(s) Stored'}</h3>\n";

    } else {
	print "<h3>$lex{Error}! $lex{Contact}:";
	print " $adminname <a href=\"mailto:$adminemail\">$adminemail</a><br>\n";
	print "$lex{Error}: $DBI::errstr</h3>\n";
    }

    # More Attendance Entry...
    # Start Page
    print "<form action=\"$self\" method=\"post\" style=\"display:inline;\">\n";
    print "<input type=\"submit\" value=\"$lex{'Start Page'}\"></form>\n\n";

    # Previous Page
    print "<form action=\"$self\" method=\"post\" style=\"display:inline;\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"1\">\n";
    foreach my $key ( sort keys %arr ) {
	if ( $key =~ m/:/ ) { next; } # skip attendance values
	print "<input type=\"hidden\" name=\"$key\" value=\"$arr{$key}\">\n";
    }
    print "<input type=\"submit\" value=\"$lex{Add} $lex{Attendance}\"></form>\n";

    # print "<p>[ <a href=\"$attpage\">$lex{Attendance}</a> ]</p>\n";
    print "</center></body></html>\n";

    exit;

} # end of writeRecords();




#-------------
sub setPeriods {
#-------------

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

    my $studtable = 'student';
    if ( $arr{showwithdrawn} ) {
	$studtable = 'studentall';
    }
    delete $arr{showwithdrawn};


    # Set # of weeks to do, 1 or 2
    my $weekcount = $arr{mode};


    # Get Date
    if ( $arr{date} ) { 
	# Generate a list from those dates. Assume year-mon-day
	($year,$month,$day) = split /-/,$arr{date};
	$jd = julian_day($year,$month,$day);
	$dow = day_of_week($jd);
	$mondayjd = $jd - ($dow-1);
	if (length($month) == 1){ $month = "0".$month;}
	if (length($day) == 1){ $day = "0".$day;}
	$currsdate = "$year$month$day"; 
	$currdate = "$year-$month-$day";

    } else { # get current date
	@tim = localtime(time);
	$year = @tim[5] + 1900;
	$month = @tim[4] + 1;
	$day = @tim[3];
	$jd = julian_day($year,$month,$day);
	$mondayjd = $jd - ($tim[6]-1); #This will now give Monday of that week.
	if (length($month) == 1){ $month = "0".$month;}
	if (length($day) == 1){ $day = "0".$day;}
	$currdate = "$year-$month-$day";
	$currsdate = "$year$month$day"; 
	$currdate1 = "@month[$month] $day, $year";
    }

    # Setup Array and Hash to hold Dates and DOW Dates
    mkDateData($mondayjd,$weekcount);


    # set group type
    my $grouptype;
    if ( $arr{grouptype} eq $lex{Grade} ) {
	$grouptype = 'grade';
    } else {
	$grouptype = 'homeroom';
    }
    
    # set group values
    my @values = split /\s/, $arr{groupvalue}; # split into array based on spaces


    # setup student select
    my $select;
    if ( @values ) {
	$select = 'where ';
	$first = 1;
	foreach my $value ( @values ) {
	    $value = $dbh->quote( $value );
	    if ( not $first ) { $select .= ' or '; }
	    $select .= "$grouptype = $value ";
	    $first = 0;
	}
    }


    # Set sorting order
    my $sortorder = "lastname, firstname";
    if ( $arr{sortorder} eq $lex{Grade} ) {
	$sortorder = "grade,lastname, firstname";
    }


    print "<h3>$arr{grouptype} $arr{groupvalue}</h3>\n";

    # Remove date from %arr; already in $currdate;
    delete $arr{date}; # loops below

    # Calculate Previous Week Date
    $prevjd = $mondayjd - 7;
    ($prevyear, $prevmonth, $prevday) = inverse_julian_day($prevjd);
    $prevdate = "$prevyear-$prevmonth-$prevday";

    print "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n";
    print "<tr><td>";

    print "<form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"1\">\n";
    print "<input type=\"hidden\" name=\"date\" value=\"$prevdate\">\n";
    foreach my $key ( keys %arr ) {
	print "<input type=\"hidden\" name=\"$key\" value=\"$arr{$key}\">\n";
    }
    print "<input type=\"submit\" value=\"<= $lex{'Previous Week'}\"></form>\n";
    print "</td>\n\n";

    # Calcualte Next Week Monday Date
    $nextjd = $mondayjd + 7; 
    ($nextyear, $nextmonth, $nextday) = inverse_julian_day($nextjd);
    $nextdate = "$nextyear-$nextmonth-$nextday";

    print "<td><form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"1\">\n";
    print "<input type=\"hidden\" name=\"date\" value=\"$nextdate\">\n";
    foreach my $key ( keys %arr ) {
	print "<input type=\"hidden\" name=\"$key\" value=\"$arr{$key}\">\n";
    }
    print "<input type=\"submit\" value=\"$lex{'Next Week'} =>\"></form>\n";
    print "</td></tr></table>\n\n";


    # Start Main Entry Form.
    print "<form action=\"$self\" method=\"post\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"2\">\n";
    print "<input type=\"hidden\" name=\"date\" value=\"$currdate\">\n";
    foreach my $key ( keys %arr ) { # 4 values: 2 group, mode, and sortorder
	print "<input type=\"hidden\" name=\"$key\" value=\"$arr{$key}\">\n";
    }    

    print "<input type=\"submit\" value=\"$lex{Continue}\">\n";
    print "<table cellpadding=\"4\" cellspacing=\"0\" border=\"1\">\n";


    # Loop through table headings.
    print "<tr><th>$lex{Name}</th>\n";
    foreach my $day ( @days ){ print "<th>$datedata{$day}</th>";}
    print "</tr>\n";

    # Find the kids' names and studnum
    my $sth = $dbh->prepare("select lastname, firstname, studnum, grade from $studtable
    $select order by $sortorder");
    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n";}
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die "$DBI::errstr\n";}

    my $sth1 = $dbh->prepare("select count(*) from studentwd where studnum = ?");

    # Loop through kids displaying the values.
    my $first = 1;
    while ( my ($lastname, $firstname, $studnum, $grade) = $sth->fetchrow ){

	# Check if withdrawn
	my $wd;
	$sth1->execute($studnum);
	my $count = $sth1->fetchrow;
	if ( $count ) {
	    $wd = "<span style=\"color:red;\">$lex{WD}</span>";
	}


	# print Name.
	print "<tr><td><b>$wd $lastname</b>, $firstname ($studnum)($grade)</td>\n";

	my $ppdmode;
	my %ampm = (1 => $lex{'AM'}, 2 => $lex{'PM'} );

	my $ppd = $g_ppd{$grade};
	if ( $ppd == 2 ) {
	    $ppdmode = 1;  # am/pm mode
	}

	$first = 0;

	# print the days for this mode:
	foreach my $day ( @days ){
	    print "<td>";
	    for my $period ( 1..$ppd ) {
		if ( $ppdmode ) {
		    print "$ampm{$period}<input type=\"checkbox\" name=\"$studnum:$day:$period\" value=\"1\">";
		} else {
		    print "P$period<input type=\"checkbox\" name=\"$studnum:$day:$period\" value=\"1\">";
		}
	    }
	    print "</td>";
	}
	print "</tr>\n";
    }

    if ( $first ) {
	my $cols = $#days + 2;
	print "<tr><td colspan=\"$cols\" style=\"text-align:center;font-size:130%;font-weight:bold;\">";
	print "$lex{'No Student(s) Found'}</td></tr>\n";
    }

    print "</table><input type=\"submit\" value=\"$lex{Continue}\"></form>\n";
    print "</center></body></html>\n";

    exit;

} # end of setPeriods();



#-------------
sub mkDateData {
#-------------

    my ( $jd, $weeks ) =  @_;
    # Build an array of ISO dates and a hash using them
    # as keys to hash values of 'Mon Jan 6' format.
    # If one week, then just 5 values, if two wk then 10, etc.
    for ( 1 .. $weeks ){
	for ( 1 .. 5 ){
	    my ($yr,$mon,$day) = inverse_julian_day($jd);
	    my $dow = day_of_week($jd) + 1;
	    push @days, "$yr-$mon-$day";
	    $datedata{"$yr-$mon-$day"} = "$dow[$dow], $s_month[$mon] $day";
	    $jd++;
	}
	$jd = $jd + 2; # skip over weekend.
    }
}


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


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

    # Start Date
    print "<tr><td class=\"bra\">$lex{'Start Date'}</td>\n";
    print "<td><input type=\"text\" name=\"date\" id=\"date\" size=\"12\" value=\"$currdate\">\n";
    print "<button type=\"reset\" id=\"start_trigger\">...</button>\n";
    print "</td></tr>\n";

    print "<tr><td class=\"bra\">$lex{'Select by'}</td>\n";
    print "<td><select name=\"grouptype\"><option>$lex{Grade}</option>\n";
    print "<option>$lex{Homeroom}</option></select>\n";
    print "<input type=\"text\" name=\"groupvalue\" size=\"12\"> ";

    print "$lex{'Separate with Spaces'}, $lex{'Blank=All'}</td></tr>\n";

    print "<tr><td class=\"bra\">$lex{'Sort by'}\n";
    print "</td><td><select name=\"sortorder\"><option>$lex{Name}</option>\n";
    print "<option>$lex{Grade}</option></select></td></tr>\n";

    # Mode: Weekly, Biweekly
    print "<tr><td class=\"bra\">$lex{Mode}\n";
    print "</td><td><select name=\"mode\"><option value=\"1\">$lex{Weekly}</option>\n";
    print "<option value=\"2\">$lex{Biweekly}</option></select></td></tr>\n";

    # Show Withdrawn
    print "<tr><td class=\"bra\">$lex{Show} $lex{Withdrawn} $lex{Students}\n";
    print "</td><td><input type=\"checkbox\" name=\"showwithdrawn\" value=\"1\">\n";
    print "</td></tr>\n";

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

    print "<script type=\"text/javascript\">
     Calendar.setup({
        inputField     :    \"date\", // id of the input field
        ifFormat       :    \"%Y-%m-%d\", // format of the input field
        button         :    \"start_trigger\", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // show all years in drop-down boxes 
    })";

    print "</script>\n";

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

    exit;

}
