#!/usr/bin/perl
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::Transaction qw(
    trans_getUnpaidChargeList  
    trans_getBalance 
);
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);

use JSON;

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        => 'billing/payments.tmpl'
        }
);

    my $tm = localtime;
    my $dateToday = sprintf("%04d-%02d-%02d", 
                            $tm->year+1900, 
                            ($tm->mon)+1, 
                            $tm->mday);

my $formType="k_12";
my $pref = tmpl_preference($dbh);
my $libType = $pref->{'libraryType'} || 'k-12';
if($libType eq 'public'){
    $formType="public";
}
elsif($libType eq 'academy'){
    $formType="academy";
}
my $uid = $input->{'uid'};
if(!$uid || $uid<=0){
    $uid = $cgi->cookie('borrower');
}

if($uid>0){
    my ($userInfo, $guardian) = user_getInformationById($dbh, $uid);
    my $balance= trans_getBalance($dbh, $uid);
    $userInfo->{"accountBalance"}=$balance;
    my $userJSON   = to_json($userInfo, {pretty => 1})  ;
    my $chargeList = trans_getUnpaidChargeList($dbh,$uid);;
    my $chargeListJSON   = to_json($chargeList, { pretty => 1})  ;
    my $slipPrinter      = (defined $syspref->{'slipPrinter'} && $syspref->{'slipPrinter'} >0) ?1: 0;
    $template->param(userInfo   =>$userJSON,
                     chargeList =>$chargeListJSON,
                     slipPrinter=>$slipPrinter);

    push @cookieList, $cgi->cookie(
                    -name       => 'borrower',
                    -path       =>'/',
                    -value      => $uid,
            );

}

        
        $template->param(
            libname  => $libname,
            uid      => $uid,"$formType"=>1,
            libType  =>$libType

        );

  $template->param(hlpUrl     => Opals::Constant->getHlpUrl('payments') );

    my $paymentMsgMap =loc_getMsgFile('circ/payment.msg');
    loc_write($template,$paymentMsgMap);

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





