#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Digest::SHA qw(
    sha1_base64
    sha1_hex
);

use Opals::Context;

use Opals::Transactions qw(
    trans_recordFine
    trans_recordFine_Ext
    trans_getFineDetail
    trans_getBalance
    
);
use Opals::Fines qw(
    fine_getUserByOdl_id
);
use JSON;

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

my $cgi      = CGI->new;
my $input    = $cgi->Vars();


my ($status,$errorCode,$errorMsg)    ;
   my $material =$input->{'materialSel'};

   my @daysOverdue  = ($cgi->param('daysOverdue'));
   my @material     = ($cgi->param('material'));
   my @odl_id       = ($cgi->param('odl_id'));
   my @rate         = ($cgi->param('rate'));
   my @fgvAmount    = ($cgi->param('fgvAmount'));
   my @odl_type     = ($cgi->param('odl_type'));
   my @charge       = ($cgi->param('charge'));
   my @loanType     = ($cgi->param('loanType'));

   my @fineTransList =();
   my $loginuid     = $template->param('curUserId');
   my $n= scalar(@odl_id);
  for(my $i=0; $i< scalar(@odl_id); $i++){
      my $odl_id       = @odl_id[$i];
      my $user         = fine_getUserByOdl_id($dbh,$odl_id);
      my $uid          = $user->{'uid'};
      my $material     = @material[$i]; 
      my $rate         = @rate[$i]; 
      my $forgiven     = @fgvAmount[$i];
      my $daysOverdue  = @daysOverdue[$i];
      my $charge       =@charge[$i];
      my $loanType     =@loanType[$i];
        if(@odl_type[$i] !~ m/^overdue$/i){
          $daysOverdue=0;
      }
      if($odl_id> 0 && $uid>0){
          my $tid;
          if($loanType eq 'daily'){
            $tid = trans_recordFine($dbh,$uid,$odl_id,$rate,$material,$daysOverdue,$forgiven,$charge,$loginuid);
          }
          else{        
            $tid = trans_recordFine_Ext($dbh,$uid,$odl_id,0,$rate,$material,0,$daysOverdue,$forgiven,$charge,$loginuid);
          }
          if($tid && $tid >0){
                my $trans =trans_getFineDetail($dbh,$tid);
                if($trans && $trans->{'tid'} ==$tid){
                    push @fineTransList,$trans;
                }
          }
      }
     
  }   
  print "Content-type: text/plain\n\n";
  print to_json({fines =>\@fineTransList},{pretty=>1} );
    
 
#------------------------------------------------------------------------------
