#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference

);

use Opals::User qw(
    user_getInformationById
);

use Opals::Date qw(
    date_now
    date_text
    date_DHM_text
    date_text
);

use Opals::Tb_Circulation qw(

    circ_getUserListLoan
    circ_getUserListReserve
    circ_getUserLoanHistory
    
);
#    circ_userListReserve
#    circ_userListLoan
#    circ_isOnReserve

use Opals::Tb_Record qw(
    
    tb_item_findByBarcode

);

use Opals::Tb_Transactions qw(
    trans_getUnpaidFineList
    
);

use POSIX qw(
    floor
);

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

my $cgi      = CGI->new;
my $input    = $cgi->Vars();
my $uid       = $input->{"uid"};

my ($status,$errorCode,$errorMsg)    ;
my $pref = tmpl_preference($dbh);

my $today = date_now();
$today =~ s/([\d]{4}-[\d]{2}-[\d]{2}) ([\d:])+/$1/;
#$today = date_text($today, 1);

my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => '/txtbk/ajax/circ/userCircInfo.tmpl',
        reqPermission   => 'tb_circ_loan|tb_circ_return',
    }
);
   my $libname       = $pref->{'libname'};
   my ($userInfo,$guardian) =user_getInformationById($dbh,$uid);

   my ($numOverdue,$loanList) =GetLoanItems($dbh, $uid);
   my $reserveList = GetReservedItems($dbh, $uid);
   my $lostList = GetLostItems($dbh, $uid, 3);
   my $transList = getUnpaidList($dbh, $uid);
   my $loanHistoryList = getLoanHistory($dbh, $uid);

   $template->param(
        firstName   => $userInfo->{'firstname'},
        lastName    => $userInfo->{'lastname'},
        email       => $userInfo->{'email'},
        homeRoom    => $userInfo->{'homeroom'},
        teacher     => $userInfo->{'teacher'},
        libName     => $libname ,
        loanList    => $loanList,
        reserveList => $reserveList,
        lostList    => $lostList,
        transList   => $transList,
        loanHistory => $loanHistoryList,
        today       => $today,
    );

tmpl_write($dbh, $cgi, $cookie, $template);

#----------------------------------------------------------
sub GetReservedItems
{
    my ($dbh,$uid) = @_;
    
    my $reserveList = circ_getUserListReserve($dbh, $uid);
    foreach my $reserve (@$reserveList) 
    {
        $reserve->{'dateReserve'} = date_text($reserve->{'dateReserve'}, 0);
        if($reserve->{'numCopyReserve'}==0){
            $reserve->{'dateExpiry'}  ='';
        }
        else{
            $reserve->{'dateExpiry'}  = date_text($reserve->{'dateExpiry'}, 0);
        }
    }
    return $reserveList;
}
#----------------------------------------------------------

sub GetLoanItems
{
    my ($dbh, $uid) = @_;
    
    my  $loanList = circ_getUserListLoan($dbh, $uid);
    my $odCount = 0;
    foreach my $loan (@$loanList) 
    {
        if ( $loan->{'overdue'} ) { $odCount++; }
        $loan->{'dateLoan'} = date_text($loan->{'dateLoan'}, 0);
        $loan->{'dateDue'}  = date_text($loan->{'dateDue'}, 0);
        #$loan->{'isReserved'}=circ_isOnReserve($dbh,$loan->{'rid'}); 
=item        
        if($loan->{'barcode'} =~m/^\_\_\_(.*)/){
            $loan->{'org_barcode'} =$1;
        }
        else{
            $loan->{'org_barcode'} =$loan->{'barcode'};
        }
        if($loan->{'tempIll'} =~m/ILL|temporary/i){
            $loan->{'isTempILL'} =1;
        }
=cut        

    }
    return($odCount,$loanList);
}

sub GetLostItems {

    my ($dbh, $uid,$lost ) = @_;
=item
    my $sql = "select l.barcode, max(odl.ondate) as lostdate
            from tb_odl odl 
            inner join tb_loan l on l.id = odl.idloan 
            where uid = ? && odl.type regexp 'lost' && odl.settleDate is null 

            && l.barcode in(
		      	select i.barcode
            from tb_items i inner join
            (select ist1.* from
                (select * from tb_itemStatus ) as ist1
                left outer join
                (select * from tb_itemStatus )as ist2
            on ist1.barcode=ist2.barcode && ist1.id <ist2.id where ist2.id is null && ist1.status = ?)
            as ist on i.barcode=ist.barcode )
            group by l.barcode  order by lostdate ";
=cut
 my $sql = "select l.barcode, max(odl.ondate) as lostdate
            from tb_odl odl 
            inner join tb_loan l on l.id = odl.idloan 
            where uid = ? && odl.type regexp 'lost'
            && l.barcode in(
		      	select i.barcode
            from tb_items i inner join
            (select ist1.* from
                (select * from tb_itemStatus ) as ist1
                left outer join
                (select * from tb_itemStatus )as ist2
            on ist1.barcode=ist2.barcode && ist1.id <ist2.id where ist2.id is null && ist1.status = ?)
            as ist on i.barcode=ist.barcode )
            group by l.barcode  order by lostdate ";

   my @value =  ($uid,$lost);

   my $itemList =  $dbh->selectall_arrayref($sql, { Slice => {} }, @value);
   my @lostList=();
   foreach my $i (@$itemList) {
       my $itemInfo = tb_item_findByBarcode($dbh,$i->{'barcode'});
       push @lostList, {
            title   => $itemInfo->{'title'},
            author      => $itemInfo->{'author'},
            price       => $itemInfo->{'price'},
            callnumber  => $itemInfo->{'classNumber'},
            barcode     => $i->{'barcode'},
            lostdate    => $i->{'lostdate'},
            dateLost    => date_text($i->{'lostdate'},0),
       };
   }
   return \@lostList;
}
sub getUnpaidList{
    my($dbh,$uid)=@_;
    my @transList = trans_getUnpaidFineList($dbh, $uid);
    foreach my $t(@transList){
        $t->{'date'} = date_text($t->{'date'});
    }
    return \@transList;
}


sub getLoanHistory {
    
    my($dbh,$uid)=@_;
    my $list = circ_getUserLoanHistory($dbh, $uid);
    return $list;
}
