#!/usr/bin/perl

use CGI;
use DBI;
use strict;
unshift(@INC, '.');
use ipac_cfg;

my $q = new CGI;
my $path="https://" . $q->server_name();
my $cgi=$path . "/cgi-bin";
my $dbh;
my $sth;
my @row;
my $user = $ENV{REMOTE_USER};
my $login;
my $price;
my $cust_id;
my $cash;
my $logins;
my $refer=$q->referer();
my $oldp;
my @logins;

if ($ENV{HTTPS} ne "on" || $user ne "admin") {
    print $q->header(-type=>"text/html;", -status=>'403 Forbidden'),
	    $q->start_html('Forbidden'),
	    $q->h1('You dont have permission to access this script'),
	    print $user, "fuck<P>", $ENV{HTTPS};
	    $q->end_html;
    exit;
}

if ($q->param('login') ne "") {
	$dbh = DBI->connect("dbi:Pg:dbname=$ipac_cfg::pg_dbname",
                    	    $ipac_cfg::pg_login, $ipac_cfg::pg_pwd,
	            	    { RaiseError => 1, AutoCommit => 0 });
	$login=$q->param('login');
	$price=$q->param('price');
	$sth = $dbh->prepare("select cust_id from customers where login=?");
	$sth->execute($login);                                              
	@row = $sth->fetchrow_array;                                        
	$sth->finish;                                                       
	$cust_id=$row[0];                                                   

	$dbh->do(q{update cash set cash=(select cash from cash where cust_id=?)+? where
	    cust_id=?}, undef, $cust_id, $price, $cust_id) or die $dbh->errstr;
	$dbh->commit();
	$dbh->disconnect  or warn $dbh->errstr;
##	reconfig();
##	print $q->end_html;
        $oldp=$q->param('refer');
	print "Location: $oldp\n";
}

print  $q->header,
       $q->start_html(-title=>'Make payment');

print "<table><tr><td>".
	"<IMG BORDER=0 ALT=\"ipac-ng logo\"".
	"SRC=\"$path/poweredby.png\"></td><td>".
	"<center><font color=\"#ff0000\" size=6>ipac-ng make payment</font></center>".
	"</td></tr></table><A HREF=\"http://sf.net/projects/ipac-ng\">".
    	"ipac-ng home page</A>&nbsp;&nbsp;";
print "<A HREF=\"$path/stat\">Go to main page</A>&nbsp;&nbsp;";
print $ipac_cfg::menu;

$dbh = DBI->connect("dbi:Pg:dbname=$ipac_cfg::pg_dbname",
                        $ipac_cfg::pg_login, $ipac_cfg::pg_pwd,
	                             { RaiseError => 1, AutoCommit => 0 });

if ($q->param('cust') ne '') {
	$sth = $dbh->prepare("select login from customers where cust_id=?");
	$sth->execute($q->param('cust')) or die $sth->errstr;
} else {
	$sth = $dbh->prepare("select login from customers order by login");
	$sth->execute() or die $sth->errstr;
}
while (@row = $sth->fetchrow_array) {
	push(@logins, $row[0]);
}
$sth->finish;
print "<P><TABLE CELLPADDING=2 CELLSPACING=1 BORDER=0><tr>",
	$q->td(['Login', 'Cash']),
	"</tr>";

print $q->startform, "<tr>",
	"<td>", $q->popup_menu('login', \@logins), "</td>",
	"<td>", $q->textfield('price'), "</td>",
	$q->hidden('refer', $refer),
	"<td>", $q->submit(), "</td></tr></table>", $q->endform;

$dbh->disconnect or warn $dbh->errstr;
print $q->end_html;
