package ticketserver::Tools;

use strict;
use warnings;
use Math::Int64 qw( :native_if_available int64 );
use Digest::MD5 qw(md5);
use ADBGUI::Tools qw(ensureLength);

BEGIN {
   use Exporter;
   our @ISA = qw/Exporter/;
   #our @EXPORT = qw//;
   our @EXPORT_OK = qw/iTAN getiTANforVerbundPlain printHeader timetodatev/;
}

sub timetodatev {
   my @t = localtime(shift);
   return "".($t[5]+1900)."-".ensureLength($t[4]+1, 2, "0")."-".ensureLength($t[3], 2, "0")."T".ensureLength($t[2], 2, "0").":".ensureLength($t[1], 2, "0").":".ensureLength($t[0], 2, "0");
}

sub printHeader {
   my $heap = shift;
   my $out = shift;
   my $config = shift;
   my $end = shift;
   return
      if $heap->{headerout}++;
   print $out "      <Belegart>Rechnung</Belegart>"."\n";
   print $out "      <Kundennummer>".($config->{rechnungid}||$config->{kundenid}||die)."</Kundennummer>"."\n";
   print $out "      <Lieferdatum>".timetodatev($end).
                     #"2020-04-11T00:00:00".
                     "</Lieferdatum>\n";
   print $out "      <Belegdatum>".timetodatev($end).
                     #"2020-04-11T00:00:00".
                    "</Belegdatum>"."\n";
   print $out "      <Belegnummer>EXT-".++$heap->{i}."</Belegnummer>"."\n";
   print $out "      <Zahlungsbedingung>12</Zahlungsbedingung>\n";
   print $out "      <Preislistennummer>2</Preislistennummer>\n";
   print $out "\n";
   print $out "      <Positionen>"."\n";
}

sub iTAN {
   my $salt = shift;
   my $length = shift || 8;
   my $md5 = md5($salt);
   #print "md5:".length($md5)."\n";
   my $number = unpack("A8", $md5);
   #print $salt."->".length($number)."\n";
   while (length($number) < 8) {
      $number= chr(0).$number
   }
   my $text = Math::Int64::native_to_int64($number);
   return substr($text, -$length);
}

sub getiTANforVerbundPlain {
   my $tannum     = shift || die;
   my $forename   = shift || die;
   my $name       = shift || die;
   my $tanid      = shift || die;
   my $salt       = $tanid.$tannum.uc(substr($forename, 0, 1)).uc(substr($name, 0, 1));
   #print "\n".$salt."\n";
   return iTAN($salt);
}

1;