#!/usr/bin/perl -w
use strict;
use DBI;
use CGI;
use lib qw(../lib/);
use CommSecure;
use Variable;

=head1 LICENCE

validate.pl - CommSecure Cleared transactions validation script
Copyright (C) 2002 James Bromberger <james@rcpt.to>

This program 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.

This program 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 this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


=cut

my $query = new CGI;
print $query->header(-type => 'text/plain');
my $dbh = DBI->connect("dbi:mysql:database=LCA2003-Reg");

if (not defined $dbh) {
	print "Declined\n";
	$dbh->disconnect;
	die "Cannot connect to DB";
	}

# Is there a RefNum in the parameters?
 if (not defined $query->param('RefNum')) {
 	print "Declined\n";
	$dbh->disconnect;
	die "No RefNum";
	}

my $t = CommSecure->new(-dbh => $dbh, -refnum => $query->param('RefNum'));

my $is_ok = 1;
if (not defined $t) {
	$is_ok = 0;
	warn "No transaction";
} elsif (not $t->is_valid) {
	$is_ok = 0;
	warn "Invalid transaction";
#} else {
#	warn "Transaction OK: Verify?";
}
#$is_ok = 0 if $t->cleared;

# Must accept the incoming paramters.
my $v = CommSecure::Validate->new(-dbh => $dbh,
	-amount => $query->param('Amount')||'',
	-refnum => $query->param('RefNum')||'',
	-host => $query->remote_host,
	-save => 1,
	);

my $timeout = Variable->new(-dbh => $dbh, -name => 'CommSecure_Validate_Timeout') || 3600;
my $seconds_since_request = time() - $t->request->date;
#warn "Original Transaction was $seconds_since_request ago, timeout is $timeout";

# Is it a valid enquiry?
if (not $is_ok || $seconds_since_request > $timeout) {
	warn "$is_ok) Verification request from " . $query->remote_host . " was declined - (OK = $is_ok, seconds since request = $seconds_since_request, timeout = $timeout)";
	print "Decline\n";
	$dbh->disconnect;
	exit;
}

# Everything matches up! 
print "Accept";
warn sprintf "Validation for request %s for amount %s from host %s was accepted",
	$t->refnum, $t->request->amount, $query->remote_host;
