#!/usr/bin/perl

use strict;
use CGI;

#use Opals::Constant;
use Opals::Context;
use Opals::Transaction qw(
  trans_payment
);

#use SIP::Map;
use SIP::Template;
use SIP::Session;

#use SIP::Utility;

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

my $cgi = CGI->new;

# $cgi->param('aaa') returns an array of aaa
my $input = $cgi->Vars();

#my $op = $input->{'op'};
#my $util = SIP::Utility->new();

my $template = SIP::Template->new(filename => 'sample.tmpl',);

my $transaction_datetime = $util->now();
my @dt = split(/ /, $transaction_datetime);
my $transaction_date =~ $dt[0];

my $session = SIP::Session->new(
  dbh               => $dbh,
  session_id        => $input->{'session_id'},
  patron_identifier => $input->{'patron_identifier'}
);
$session->validate(
  patron_identifier => 1,
  account_expiry    => 1
);

my $screen_message = $session->get('screen_message');
my $user           = $session->get('user');

=item
{
  "uid":"1356", // patron_identifier
  "amtReceived":"14.00", // fee_amount or calculated?
  "payMethod":"cash", // payment_type
  "tender":"14.00", // fee_amount
  "change":"0.00",
  "payList":[ // => null: SIP-generated from database
    {
      "cid":"22717",
      "payAmount":"14.00" // totalCharge, the last one may be partial
    }
  ]
}
=cut

my $patron_id  = $input->{'patron_identifier'};
my $fee_amount = $input->{'fee_amount'};
my $pid;

if ($session->isValid()) {
  my $respUid     = 0;
  my $uid         = $patron_id;
  my $amtReceived = $fee_amount;
  my $payMethod   = $input->{'payment_type'};
  my $tender      = $fee_amount;
  my $change;
  my $payList = getPayList($dbh, $uid, $tender);

  my $pid = trans_payment(
    $dbh,  $respUid,   $uid,    $amtReceived, $payList, '',
    undef, $payMethod, $tender, $change
  );
}

my $response = {
  debug             => $session->get('debug'),
  payment_accepted  => ($pid) ? 'true' : 'false',
  transaction_date  => $util->format_datetime($transaction_datetime, 'SIP'),
  institution_id    => $input->{'institution_id'},
  patron_identifier => $input->{'patron_identifier'},
  transaction_id    => $pid,
  screen_message    => $screen_message,
};

$template->param($response);

$template->write(cgi => $cgi);

################################################################################
sub getPayList {
  my ($dbh, $uid, $tender) = @_;

  my @val = ($uid);
  my @charges = $dbh->selectall_arrayref(<<_SQL_, { Slice => {} }, @val);
select  *
from    opl_charge
where   uid = ?
     && balance > 0
order by cid asc
_SQL_

  my $payList = [];
  foreach my $c (@charges) {
    push @{$payList}, {
      cid       => $c->{'cid'},
      payAmount => $c->{'balance'};
    };

    $tender -= $c->{'balance'};

    if ($tender <= 0) {
      last;
    }
  }

  # balance:45.00
  #
  # case 1:
  # tender:     40.00,
  # payAmount:  balance: = 45.00,
  # tender:     tender - balance = 40.00 - 45.00 = -5.00,
  # payAmount:  payAmount + tender = 45.00 + (-5.00) = 40.00
  #
  # case 2:
  # tender:     48.00,
  # payAmount:  balance = 45.00,
  # tender:     tender - balance = 48.00 - 45.00 = 3.00,
  # payAmount:  payAmount + tender = 45.00 + 3.00 = 48.00
  $payList->[$#payList]->{'payAmount'} += $tender;

  return $payList;
}
