#!/usr/bin/perl
use Mysql;

use Time::localtime;
use Time::Local;
$tm = localtime;
$d100=3100;
$d100=int((timelocal(0,0,0,1,$tm[4]+1,$tm[5])-timelocal(0,0,0,1,,$tm[4],$tm[5]))/24/36) if $tm[4]<11; #days x 100
$d100=3000;
my ($db,$user,$pass) = ("imya_mysql","loginmysql","passmysql");

my  $refprc="/home/investcom/www/cgi-bin/refprc.txt";

sub exec_qry {
    my($id,$query,$debug) = @_;
    $id    ||= "?"; 
    $sth=$dbh->query($query);
    if (!$sth) {
        $query = "\n\tquery $query";
	$error = Mysql->errmsg;
        print qq{Not ok $id:\n\terrmsg $error$query\n};
	return 0;
    }
    if ($debug && 0) {
	$,="\t";
	my $n = $dbh->listfields($debug);
	my $s = $dbh->query("SELECT * from  $debug");	
	print $n->name,"\n\n";
	print @row,"\n" while (@row = $s->fetchrow());
    }
    return $sth;
}

open(INPUT, "< $refprc");
$refprc=<INPUT>;
close(INPUT);
$dbh = Mysql->connect("localhost",$db,$user,$pass) ||  die "not ok 3: $Mysql::db_errstr\n";
exec_qry(1,"
lock tables invest_invest as i WRITE, invest_invest WRITE,
invest_users as u WRITE, invest_users WRITE,
invest_percents as p READ,
invest_invoice WRITE
");
exec_qry(2,"
CREATE TEMPORARY TABLE t_i_i
SELECT i.id, i.user_id, i.data, i.summ, i.reinvest, i.time_, i.status,
i.summ*p.per_month/$d100 as x_summ
FROM invest_invest i, invest_percents p
WHERE (
i.summ >= p.min_s
) AND (
i.summ < p.max_s
) AND (
i.time_ >= p.min_period
) AND (
i.time_ < p.max_period
) AND (
i.status=0
)
","t_i_i");
exec_qry(3,"
replace invest_invest  (id, user_id, data, summ, reinvest, time_, status)
select id, user_id, data, summ+x_summ as summ, reinvest, time_, status from t_i_i
where reinvest=1
");
exec_qry("3a","
CREATE TEMPORARY TABLE t_i_r
SELECT  u.ref_id as id, i.x_summ*$refprc as summ
FROM t_i_i i, invest_users u
WHERE (i.user_id = u.id) AND (u.ref_id > 0)
","t_i_r");
exec_qry("3b","
insert into t_i_i (user_id, x_summ)
select id, summ from t_i_r
");
exec_qry(4,"
insert into t_i_i (user_id, x_summ)
select user_id, summ from invest_invest
where ((TO_DAYS(NOW()) - TO_DAYS(data)) >= time_) 
AND (status=0)
");
exec_qry(5,"
UPDATE invest_invest
SET status = 2
where ((TO_DAYS(NOW()) - TO_DAYS(data)) >= time_)
AND (status=0)
");
exec_qry(6,"
CREATE TEMPORARY TABLE t_i_u_b
SELECT user_id as id, sum(x_summ) as extra
FROM t_i_i
WHERE reinvest=0
group by id
");
exec_qry(7,"
CREATE TEMPORARY TABLE t_i_u
SELECT u.id, u.data, u.login, u.pass, u.wmid, u.purse, u.email, u.balance+t.extra as balance, u.ref_id
FROM invest_users u, t_i_u_b t
WHERE u.id = t.id
");
exec_qry(8,"
replace invest_users  (id, data, login, pass, wmid, purse, email, balance, ref_id)
select
 id, data, login, pass, wmid, purse, email, balance, ref_id
 from t_i_u
");
exec_qry(9,"
delete FROM invest_invoice
WHERE (sum = '0.00') and (now() > DATA + INTERVAL 7200 SECOND) 
");

