#!/usr/bin/perl -w
use warnings;
use strict;
use lib qw(ticketserver/tools/ . /mnt/datev/);
use kunden;
use POE;
use CM::POETools qw(requestData);
use ADBGUI::BasicVariables;
use ADBGUI::Tools qw(ensureLength);
use HTTP::Date;
use JSON;
use Config::Simple;
use FileHandle;
use Data::Dumper qw(Dumper);
use Date::Calc qw(Monday_of_Week Add_Delta_Days Mktime Decode_Date_EU2 Decode_Date_US2 Add_Delta_YM);
use File::Path qw(make_path);
use ADBGUI::Tools qw(ReadConfig);
use Text::CSV;
use Time::Local qw(timelocal);
use ticketserver::DBManager;
use ticketserver::Tools qw(printHeader timetodatev);

my $found = 0;
my $i = 0;
my $j = 1;

$SIG{__DIE__} = \&confess;

my $config = ReadConfig('dbm.cfg');
#use Data::Dumper qw(Dumper);
#print Dumper($config);
die "No ID!\n"
   unless $config->{id};
die "No KW/Month given!\n"
   unless my $KWMONTH   = $ARGV[0];
die "No Year given!\n"
   unless my $YEAR = $ARGV[1];
die "No kundenid"
   unless $config->{kundenid};

# Wochen
#my ($year,$month,$day) = Add_Delta_Days(Monday_of_Week($KWMONTH,$YEAR), 4);
#my $start = Mktime($year,$month,$day, 0, 0, 0);
#($year,$month,$day) = Add_Delta_Days($year,$month,$day, 7);

# Monate
my ($year,$month,$day) = ($YEAR, $KWMONTH, 1);
my $start = Mktime($YEAR,$KWMONTH, 1, 0, 0, 0);
($year,$month,$day) = Add_Delta_YM($YEAR, $KWMONTH, 1, 0, 1);
my $end = Mktime($year,$month,$day, 0, 0, 0)-1;

print "FROM ".localtime($start)." -> ".localtime($end)." for id ".$config->{id}." via 127.0.0.1:".$config->{listenport}."\n";

make_path("/mnt/datev/".$YEAR.".".$KWMONTH."/");
my $filename = "/mnt/datev/".$YEAR.".".$KWMONTH."/".$config->{id}.".datev";
open(my $out, ">", $filename) || die($!);
print $filename."\n";

POE::Session->create(
   inline_states => {
      _start  => sub {
         my ($kernel, $heap) = @_[KERNEL, HEAP];
         requestData($_[SESSION]->ID(), "adbgui://localhost:".$config->{listenport}."/GET tickets", "getticketsdone", undef, {auth => [$config->{'user'}, $config->{'pass'}], adbguitimeout => 600});
         print STDERR "Tickets...\n";
      },
      _stop => sub {
      },
      getticketsdone  => sub {
         my ($kernel, $session, $heap, $input) = @_[ KERNEL, SESSION, HEAP, ARG0];
         my $json = undef;
         if ($input && ($json = from_json($input)) && ($json->{result} eq "ok")) {
            $heap->{tickets} = $json->{data};
            my $lastticket = undef;
            foreach my $curline (@{$heap->{tickets}}) {
               next
                  if $lastticket &&
                    ($lastticket eq $curline->{"tickets.id"});
               $lastticket = $curline->{"tickets.id"};
               my $cur = undef;
               next
                  unless $curline->{"tickets.start"} &&
                         $curline->{"tickets.brums"}   && (length(
                         $curline->{"tickets.brums"}) > 5);
               die "No start date!"
                  if (!$curline->{"tickets.start"} || (
                       $curline->{"tickets.start"} eq "0000-00-00 00:00:00"));
               die "Unparsable date ".$curline->{"tickets.start"}
                  unless $cur = str2time($curline->{"tickets.start"});
               next
                  unless ($cur > $start) &&
                         ($cur < $end);
               push(@{$heap->{ticketstore}}, [$curline->{"tickets.id"}, $curline->{"tickets.brums"}]);
            }
            if ($heap->{ticketstore}) {
               print STDERR "GETUSERDATAFORTICKETS...\n";
               return requestData($_[SESSION]->ID(), "adbgui://localhost:".$config->{listenport}."/GETUSERDATAFORTICKETS ".to_json($heap->{ticketstore}), "getuserdataforticket", undef, {auth => [$config->{'user'}, $config->{'pass'}], adbguitimeout => 600});
            }
         }
         $kernel->yield("kontobuchungen");
      },
      getuserdataforticket => sub {
         my ($kernel, $session, $heap, $input) = @_[ KERNEL, SESSION, HEAP, ARG0];
         my $json = undef;
         # Erstmal kein PayPal
         return $kernel->yield("kontobuchungen");
         if ($input && ($json = from_json($input)) && ($json->{result} eq "ok")) {
            foreach my $ticketobj (@{$heap->{ticketstore}}) {
               printHeader($heap, $out, $config, $end);
               my $ticketid = $ticketobj->[0];
               my $ticketbrums = $ticketobj->[1];
               my $curenduser = $json->{data}->{$ticketid};
               my $kundenstr = $curenduser->{"enduser.forename"}." ".$curenduser->{"enduser.name"}." / ".$ticketid." / ".$ticketbrums;
               print $kundenstr."\n";
               $found++;
               my $anz = $curenduser->{anz} || die();
               #my $curmac = $heap->{macs}->{$ticketid}->[0];
               #my $curenduser = $heap->{enduser}->{uc($heap->{macs}->{$ticketid}->[0]->{"mac.address"})}->[0];
               print " -> ".$anz."\n";
               #die Dumper($heap->{macs}->{$ticketid}->[0]);
               print $out "         <Textposition>"."\n";
               print $out "            <Positionstext>Kunde: ".$kundenstr."</Positionstext>"."\n";
               print $out "         </Textposition>"."\n";
               print $out "         <Artikelposition>"."\n";
               print $out "            <Artikelnummer>IZV-TKTS-10</Artikelnummer>"."\n";
               print $out "            <Referenznummer>".$j++."</Referenznummer>"."\n";
               print $out "            <Menge>".($anz == 1 ? 1 :
                                                 $anz == 2 ? 2 :
                                                 $anz == 3 ? 2.5 : 3.5)."</Menge>"."\n";
               print $out "         </Artikelposition>"."\n";
            }
         }
         $kernel->yield("kontobuchungen");
      },
      kontobuchungen => sub {
         my ($kernel, $session, $heap) = @_[ KERNEL, SESSION, HEAP];
         open(my $fh, "<", "/mnt/datev/kontobewegungen_export.csv") || die($!);
         <$fh>;
         my $csv = Text::CSV->new ({ sep_char => ";", binary => 1 });
         my $row = $csv->getline ($fh);
         print $out "   <Beleg>"."\n";
         while ($row = $csv->getline ($fh)) {
            printHeader($heap, $out, $config, $end);
            #my $i = 0;
            #foreach my $line (@$row) {
            #   print $i++."\t".$line."\n";
            #}
            my $IBAN = $row->[7];
            my $name = $row->[6];
            my $datum = $row->[4];
            my $verwendungszweck = $row->[10];
            my $betrag = $row->[11];
            my $brumsid = $kunden->{$IBAN} ? ($kunden->{$IBAN}->{brumsid} || undef) : undef;
            #die "IBAN=".$IBAN." name=".$name." datum=".$datum." betrag=".$betrag." verwendungszweck=".$verwendungszweck." betrag=".$betrag."\n";
            if (!$brumsid && ($verwendungszweck =~ /(\d{3,7})/)) {
               $brumsid = $1;
            }
            my $ticketid = $kunden->{$IBAN} ? ($kunden->{$IBAN}->{ticketid} || undef) : undef;
            if ($verwendungszweck =~ /([279cdfhkmnprstuvwxCDFHKMNPRSTUVWX]{10})/) {
               if (my $code = ticketserver::DBManager::getVerifiedNumConfig($config, uc($1))) {
                  $brumsid = $code;
               }
            }
            $betrag =~ s,\.,,g;
            next if
               $betrag =~ s,\,,\.,g;
            next if $betrag < 10;
            next
               if $betrag % 5;
            my $day = [Decode_Date_EU2($datum)];
            my $now = timelocal(0, 0 ,0, $day->[2], $day->[1]-1, $day->[0]-1900);
            die
               unless $now;
            if (($start > $now) ||
                ($end < $now)) {
               #print localtime($start)." < ".localtime($now)." < ".localtime($end)."\n";
               next;
            }
            unless ($kunden->{$IBAN}) {
               print $IBAN."\t".$betrag."\t".$name."\t".($verwendungszweck||"-")."\n";
               next;
            }
            die "Kunde ".$IBAN." hat keine Kundenid"
               unless $kunden->{$IBAN}->{kundenid};
            next
               unless $kunden->{$IBAN}->{kundenid} == $config->{kundenid};
            print "Keine Brumsid und keine TicketID in ".$verwendungszweck." fuer ".$IBAN."... Buche nur auf Standort.\n"
               unless $brumsid || $ticketid;
            my $cur = undef;
            print $out "         <Textposition>"."\n";
            print $out "            <Positionstext>Kunde: ".$name." / ".($brumsid ? "-" : $kunden->{$IBAN}->{ticketid}||"-").($brumsid ? " / ".$brumsid : "")."</Positionstext>"."\n";
            print $out "         </Textposition>"."\n";
            print $out "         <Artikelposition>"."\n";
            print $out "            <Artikelnummer>IZV-TKTS-10</Artikelnummer>"."\n";
            print $out "            <Referenznummer>".$j++."</Referenznummer>"."\n";
            print $out "            <Menge>".($betrag/10)."</Menge>"."\n";
            print $out "         </Artikelposition>"."\n";
            print $out "      </Positionen>"."\n";
            $found++;
         }
         print $out "   </Beleg>"."\n";
      },
   }
);

$poe_kernel->run();

close $out;
unlink $filename
   unless $found;
print "Wrote ".$found." entries\n";
