#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use JSON;

use Opals::Context;

use Time::localtime;

use Opals::Tb_Record qw(
    
    tb_item_findByBarcode

);


my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my $tm = localtime;
my $todayStr = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);

    my $uid = -1;
    my $errUser = 0;
    $uid=$input->{'uid'};
    my $odList = getOdList($dbh, $uid) ;
    my $odListJSON = to_json($odList, {pretty => 1})  ;
    print "Content-type: text/plain\n\n";
    print   $odListJSON;


#-------------------------------------------------------------
sub getOdList{
    my ($dbh,$uid)=@_;
    my $list = _getUserListOD($dbh,{uid=>$uid});
    return $list;

}

sub _getUserListOD{
    my ($dbh, $params) = @_;
    my $sth = $dbh->prepare(<<_STH_);
select  barcode,dateLoan,dateDue,cast((timestamp(now())-timestamp(dateDue)) as signed integer) as deltaDateDue from tb_loan where uid=? && dateReturn is null;
_STH_
    $sth->execute($params->{'uid'}) ;
    my @tmpList ;
    my @loanList;
    while (my $loan = $sth->fetchrow_hashref){
        #if ($loan->{'deltaDateDue'} > 0) {
            $loan->{'overdue'} = $loan->{'deltaDateDue'} > 0? 1:0;
            push @tmpList, $loan;
        #}
    }
    foreach my $loan (@tmpList){
        my $itemInfo = Opals::Tb_Record::tb_item_findByBarcode($dbh, $loan->{'barcode'}, 1);
        if ($itemInfo) {
            push @loanList, {
                barcode     => $loan->{'barcode'},
                dateLoan    => $loan->{'dateLoan'},
                dateDue     => $loan->{'dateDue'},
                overdue     => $loan->{'overdue'},
                rid         => $itemInfo->{'rid'},
                title       => $itemInfo->{'title'},
                author      => $itemInfo->{'author'},
                isbn        => $itemInfo->{'isbn'},
                publisher   => $itemInfo->{'publisher'},
            };
        }
    }
    $sth->finish;
    return \@loanList;
}


