#!/usr/bin/perl
use strict;

use Opals::Context;
use Time::localtime;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);

use Opals::Date qw(
    date_parse
    date_text
    date_today
    date_profileList
);

use Opals::User qw(
    user_getInformationById
    user_list

);

use Opals::Tb_Transactions qw(
    trans_getUnpaidFineList
    trans_getBalance
    trans_doPayment
    trans_getTaxTable
    trans_doRefund
    trans_getUnrefundLostList
 
    trans_getTotalCharge
    trans_getTotalForgiven
    trans_getTotalPaid
    trans_getTotalRefundLost
    trans_getTotalRefund
    
    trans_getDetailBalance
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);


my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }
my $cgi    = CGI->new;
my $input  = $cgi->Vars();
#my $uid    = $cgi->cookie('borrower');#$input->{'uid'};
my $op     = $input->{'op'};

my $offset    =  0; #$input->{'offset'};
my $size      =  10; #$input->{'size'};
my $dir       =  'asc' ;#$input->{'dir'};

 
my $pref = tmpl_preference($dbh);
my $libname  =  $pref->{'libname'};
   $libname =~ s/<br>/ /g;
my ($permission, $cookieList, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => '/txtbk/circ/payments.tmpl',
            reqPermission   => 'tb_fine|tb_payment',
        }
);

    my $tm = localtime;
    my $dateToday = sprintf("%04d-%02d-%02d", 
                            $tm->year+1900, 
                            ($tm->mon)+1, 
                            $tm->mday);
# See User.pm for the list of permissions
if ($permission && $permission->{'tb_fine'}) {
    my ($uid,$status) = getUID();
    if ($uid >= 0){
        push @$cookieList, $cgi->cookie(
            -name   => 'borrower',
            -value  => $uid
        );
        my $u_block=($status==1?0:1);
        $template->param(u_block =>$u_block);
        $template->param(hiddenid => $uid);
        my $loginuid = $template->param('curUserId');
        my ($responsibleInfo, $g) = user_getInformationById($dbh, $loginuid);
        my $respName = $responsibleInfo->{'firstname'} . " " . $responsibleInfo->{'lastname'};
        if($op eq  'payment'){
            my ($tid, $odl_id, $fgvAmt, $chrgAmt, $payAmt);
            my $payAmountTotal = $input->{'payAmount'}; 
            my $numTrans = $input->{'numTrans'}; 
            my $totalUnpaid= 0.00;
            my @payArray=();   
            my @payTid =();
            if($numTrans>0){        
                for (my $i=0; $i < $numTrans ; $i++){
                    $tid     = $input->{'tid_'.$i};
                    $odl_id  = $input->{'odl_id_'.$i};
                    $fgvAmt  = $input->{'fgvAmt_'.$i};
                    $chrgAmt = $input->{'chargeAmt_'.$i};
                    if ( $fgvAmt > 0 || $payAmt != 0){ 
                        push @payTid,$tid;
                        push @payArray,{tid=>$tid,
                                        odl_id=>$odl_id,
                                        forgiveAmount=>$fgvAmt,
                                        chargeAmount=>$chrgAmt
                                    };
                    }
                }
                my $tid =trans_doPayment($dbh,$uid,$respName,\@payArray,$payAmountTotal);
                my $tidList = join(":",@payTid);
                $template->param(payment_tid=>$tid);
            }
        }
        elsif($op eq  'refund'){
            my $rAmount= $input->{'rAmount'};
            my $tid =trans_doRefund($dbh,$uid,$respName,$rAmount);
            $template->param(
                refundAmount   => $rAmount,
                dateToday      => date_text($dateToday,1),
                refund_tid     => $tid,
            );
       }
        my ($userInfo, $guardian) = user_getInformationById($dbh, $uid);
        $template->param(
            user_uid            => $userInfo->{'uid'},
            user_barcode        => $userInfo->{'userbarcode'},
            user_username       => $userInfo->{'username'},
            user_firstname      => $userInfo->{'firstname'},
            user_lastname       => $userInfo->{'lastname'},
            homeroom            => $userInfo->{'homeroom'},
            teacher             => $userInfo->{'teacher'},
            notes               => $userInfo->{'notes'},
            libname             => $libname,
        );
        ########  Get unpaid transactions  ############
        my @transTbl = trans_getUnpaidFineList($dbh,$uid,$dir);
        my $idx=0;
        foreach my $tr(@transTbl){
            $tr->{'idx'} =$idx++;
            $tr->{'barcode'} =~ s/^___//g;
            $tr->{'barcode'} =~ s/_\d\d\d$//g;
        }
        my @taxTbl =trans_getTaxTable($dbh);
        if(scalar(@taxTbl)>0){
            $template->param(taxTbl=>\@taxTbl);
        }
        $template->param(
            transList   => \@transTbl,
            numTrans    => scalar(@transTbl),
            dateTodayStr=> $dateToday,
        );
        ########  Get refund transactions ############ 
        my  ($tidList,$totalRefund) =("",0);              
        my @refundTbl = trans_getUnrefundLostList($dbh,$uid,$dir);
        foreach my $r(@refundTbl){
            $r->{'refundBalance'} = sprintf("%.2f",abs($r->{'refundBalance'}));
            $totalRefund   += $r->{'refundBalance'};
        }
        $template->param(
            refundList  => \@refundTbl,
            tidList     => $tidList,
        );
    }#//if ($uid >= 0)
    my ($totalCharge,$totalPaid,$totalFgvn,$totalRefundLost,$totalRefund) = trans_getDetailBalance($dbh,$uid,0);
    my $balance = trans_getBalance($dbh,$uid,0);
    if ($balance == 0){
        $template->param(zeroBalance    => 1);
    }
    my $totalFgvnPaid = $totalFgvn + $totalPaid;
    $totalCharge = sprintf("%.2f",$totalCharge);
    $totalFgvnPaid = sprintf("%.2f",$totalFgvnPaid);
    $totalRefund =  sprintf("%.2f",$totalRefund);
    $balance = sprintf("%.2f",$balance);
    #my $totalPaidBack = sprintf("%.2f",$totalCredit);
    #$totalDebit = sprintf("%.2f",$totalDebit);
    if($balance > 0 && $balance !=  $totalCharge ){
        $template->param(
            unBalance   => 1,
        );
    }
    $template->param(
       balance => $balance>0?$balance:0,    
       refund  => $balance<0?abs($balance):0 ,    
       hasRefund  => $balance<0?abs($balance):0,
       totalCharge => $totalCharge,
       totalFine => $balance,
       totalFgvn => $totalFgvn,
       totalPaid => $totalPaid,
       totalFgvnPmt => $totalFgvnPaid,
       totalRefund => $totalRefund,
       totalRefundLost=>$totalRefundLost,
       checkid => 1
    );
}
    
    my $paymentMsgMap =loc_getMsgFile('circ/payment.msg');
    loc_write($template,$paymentMsgMap);

    tmpl_write($dbh, $cgi, $cookieList, $template); 
#---------------------------------------------------------
sub getUID{
    my ($uid,$status)=(-1,0);
    if ( $input->{'uInput'}) {
        # my @uList = user_list($dbh,  $input->{'uInput'}, USER_ACTIVE);
        my @uList = user_list($dbh,  $input->{'uInput'}, undef);
        if(scalar(@uList)==1){
           $uid = $uList[0]->{'uid'};
           $status= @uList[0]->{'status'};
           if( @uList[0]->{'status'}==1 ){
               $template->param(block =>0);
               @uList[0]->{'block'}=  0;
           }
           else {
               $template->param(block =>1);
           }
            $template->param(uPerson => 1);
        }
        elsif(scalar(@uList)>=1){
            for(my $i=0; $i < scalar(@uList) ; $i++){
                @uList[$i]->{'block'}= @uList[$i]->{'status'}==1 ? 0:1;
            }
           # $template->param(uList => \@uList);
        } 
     $template->param(uList => \@uList);
    }
    elsif ( $input->{'InputFromList'}){
        $uid = $input->{'InputFromList'};
        my ($uInfo,$ttt)=user_getInformationById($dbh,$uid);
        $status=$uInfo->{'status'};
    }
    else{
        if ( $input->{'hiddenid'} ) { 
            $uid = $input->{'hiddenid'}; 
        }
        else { 
            $uid = $cgi->cookie('borrower'); 
        }
        my ($uInfo,$ttt)=user_getInformationById($dbh,$uid);
        $status=$uInfo->{'status'};
    }
    return ($uid,$status);
}

