#!/usr/bin/perl
#  Copyright 2001-2011 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 = ('Textbook' => 'Textbook',
	   'Sign Out' => 'Sign Out',
	   'Main' => 'Main',
	   'Fees' => 'Fees',
	   'Error' => 'Error',
	   'Date' => 'Date',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Student' => 'Student',
	   'Books' => 'Books',
	   'Continue' => 'Continue',
	   'Record(s) Added' => 'Record(s) Added',
	   'Id' => 'Id',
	   'Not Found' => 'Not Found',

	   );

use DBI;
use CGI;

my $self = 'tb_signout.pl';
my $maxbooks = 6; # max number of books signed out at a time.

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);


# Print Page Header
my $title = "$lex{'Sign Out'} $lex{Textbook}";
print "$doctype\n<html><head><title>$title</title>
<link rel=\"stylesheet\" href=\"$css\" type=\"text/css\">
$chartype\n</head>\n";

print "<body style=\"padding:1.5em;\">\n";
print "[ <a href=\"$homepage\">$lex{Main}</a> |\n";
print " <a href=\"$feespage\">$lex{Fees}</a> ]\n";
print "<h1>$title</h1>\n";


if ( not $arr{page} ) {
    showStartPage(); # select student group and books per page.

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

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


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

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

    # Start Table
    print "<table cellpadding=\"3\" border=\"1\" cellspacing=\"0\">\n";

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

    # Books per Student
    print "<tr><td class=\"bra\">$lex{Books}/$lex{Student}</td><td class=\"la\">\n";
    print "<select name=\"bookcount\">";
    for my $b (1..$maxbooks) { print "<option>$b</option>"; }
    print "</select></td></tr>\n";

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

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

}



#--------------
sub selectBooks {
#--------------

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

    my $group; # Grade or Homeroom
    if ( $arr{grouptype} eq $lex{Grade} ) {
	$group = 'grade';
    } else {
	$group = 'homeroom';
    }

    my $bookcount;
    if ( $arr{bookcount} > $maxbooks or $arr{bookcount} < 1 ) {
	$bookcount = 1;
    } else {
	$bookcount = $arr{bookcount};
    }


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


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

    # Table
    print "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\">\n";
    print "<tr><th>$lex{Student}</th><th>$lex{Books}</th></tr>\n";
    # Continue
    print "<tr><td colspan=\"2\" style=\"text-align:center;\">\n";
    print "<input type=\"submit\" value=\"$lex{Continue}\"></td></tr>\n";

    foreach my $studkey ( sort keys %students ) {
	my $studnum = $students{$studkey};
	
	foreach my $i ( 1..$bookcount ) {
	    if ( $i == 1 ) {
		print "<tr><td class=\"bla\">$studkey</td><td class=\"la\">\n";
	    } else { print "<tr><td></td><td class=\"la\">";}
	    print "<input type=\"text\" name=\"$studnum:$i\" size=\"14\"></td></tr>\n";
	}
    }

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

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

    exit;
}



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

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

    my $sth = $dbh->prepare("select lastname, firstname from student where studnum = ?");
    my $sth1 = $dbh->prepare("select id, titleid, barcode from book_copy where barcode = ?");
    my $sth2 = $dbh->prepare("select title, author, pubdate from book_title where id = ?");

    my $sth3 = $dbh->prepare("insert into book_signout ( copyid, studnum, signout ) values(?,?,now() )");

    my $sth4 = $dbh->prepare("select count(*) from book_signout 
      where signout is not NULL and returndate is NULL and copyid = ? ");


    my $first = 1;

    foreach my $key ( sort keys %arr ) {

	if ( not $arr{$key} ) { next; } # skip any blanks

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

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

	# Load Copy Info
	$sth1->execute( $arr{$key} );
	if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr }
	my ($id, $titleid, $barcode ) = $sth1->fetchrow;

#	print "Copyid:$id Titleid:$titleid Code:$barcode<br>\n";

	# Load Textbook Info
	$sth2->execute( $titleid );
	if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr }
	my ( $title, $author, $pubdate ) = $sth2->fetchrow;

	# Check for an existing signout
	$sth4->execute( $id ); # which is copyid.
	if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr }
	my $count = $sth4->fetchrow;

#	print "Count:$count<br>\n";

	if ( $count > 0 ) {
	    print "<h3>$lex{Error}: $lex{Textbook} $lex{'Sign Out'} $lex{Exists}: $title ($barcode)</h3>\n";
	    next;
	}

	# Write the Info
	my $text;
	if ( $title ) { $text = "$title ($pubdate)"; }
	if ( not $titleid ) { $text = "<span style=\"color:red;\">$lex{Textbook} $lex{'Not Found'}</span>"; }

	if ( $first ) {
	    # Table
	    print "<table cellpadding=\"3\" cellspacing=\"0\" border=\"1\">\n";
	    print "<tr><th>$lex{Student}</th><th>$lex{Books}</th><th>$lex{Id}</th></tr>\n";
	    $first = 0;
	}


	print "<tr><td class=\"la\">$lastname, $firstname ($studnum)</td>\n";
	print "<td class=\"la\">$text</td><td>$arr{$key}</td></tr>\n";

	# Write the record.
	if ( not $titleid ) { next; } # skip
	$sth3->execute($id, $studnum);
	if (DBI::errstr) { print $DBI::errstr; die $DBI::errstr }

    }

    if ( not $first ) {
	print "</table>\n";
    }

    if ( not $DBI::errstr ) {
	if ( not $first ) {
	    print "<h3>$lex{'Record(s) Added'}</h3>\n";
	}
	
    } else {
	print "<h3>$lex{Error}:$DBI::errstr<br>\n";
	print "$lex{Contact} $adminname <a href=\"mailto:$adminemail\">$adminemail</a></h3>\n";
    }

    print "<p>[ <a href=\"$homepage\">$lex{Main}</a> | \n";
    print "<a href=\"$feespage\">$lex{Fees}</a> | \n";
    print "<a href=\"$self\">$title</a> ]\n";
    
    print "</p></body></html>\n";

    exit;
}
