#!/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::Mail qw(
    mail_send
);

use Opals::Tb_Circulation qw(

    circ_getUserListLoan
    circ_getUserListReserve
);

use Opals::Tb_Record qw(
    
    tb_item_findByBarcode

);

use Opals::Tb_Transactions qw(
    trans_getUnpaidFineList
    
);

use POSIX qw(
    floor
);
use Opals::Date qw(
    date_today
    date_text
);

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

my $cgi     = CGI->new;
my $input   = $cgi->Vars();
my $uid     = $input->{"uid"};
my $op      = $input->{"op"};
my $to      = $input->{'emailTo'};
my $subject = $input->{'emailSubject'};



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

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

my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => '/txtbk/util/save_sendUserCircInfo.tmpl',
        reqPermission   => 'tb_circ_loan|tb_circ_return',
    }
);
my ($libname,$userInfo,$guardian,$numOverdue,$loanList,$reserveList,$lostList,$transList,$content);
if ($permission && ($permission->{'tb_circ_loan'}|| $permission->{'tb_circ_return'})) {
   $libname       = $pref->{'libname'};
   ($userInfo,$guardian) =user_getInformationById($dbh,$uid);

   ($numOverdue,$loanList) =GetLoanItems($dbh, $uid);
   $reserveList = GetReservedItems($dbh, $uid);
   $lostList = GetLostItems($dbh, $uid, 3);
   $transList = getUnpaidList($dbh, $uid);
   $template->param(
        firstName=> $userInfo->{'firstname'},
        lastName=> $userInfo->{'lastname'},
        homeRoom=> $userInfo->{'homeroom'},
        teacher=> $userInfo->{'teacher'},
        libName=>$libname ,
        loanList=>,$loanList,
        reserveList=>$reserveList,
        lostList=>$lostList,
        transList =>$transList,
        today=>$today,
        );
    }

    
    $content = templateToSave(); 
if ($op && $op eq 'save') {
    print "Content-Type:application/x-download\n";
    print "Content-Disposition:attachment;filename=userCircInfo_tbk.html\n\n";     
    print $content;
}
elsif($op && $op eq 'saveCSV'){

}
elsif($op && $op eq 'email'){
    if (mail_send($pref, $to, $subject, $content)){
        $template->param(done=>1);
    }
    else{
        $template->param(error=>1);
    }
    $template->param(
        firstName   => $userInfo->{'firstname'},
        lastName    => $userInfo->{'lastname'},
        email       => $to,
        sendEmail   => 1
    );
    tmpl_write($dbh, $cgi, $cookie, $template);
}
else {
    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);
    }
    return($odCount,$loanList);
}

sub GetLostItems {

    my ($dbh, $uid,$lost ) = @_;
    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 templateToSave {

    my $rootDir   = Opals::Context->config('rootDir');

    my $template = HTML::Template->new(    
        filename            => "save_sendUserCircInfo.tmpl",
        path                => "$rootDir/htdocs/theme/opals/txtbk/util/",
        global_vars         => 1,
        die_on_bad_params   => 0,
        cache               => 1,
        shared_cache        => 0,
        loop_context_vars   => 1,);

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

}
