#!/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 $options = "0";
my $user = $ENV{REMOTE_USER};
my $login;
my $name;
my $surname;
my $phone;
my $ipaddr;
my $cash;
my $kredit;
my $email;
my $address;
my $comment;
my $detail;
my %yes_no = ('f'=>'no', 't'=>'yes');
                                     
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'),
	    $q->end_html;
    exit;
}

if ($q->param('login') ne "") {
	$login = $q->param('login');
	print ("Status: 302 Moved\n");
	print "Location: $cgi/edit_cust?log=$login\n\n";
}

print  $q->header,
       $q->start_html(-title=>'Add a customer');

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 add new customer</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;

$options = print_get_form();
if ($q->param('login') eq "") {
	print $q->end_html;
	exit;
}

($login, $name, $surname, $phone, $email, $ipaddr, $cash, $kredit, $address, $comment, $detail)
	= split(/\|/, $options, 11);

$dbh = DBI->connect("dbi:Pg:dbname=$ipac_cfg::pg_dbname",                  
                        $ipac_cfg::pg_login, $ipac_cfg::pg_pwd,            
                                 { RaiseError => 1, AutoCommit => 0 });
$sth = $dbh->prepare("SELECT login from customers where login = ?");
$sth->execute($login) or die $sth->errstr;
@row = $sth->fetchrow_array;
$sth->finish;

if ($row[0] ne "") {
	print "Error, login name '$login' already exist";
	$dbh->disconnect or warn $dbh->errstr;
	exit;
}

$dbh->do(q{insert into customers (login, name, sname, ip_addr, phone, e_mail, address, comment, detailed) values (?, ?, ?, ?, ?, ?, ?, ?, ?)}, 
	    undef, $login, $name, $surname, $ipaddr, $phone, $email, $address,
		    $comment, $detail);
$sth = $dbh->prepare("insert into cash (cust_id) ".
			"select cust_id from customers where login = ?");
$sth->execute($login);
$sth = $dbh->prepare("update cash set cash = ?, kredit = ? ".
	    "where cash.cust_id=customers.cust_id and customers.login = ?");
$sth->execute($cash, $kredit, $login);
$sth = $dbh->prepare("SELECT cust_id from customers where login = ?");
$sth->execute($login) or die $sth->errstr;
@row = $sth->fetchrow_array;
$sth->finish;
#$q->append('login', 'blyaha-muha');
$dbh->commit;
print "User $login succesfully added";
$dbh->disconnect  or warn $dbh->errstr;
print $q->end_html;

sub print_get_form {
	my $q = new CGI;
	print $q->startform,
	    "<P><TABLE CELLPADDING=2 CELLSPACING=1 BORDER=0>",
	    $q->Tr([
		$q->td(['Login', $q->textfield('login')]),
		$q->td(['Name', $q->textfield('name')]),
		$q->td(['SurName', $q->textfield('surname')]),
		$q->td(['Phone', $q->textfield('phone')]),
		$q->td(['Email', $q->textfield('email')]),
		$q->td(['IP', $q->textfield('ipaddr')]),
		$q->td(['Cash', $q->textfield('cash')]),
		$q->td(['Maximum Loan', $q->textfield('kredit')]),
		$q->td(['Address', $q->textfield('address')]),
		$q->td(['Comment', $q->textfield('comment')]),
		$q->td(['Detailed', $q->popup_menu('detail', ['f', 't'], 'f', \%yes_no)])
	    ]), "</table>",
		$q->submit(), $q->endform;
	if ($q->param) {
		return sprintf("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s", 
						$q->param('login'), 
						$q->param('name'),
						$q->param('surname'),
						$q->param('phone'),
						$q->param('email'),
						$q->param('ipaddr'),
						$q->param('cash'),
						$q->param('kredit'),
						$q->param('address'),
						$q->param('comment'),
						$q->param('detail'));
	}
}
