#!/usr/bin/perl 
#
#      
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) Rainer Gümpelein, TeilRad GmbH
#

use vars qw($syshost);

BEGIN {
  $syshost = $ARGV[0] || exit 1;
}

use lib "/var/www/copri-bike/$syshost/src";
use strict;
use warnings;
use POSIX;
use Scalar::Util qw(looks_like_number);
use Lib::Config;
use Mod::DBtank;
use Mod::Payment;
use Data::Dumper;

my $cf = new Config;
my %varenv = $cf->envonline();
my $dbt = new DBtank;
my $pay = new Payment;
my $now_dt = strftime("%Y-%m-%d %H:%M:%S",localtime(time));

my $todo = $ARGV[1] || "";
my $adrc_id = $ARGV[2] || "";
my $aowner = $ARGV[3] || "196";


open(FILE,">>$varenv{logdir}/payment_ack.log");
print FILE "\n*** $now_dt todo:$todo|adrc_id:$adrc_id|aowner:$aowner  \n";

my $dbh = $dbt->dbconnect();
my $authref = {
   table           => "contentadr",
   fetch           => "one",
   template_id     => "202",
   c_id            => "$adrc_id",
};
my $ctadr = { c_id => 0 };
$ctadr = $dbt->fetch_record($dbh,$authref) if($adrc_id);
  

#preauthorization 1€ and after success async capture 0 for deletion
#define fictiv invoice to get 1 € test
my $epoche = time();
if($ctadr->{c_id}){
  my $ctt = {
     c_id => 1,
     int01 => 0,#will delete preauth_amount by capture 0€
     int04 => 0,
     int15 => 1,#preauth_amount
     txt16 => "",
     reference => "$ctadr->{c_id}_$epoche",
     payone_reset => ''
  };

  print FILE "fictiv invoice ctt:" . Dumper($ctt) . "\n";

  my $payone_txid = "";
  if($todo eq "payment_ackCC"){
    $payone_txid = $pay->preauthorizationCC_main(\%varenv,$ctadr,$ctt,$aowner);
    print FILE "preauthorizationCC_main txid:$payone_txid\n";

    $ctt->{txt16} = $payone_txid;
    if($ctt->{txt16}){
      sleep 2;
      my $payone_txid_captured = $pay->captureCC_main(\%varenv,$ctadr,$ctt,$aowner);
      print FILE "captureCC_main returns txid:$payone_txid_captured\n";
    }else{
      print FILE "Failure, No preauthorizationCC_main txid!\n";
    }
  }elsif($todo eq "payment_ackSEPA"){
    $payone_txid = $pay->preauthorizationSEPA_main(\%varenv,$ctadr,$ctt,$aowner);
    print FILE "preauthorizationSEPA_main txid:$payone_txid\n";

    $ctt->{txt16} = $payone_txid;
    if($ctt->{txt16}){
      sleep 2;
      my $payone_txid_captured = $pay->captureSEPA_main(\%varenv,$ctadr,$ctt,$aowner);
      print FILE "captureSEPA_main returns txid:$payone_txid_captured\n";
    }else{
      print FILE "Failure, No preauthorizationSEPA_main txid!\n";
    }
  }
}

close(FILE);

