#!/usr/bin/perl -w
#Transfer money from main account to extended
#Get users
#Create Extaccount if not exists
#Check deposit. If deposit > $value take to extended

use vars qw(%RAD %conf @MODULES $db $html $DATE $TIME $GZIP $TAR
$MYSQLDUMP
%ADMIN_REPORT
$DEBUG
);

my $transfer_sum = 0;
my $debug        = 1;
my $version      = 0.4;
my $gid          = 0;

use strict;
use FindBin '$Bin';

require $Bin . '/../libexec/config.pl';
unshift(@INC, $Bin . '/../', $Bin . '/../Abills', $Bin . "/../Abills/$conf{dbtype}");
require Abills::SQL;
Abills::SQL->import();
require Users;
Users->import();
require Admins;
Admins->import();
require Finance;
Finance->import();
require Abills::HTML;
Abills::HTML->import();
$html = Abills::HTML->new({ CONF => \%conf });

my $sql   = Abills::SQL->connect($conf{dbtype}, $conf{dbhost}, $conf{dbname}, $conf{dbuser}, $conf{dbpasswd}, { CHARSET => ($conf{dbcharset}) ? $conf{dbcharset} : undef });
my $db    = $sql->{db};
my $admin = Admins->new($db, \%conf);
$admin->info($conf{SYSTEM_ADMIN_ID}, { IP => '127.0.0.1' });

if ($admin->{errno}) {
  if ($admin->{errno} == 2) {
    print "Can't find system administrator. ID $conf{SYSTEM_ADMIN_ID}\n";
  }
  else {
    print "$admin->{errno} $admin->{errstr}\n";
  }
  exit 0;
}

$conf{EXT_BILL_ACCOUNT} = 1;

my $users = Users->new($db, $admin, \%conf);

require "language/$conf{default_language}.pl";
use POSIX qw(mktime strftime);
my $payments = Finance->payments($db, $admin, \%conf);
$users->{debug}=1 if ($debug> 5);
my $users_list = $users->list({ PAGE_ROWS  => 100000, 
	                              COLS_NAME  => 1,
	                              COMPANY_ID => 0
	                             });



foreach my $u (@$users_list) {
  my $deposit = $u->{deposit};
  my $uid     = $u->{uid};
  print "$uid $u->{id} $deposit " if ($debug > 0);

  if ($u->{disable}) {
    print "$u->{disable}" if ($debug > 0);
  }
  else {
    print "Ext Bill Not exist" if ($debug > 0);
    $users->change($uid, { UID => $uid, CREATE_EXT_BILL => 1 });
    if ($users->{errno}) {
      print "Error";
      exit;
    }

    if ($transfer_sum && ($deposit > $transfer_sum)) {
      my $sum2extbill = $transfer_sum;
      my $user        = $users->info($uid);
      print " Transfert: $sum2extbill" if ($debug > 0);
      $users->query($db, "UPDATE payments SET sum=sum-$sum2extbill WHERE  uid='$uid';", 'do');
      $users->query($db, "UPDATE bills SET deposit=deposit-$sum2extbill WHERE id='$user->{BILL_ID}';", 'do');

      $payments->add(
        $user,
        {
          SUM      => $sum2extbill,
          BILL_ID  => $users->{EXT_BILL_ID},
          DESCRIBE => 'Ext bill Transfert',
          METHOD   => 0,
          EXT_ID   => ''
        }
      );
    }
  }
  print "\n" if ($debug > 0);
}

