#!/usr/bin/perl

package base;

foreach $service (@CFG::SERVICES) {
	require "/usr/lib/cherry/$service/utils" if(-f "/usr/lib/cherry/$service/utils");
}

foreach $module (@CFG::MODULES) {
	require "/usr/lib/cherry/$module/utils" if(-f "/usr/lib/cherry/$module/utils");
}


sub create_client {
	my ($client_id, 
	$oper_id, $name, $address_jur, $address_post, $contact_phone, 
	$contact_fax, $client_type, $passport, $inn, $bank_account_num,  
	$bank_corr_num, $bank_name, $bank_id, $balance, 
	$currency_type, $options) = @_;

	my $sql;
	my $sth;

	if( !$client_id ) {

	($client_id)= $main::dbh->selectrow_array("SELECT nextval('base_clients_id_seq') ");
	if( $client_id < 1) { $client_id = 1; }
		
	}
	
	$sql = "INSERT INTO base_clients (client_id, oper_id, name, address_jur, address_post, contact_phone, contact_fax, client_type, passport, inn, bank_account_num,  bank_corr_num, bank_name, bank_id, balance, currency_type, options) VALUES ( $client_id, '$oper_id', '$name', '$address_jur', '$address_post', '$contact_phone', '$contact_fax', '$client_type', '$passport', '$inn', '$bank_account_num',  '$bank_corr_num', '$bank_name', '$bank_id', $balance, '$currency_type', '$options')";
	
        $sth = $main::dbh->prepare($sql);
        if( ! $sth ) { return ""; }
        if( ! $sth->execute ) { return ""; }

	return $client_id;
}

sub destroy_client {
        my ($client_id) = @_;
        my $sth;
        my $sql;
        my $rv;

        $sql = "DELETE FROM base_clients WHERE client_id = $client_id";

         $sth = $main::dbh->prepare($sql);

                if( !$sth ) { return 0; }

                $rv = $sth->execute;
                if( !$rv ) { return 0; }

        return $rv;
}


sub encrypt {
    local($salt);               # initialization
    local($i, $rand);
    local(@itoa64) = ( 0 .. 9, a .. z, A .. Z ); # 0 .. 63
    local($passwd) = shift @_;

    warn "calculate salt\n" if $verbose > 1;
    # to64
    for ($i = 0; $i < 8; $i++) {
        srand(time + $rand + $$);
        $rand = rand(25*29*17 + $rand);
        $salt .=  $itoa64[$rand & $#itoa64];
    }

    return crypt($passwd,$salt);
}

sub history {
	my($need_reboot, $changed_tables, $variables2) = @_;

	my($variables);
	my($key);



	foreach $key (keys %CGI::Deurl::query) {
        	$variables .= "$key=\"".$CGI::Deurl::query{$key}."\" ";
	}

	$variables =~ s/\\/\\\\/g;
	$variables =~ s/\'/\\\'/g;
	$main::dbh->do("INSERT INTO base_history (date, action, operator, descr, reboot, changed_tables, oper_id) VALUES ('now', '$main::tpl', '$main::operator', '$variables $variables2'  , ". 1*$need_reboot.", '$changed_tables','$main::oper_id')");

}

1;
