#!/usr/bin/perl

# Copyright 2000-2002 Katipo Communications
#
# This file is part of Koha.
#
# Koha 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.
#
# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA  02111-1307 USA

use strict;
use CGI;
use C4::Context;
use C4::Output;
use C4::Database;
use C4::Auth;
use C4::Output;
use C4::Koha;
use C4::Interface::CGI::Output;
use HTML::Template;

my $input = new CGI;
my $dbh = C4::Context->dbh;

my $type=$input->param('type');
my $branch = $input->param('branch');
$branch="" unless $branch;
my $op = $input->param('op');

# my $flagsrequired;
# $flagsrequired->{circulation}=1;
my ($template, $loggedinuser, $cookie)
    = get_template_and_user({template_name => "parameters/smart-rules.tmpl",
                             query => $input,
                             type => "intranet",
                             authnotrequired => 1,
 			     flagsrequired => {parameters => 1, management => 1},
			      debug => 1,
                             });

if ($op =~ 'delete-(.*)-(.*)-(.*)') {
	my $itemtype = $1;
	my $categorycode = $2;
	my $branch = $3;
	warn "deleting $1 $2 $3";

	my $sth_Idelete = $dbh->prepare("delete from issuingrules where branchcode=? and categorycode=? and itemtype=?");
	$sth_Idelete->execute($branch, $categorycode, $itemtype);
}
# save the values entered
if ($op eq 'add') {
	my $sth_search = $dbh->prepare("select count(*) as total from issuingrules where branchcode=? and categorycode=? and itemtype=?");
	my $sth_insert = $dbh->prepare("insert into issuingrules (branchcode,categorycode,itemtype,maxissueqty,issuelength,fine,firstremind,chargeperiod) values (?,?,?,?,?,?,?,?)");
	my $sth_update=$dbh->prepare("Update issuingrules set fine=?,firstremind=?,chargeperiod=?,maxissueqty=?,issuelength=? where branchcode=? and categorycode=? and itemtype=?");
	
	my $br = $branch; # branch
	my $bor = $input->param('categorycode'); # borrower category
	my $cat = $input->param('itemtype'); # item type
	my $fine = $input->param('fine');
	my $firstremind = $input->param('firstremind');
	my $chargeperiod = $input->param('chargeperiod');
	my $maxissueqty = $input->param('maxissueqty');
	my $issuelength = $input->param('issuelength');
	warn "Adding $br, $bor, $cat, $fine, $maxissueqty";

	$sth_search->execute($br,$bor,$cat);
	my $res = $sth_search->fetchrow_hashref();
	if ($res->{total}) {
		$sth_update->execute($fine, $firstremind, $chargeperiod, $maxissueqty,$issuelength,$br,$bor,$cat);
	} else {
		$sth_insert->execute($br,$bor,$cat,$maxissueqty,$issuelength,$fine,$firstremind,$chargeperiod);
	}
}
my $branches = getbranches;
my @branchloop;
foreach my $thisbranch (keys %$branches) {
	my $selected = 1 if $thisbranch eq $branch;
	my %row =(value => $thisbranch,
				selected => $selected,
				branchname => $branches->{$thisbranch}->{'branchname'},
			);
	push @branchloop, \%row;
}

my $sth=$dbh->prepare("Select description,categorycode from categories order by description");
$sth->execute;
my @category_loop;
while (my $data=$sth->fetchrow_hashref){
	push @category_loop,$data;
}

my %row = (categorycode => "*", description => 'Any');
push @category_loop, \%row;

$sth->finish;
$sth=$dbh->prepare("Select description,itemtype from itemtypes order by description");
$sth->execute;
# $i=0;
my $toggle= 1;
my @row_loop;
my @itemtypes;
while (my $row=$sth->fetchrow_hashref){
	push @itemtypes,$row;
	
}
my %row = (itemtype => '*', description => 'Any');
push @itemtypes,\%row;

my $sth2 = $dbh->prepare("SELECT issuingrules.*, itemtypes.description AS humanitemtype, categories.description AS humancategorycode FROM issuingrules LEFT JOIN itemtypes ON (itemtypes.itemtype = issuingrules.itemtype) LEFT JOIN categories ON (categories.categorycode = issuingrules.categorycode) WHERE issuingrules.branchcode = ?");
$sth2->execute($branch);

while (my $row = $sth2->fetchrow_hashref) {
	$row->{'humanitemtype'} = 'Any' if (not $row->{'humanitemtype'} or $row->{'humanitemtype'} eq '*');
	$row->{'humancategorycode'} = 'Any' if (not $row->{'humancategorycode'} or $row->{'humancategorycode'} eq '*');
	$row->{'fine'} = sprintf('%.2f', $row->{'fine'});
	push @row_loop, $row;
}
$sth->finish;
$template->param(categoryloop => \@category_loop,
						itemtypeloop => \@itemtypes,
						rules => \@row_loop,
						branchloop => \@branchloop,
						branch => $branch,
						intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
		intranetstylesheet => C4::Context->preference("intranetstylesheet"),
		IntranetNav => C4::Context->preference("IntranetNav"),
						);
output_html_with_http_headers $input, $cookie, $template->output;
