#!/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 = ( 'Date or Meal missing. Please try again.' => 'Date or Meal missing. Please try again.',
	    'Groups' => 'Groups',
	    'Group by' => 'Group by',
	    'Continue' => 'Continue',
	    'Lunch Attendance Entry' => 'Lunch Attendance Entry',
	    'Homeroom' => 'Homeroom',
	    'Check All' => 'Check All',
	    'Grade' => 'Grade',
	    'Main' => 'Main',
	    'Save Lunch Entry' => 'Save Lunch Entry',
	    'Blank=All' => 'Blank=All',
	    'Separate with Spaces' => 'Separate with Spaces',
	    'Meal' => 'Meal',
	    'Fees' => 'Fees',
	    'Error' => 'Error',
	    'Record(s) Stored' => 'Record(s) Stored',
	    

	    );

my $self = 'lunchadd.pl';

use CGI;
use DBI;
use Cwd;


my $defaultFeeType = 'Full';
my %cost = ('Full' => 1.50, 'Reduced' => '0.25', 'Free' => '0');

# The field in the student table holding the lunch status value
my $lunchfield = 'lunchstatus';  

my @meals = qw(Breakfast Lunch After-School);


# calc current date
my @tim = localtime(time);
my $year = @tim[5] + 1900;
my $month = @tim[4] + 1;
my $day = @tim[3];
my $currdate = "$year-$month-$day";


# Get current dir so know what path for config files.
my $configpath;
my $teachermode;
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $teachermode = 1;
    $configpath = '..'; # go back one to get to etc.

} else {
    $configpath = '../..'; # go back two to get to etc.
}


eval require "$configpath/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 $checked = $arr{checked};
delete $arr{checked};


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


# Get current dir so know what CSS to display;
if (getcwd() =~ /tcgi/){ # we are in tcgi
    $css = $tchcss;
}


print "$doctype\n<html><head><title>". $lex{'Lunch Attendance Entry'}. "</title>\n";
print "<link rel=\"stylesheet\" href=\"$css\" type=\"text/css\">";
print "$chartype\n</head><body>[ <a href=\"$homepage\">". $lex{Main}. "</a> |\n";
print "<a href=\"$feespage\">". $lex{Fees}. "</a> ]\n";

print "<center><h1>". $lex{'Lunch Attendance Entry'}. "</h1>\n";

if ($arr{writeflag}){ # Write values and die;
    updateRecord();
    die;
}

if (not $arr{grouping}){ # first entry; show options.
    showOptions();
    die;
}

# Display a button to select all check boxes
#print "<form action=\"$self\" method=\"post\">";
#print "<input type=\"hidden\" name=\"group\" value=\"$arr{group}\">\n";
#print "<input type=\"hidden\" name=\"grouping\" value=\"$arr{grouping}\">\n";
#print "<input type=\"hidden\" name=\"checked\" value=\"checked\">\n";
#print "<input type=\"submit\" value=\"". $lex{'Check All'}. "\"></form>\n";


# Check Passed Values
#print "<br>\n";
#foreach $key (keys %arr){ print "Key: $key  VAL: $arr{$key}<br>\n"; }

my $grouping = $arr{grouping};
my $selectgrp;
my $orderby;
# define orderby
if ($grouping eq $lex{Grade}){
    $orderby = 'order by grade, lastname, firstname';
    $selectgrp = 'grade';
} elsif ($grouping eq $lex{Homeroom}){
    $orderby = 'order by homeroom, lastname, firstname';
    $selectgrp = 'homeroom';
} else {
    print "Programming Error!\n";
    die;
}

my $select;
# define select
if ($arr{group}){ # We have some group(s)
    $arr{group} =~ s/^\s+//; # strip leading spaces
    $arr{group} =~ s/\s+/ /g;  # remove multiple spaces.
    @grp = split /\s/,$arr{group};
    if (@grp){
       $select = 'where ';
       $firstflag = 1; 
       foreach my $g (@grp){
           if (not $firstflag){ $select .= ' or ';} else { $firstflag = 0;}
           $select .= "$selectgrp = '$g'";
       }
   }
}  

#print "ORDERBY: $orderby<br>\n";
#print "SELECT: $select<br>\n";


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


# Setup the form and start of table.
print "<form action=\"$self\" method=\"post\">\n";
print "<input type=\"hidden\" name=\"writeflag\" value=\"1\">\n";
print "<table cellpadding=\"3\" border=\"1\" cellspacing=\"0\">\n";

print "<tr><td colspan=\"4\" align=\"center\">Date <input type=\"text\" ";
print "name=\"date\" value=\"$currdate\" size=\"9\">\n";

# Print Meal Selection
print "$lex{Meal} <select name=\"meal\">\n";
print "<option>$arr{meal}</option>\n";
foreach my $meal (@meals) {
    print "<option>$meal</option>";
}
print "\n</select></td></tr>\n";

# Print Submit Row
print "<tr><td colspan=\"4\" align=\"center\">";
print "<input type=\"submit\" value=\"". $lex{'Save Lunch Entry'}. "\"></td></tr>\n";

# Print Headings
print "<tr><th>Name</th><th>Status</th><th>Chg</th><th>Pd</th></tr>\n";

#main loop
while (my ($studnum, $lastname, $firstname, $feeType) = $sth->fetchrow){
    print "<tr><td><b>$lastname</b>, $firstname </td><td>$feeType</td>\n";
    if (not $feeType) { $feeType = $defaultFeeType; }
    print "<td><input type=\"checkbox\" name=\"$studnum:C:$feeType\" value=\"1\" $checked></td>\n";
    print "<td><input type=\"checkbox\" name=\"$studnum:P:$feeType\" value=\"1\" $checked></td></tr>\n";
}

print "<tr><td colspan=\"4\" align=\"center\">";
print "<input type=\"submit\" value=\"". $lex{'Save Lunch Entry'}. "\"></td></tr>\n";
print "</table>\n</form></center></body></html>\n";

# ========= Functions =============


#---------------
sub updateRecord {
#---------------
    delete $arr{writeflag}; # don't need no writeflag
    my $date = $arr{date};
    delete $arr{date};
    my $meal = $arr{meal};
    delete $arr{meal};
    if (not $date or not $meal) {
	print "<p><b>". $lex{'Date or Meal missing. Please try again.'}. "</b></p>\n";
	die;
    }

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

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

	# Split into field values
	my ($studnum, $paid, $feeType) = split /:/, $rec;

	# Get cost of lunch
	my $cost = $cost{$feeType};

	if ($paid eq 'P') { $paid = "'Y'"; } else { $paid = $sql{default}; }

	#print "SN:$studnum P:$paid F:$feeType<br>\n";

	$sth = $dbh->prepare("insert into attend_lunch values(
          $sql{default},'$studnum','$date','$feeType','$meal','$cost',$paid,$sql{default})");
	$sth->execute;
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}
    }


    print "<b>". $lex{'Record(s) Stored'}. ".</b>\n";
    print "<p>[ <a href=\"$self\">". $lex{'Lunch Attendance Entry'}. "</a> | ";
    print "<a href=\"$homepage\">Main</a> ]</p></body></html>";

} # End of updateRecord


#--------------
sub showOptions { # display entry options
#--------------
    print "<p><form action=\"$self\" method=\"post\">\n";
    print "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\">\n";

    print "<tr><td align=\"right\">". $lex{'Group by'}. "</td>\n";
    print "<td><select name=\"grouping\"><option>". $lex{Homeroom}. "</option>\n";
    print "<option>". $lex{Grade}. "</option></select></td></tr>\n";

    print "<tr><td align=\"right\">". $lex{Groups};
    print "</td><td><input type=\"text\" name=\"group\" size=\"25\"></td></tr>\n";
    print "<tr><td colspan=\"2\">$lex{'Separate with Spaces'} $lex{'Blank=All'}";
    print "</td></tr>\n";

    print "<tr><td align=\"right\">". $lex{Meal}. "</td><td><select name=\"meal\">\n";
    foreach my $meal (@meals) { 
	print "<option>$meal</option>";
    }
    print "\n</select></td></tr>\n";

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

}
