#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use POSIX qw(
    ceil
    floor
);

use Time::localtime;
use Opals::User qw(
    user_getInformationById
);
use Opals::Circulation qw(
    circ_userListLoan
    circ_isOnReserve
);
use Opals::Date qw(
    date_text
    date_DHM_text
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);

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

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

my ($permission, $cookie, $template) = tmpl_read(
    {
        dbh             => $dbh,
        cgi             => $cgi,
        tmplFile        => 'ajax/circ/getCurLoanPrtSlip.tmpl',
        reqPermission   => 'circ_loan|circ_renew',
    }
);
  ###$uid =2253;


my $tm      = localtime;
my $pos     =Opals::POS->new();
my $syspref = tmpl_preference($dbh);

  # Get COMMAND PRINTER
    my $f_typeA_bold  = {'type'  => 'A','weight'  => 'bold'};
    my $f_typeB_bold  = {'type'  => 'B','weight'  => 'bold'};
    my $f_typeA_normal= {'type'  => 'A'};
    my $f_typeB_normal= {'type'  => 'B'};
    my ($marginL_def,$marginR_def)=(0,0);
    my ($marginL,$marginR)=(7,7);

    my $cmdFont_typeB_normal  = $pos->getCmd_font($f_typeB_normal);
    my $cmdFont_typeA_normal  = $pos->getCmd_font($f_typeA_normal);
    my $cmdFont_typeA_bold    = $pos->getCmd_font($f_typeA_bold);
    my $cmdFont_typeB_bold    = $pos->getCmd_font($f_typeB_bold);
    my $cmd_alignCenter       = $pos->getCmd_align("center");
    my $cmd_alignLeft         = $pos->getCmd_align("left");
    my $cmd_alignRight        = $pos->getCmd_align("right");




if ($permission && ($permission->{'circ_loan'}|| $permission->{'circ_new'})) {
    # School/Library Info *************************************** *
    my $sName       = $syspref->{'libname'};
    my $sAddress    = $syspref->{'libAddress'} ." "
                    . $syspref->{'libCity'} ." "
                    . $syspref->{'libState'} ." "
                    . $syspref->{'libZip'} ." "
                    . $syspref->{'country'};
    my $sTel        = $syspref->{'libPhone'};   
    my $header      = createHeader($sName,$sAddress,$sTel,$f_typeA_bold,$marginL,$marginR);

    # Patron Info ************************************************
    my $patronItemPrivacy =(defined $syspref->{'patronItemPrivacy'} && $syspref->{'patronItemPrivacy'} eq '1')? 1:0 ;
    my ($patron, $guardian) = user_getInformationById($dbh, $uid);
    my $userbarcode= $patron->{'userbarcode'} || "";
    if(defined $patronItemPrivacy && $patronItemPrivacy){
        $userbarcode ="XXXXXXXXXX" . substr($userbarcode,length($userbarcode) -4);
        if(length($userbarcode)>10){
            $userbarcode =substr($userbarcode,length($userbarcode) -10);
        }
    }
     
    # Item Info  ************************************************
    my ($curLoan2Prt, $prevLoan2Prt) = getLoanList($dbh, $uid);
    my $curLoanItems    = createItemInfo($curLoan2Prt,$f_typeB_normal,$marginL,$marginR_def);
    my $prevLoanItems   = createItemInfo($prevLoan2Prt,$f_typeB_normal,$marginL,$marginR_def);

    $template->param(
            cmdBold         =>$cmdFont_typeA_bold,
            cmdNormal       =>$cmdFont_typeA_normal,
            cmdBold_A       =>$cmdFont_typeA_bold,
            cmdNormal_A     =>$cmdFont_typeA_normal,
            cmdBold_B       =>$cmdFont_typeB_bold,
            cmdNormal_B     =>$cmdFont_typeB_normal,
            cmd_alignCenter =>$cmd_alignCenter,
            firstname       =>$patron->{'firstname'},
            lastname        =>$patron->{'lastname'},
            userbarcode     =>$userbarcode,
            curDate         =>getDateStr($tm),
            curTime         =>getTimeStr($tm),
            header          =>$header,
            curLoanItems    =>$curLoanItems,
            prevLoanItems   =>$prevLoanItems,
            patronItemPrivacy=>$patronItemPrivacy
    );
    
    my $prtSlipMsgMap    =loc_getMsgFile('/circ/curLoanPrtSlip.msg');
    loc_write($template,$prtSlipMsgMap);
    tmpl_write($dbh, $cgi,$cookie , $template);


}

#-------------------------------------------------------------------------------
# get all the item(s) are checkout
#
sub getLoanList{
    my ($dbh, $uid) = @_;
    my $curLidList  = {};
    my @curLidArr   = split /,/,$cgi->cookie('borrower_curLidList');
    foreach my $lid(@curLidArr){
        $curLidList->{$lid}=1;
    }
    
    my  $loanList = circ_userListLoan($dbh, $uid);

    my ($curLoan2Prt, $prevLoan2Prt);
    foreach my $loan (@$loanList) {
        my $tmp= $loan->{'dateDue'};
        $loan->{'dateLoan'} = date_text($loan->{'dateLoan'}, 0);
        $loan->{'dateDue'}= date_text($loan->{'dateDue'}, 0);
        if($tmp !~ m/23:59:59$/g){
            $tmp= date_DHM_text($tmp, 0);
            if($tmp =~ m/(\d\d:\d\d [APM]{2})/i){
                $loan->{'timeDue'}=$1;
            }
        }
        $loan->{'barcode'} =~ s/^\_\_\_(.*)(_\d\d\d)$/$1/g;                 
        if($curLidList->{$loan->{'idloan'}}){
            push @$curLoan2Prt,$loan;
        }
        else{
            push @$prevLoan2Prt,$loan;
        }
  
    }
    
    return ($curLoan2Prt, $prevLoan2Prt);
}

#-------------------------------------------------------------------------------
sub formatDateTime{
    my ($date)= @_;
    date_text($date);

}

#-------------------------------------------------------------------------------------------------
sub createHeader{
    my($schoolName,$address,$sTel,$fs,$marginL,$marginR)=@_;
    my $header = $pos->formatTxt($schoolName,$fs,$marginL,$marginR) . "\r\n" 
               . $pos->formatTxt($address,$fs,$marginL,$marginR)  ."\r\n"
               . $pos->formatTxt($sTel,$fs,$marginL,$marginR)  ."\r\n";
    return $header;

}
#-------------------------------------------------------------------------------------------------
sub createPatronInfo{
    my($patron)=@_;
    my $name =sprintf("%s %s",$patron->{'firstname'} , $patron->{'lastname'});

    my $patronInfo=  $pos->formatTxt($name) . "\r\n" 
                  . $pos->formatTxt(sprintf("Patron Number: %s\r\n", $patron->{'userbarcode'}))  ;
              
    return $patronInfo;

}

#-------------------------------------------------------------------------------------------------
sub createItemInfo{
    my($items,$fs,$marginL,$marginR)=@_;
    my $cmdFont    = $pos->getCmd_font($fs);
    my $itemInfo;
    my $i=0;
    my $fmtStr=""; my $p= 0;
    foreach my $item (@$items){
        $p= 0;
        my $len = length($item->{'barcode'});
        my $tmpBc=$item->{'barcode'};
        if($len > $marginL){
            $p =  $len -$marginL;
        }
        $tmpBc =sprintf("%" .$p++ ."s","");
        my $tmp = $tmpBc . $item->{'title'};
        $tmp =$pos->formatTxt($tmp,$fs,$marginL,$marginR);
        substr($tmp,0, $marginL+$p-1 )=""; 
        $item->{'title'}=$cmdFont .$tmp;
        $item->{'barcode'} =$cmdFont . $item->{'barcode'};
        $item->{'dateDue'} =$cmdFont . $item->{'dateDue'};

    }
    return $items ;
}

#-------------------------------------------------------------------------------------------------
sub getDateStr{
    my($tm)=@_;
    my $dateStr=   sprintf("%02d/%02d/%02d",$tm->mon+1,$tm->mday,$tm->year -100);
    return $dateStr;
}

#-------------------------------------------------------------------------------------------------
sub getTimeStr{
    my($tm)=@_;
    my $h =$tm->hour;
    my $m =$tm->min;
    my $am_pm="AM";
    if($h>12){
        $am_pm ="PM";
        $h -=12;
    }
    my $timeStr=   sprintf("%02d:%02d %s",$h,$m,$am_pm);
    return $timeStr;
}


