#!/usr/bin/perl 

BEGIN {
    if (!$ENV{'PERL5LIB'} || !$ENV{'OPALS_CONF'}) {
        exit 1;
    }
}
use Opals::Context;

use strict;
my $dbh = Opals::Context->dbh();;
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}
$| = 1;

use JSON;


my $dbh = Opals::Context->dbh();
updateUserLoanStats($dbh);

############################################################
sub updateUserLoanStats{
    my($dbh) =@_;
    my $sth=$dbh->prepare("select uid,circStats from opl_user where uid=422");
    
    $sth->execute();
    while(my($uid,$circStats)=$sth->fetchrow_array){
        my $circStats=getUserIdloanList($dbh,$uid);
        $dbh->do("update opl_user set circStats=? where uid=?",undef,to_json($circStats),$uid);
    }
}
############################################################
sub getUserIdloanList{
    my($dbh,$uid) =@_;
    my $sth=$dbh->prepare("select idloan, left(dateLoan,4) year from opl_loan where uid = ?");
    $sth->execute($uid);
    my $idloanList=[];
    my $stats={L=>[]};
    while(my($idloan,$year)=$sth->fetchrow_array){
        push @{$stats->{'L'}},$idloan;
        $stats->{$year} = 0 if(!$stats->{$year});
        $stats->{$year}++;
    }
    return $stats;
}

