#!/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.

%lex = ( 'Main' => 'Main',
	 'Fees' => 'Fees',
	 'View' => 'View',
	 'Error' => 'Error',
	 'Title' => 'Title',
	 'Author' => 'Author',
	 'Textbook' => 'Textbook',
	 'Copy' => 'Copy',
	 'Code' => 'Code',
	 'In' => 'In',
	 'Out' => 'Out',
	 'Id' => 'Id',
	 'Status' => 'Status',
	 'Copies' => 'Copies',
	 'Not Found' => 'Not Found',

	 );

use CGI;
use DBI;

my $self = 'tb_copyview.pl';


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{View} $lex{Textbook} $lex{Copy}";
print "$doctype\n<html><head><title>$title</title>\n";
print "<link rel=\"stylesheet\" href=\"$css\" type=\"text/css\">\n";
print "$chartype\n</head><body>\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();
}

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

    # Load textbook titles, in order.
    my $sth = $dbh->prepare("select id, title, author, pubdate 
      from book_title order by title");
    $sth->execute;
    if ( $DBI::errstr ) { print "$DBI::errstr;"; die "$DBI::errstr\n"; }

    my $sth1 = $dbh->prepare("select id, barcode from book_copy where titleid = ?");

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


    while ( my ( $id, $title, $author, $pubdate ) = $sth->fetchrow ) {

	print "<div style=\"font-size:120%;font-weight:bold;padding:0.3em;color:#049;\">$title ($pubdate)</div>\n";
	my $first = 1;

	# Load copy info.
	$sth1->execute($id);
	if ( $DBI::errstr ) { print "$DBI::errstr;"; die "$DBI::errstr\n"; }
	while ( my ( $copyid, $barcode ) = $sth1->fetchrow ) {

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

	    print "<tr><td>$barcode</td><td>";
	    $sth2->execute( $copyid );
	    if ( $DBI::errstr ) { print "$DBI::errstr;"; die "$DBI::errstr\n"; }
	    my $count = $sth2->fetchrow;
	    if ( $count ) { print $lex{Out}; } else { print $lex{In}; }
	    print "</td></tr>\n";
	}

	print "</table>\n";

	if ( $first ) {
	    print "<div style=\"padding:0.2em 1em;\">$lex{Copies} $lex{'Not Found'}</div>\n";
	}


    }

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

} # end of showStartPage

