#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use File::Find qw( find );
use Spreadsheet::ParseExcel::Simple;
use File::Slurp qw( read_file write_file );
use lib "/opt/pos/lib";
use App::POS::Config;
use App::POS::Machine::Server;

my $cfg_o = App::POS::Config->new( file => "/opt/pos/etc/config.ini" );
my $cfg = $cfg_o->load_fixed();
$cfg->{SAFT_TaxRegistratioNumber} ||= "";
$cfg->{SAFT_TaxRegistratioNumber} ||= "";

my $machine = App::POS::Machine::Server->new( config => $cfg_o );
my $db = $machine->database();

my $serie_config = $cfg->{DOC_TYPE_SERIE};

if ($machine->software_version >= 202101) {
  $serie_config =~ s/\@YEAR\@//g;
} else {
  my $year = &strftime("%Y", localtime);
  $serie_config =~ s/\@YEAR\@/$year/g;
}

my $dir = '/media';
my $customer_nif = $cfg->{SAFT_TaxRegistratioNumber};

my %info = ();

find(sub {
  return if /sf_MiguelManso/;
  return unless /xls/i;
  return unless -f $File::Find::name;
  return if scalar keys %info;

  my $xls = Spreadsheet::ParseExcel::Simple->read($File::Find::name);

=pod
$VAR1 = [
          'C�digo Valida��o S�rie',
          'S�rie',
          'Tipo de S�rie',
          'Classe do Documento',
          'Tipo de Documento',
          'In�cio da Sequ�ncia Previsto',
          'Fim da Sequ�ncia Previsto',
          'Quantidade',
          'N�mero �ltimo Documento Emitido',
          'In�cio Previsto de Utiliza��o',
          'Meio de Processamento',
          'N�mero do Certificado',
          'Data de Registo',
          'Comunicado Por',
          'NIF Quem Comunicou',
          'Situa��o',
          'Data Situa��o',
          'Motivo'
        ];
=cut

  foreach my $sheet ($xls->sheets) {
    while ($sheet->has_data) {
      my @data = $sheet->next_row;
      next unless scalar @data > 15;
      next if $data[3] eq 'Classe do Documento'; # ignore headers
      next unless $data[15] eq 'Ativa';
      #next unless $data[3] eq 'Faturas e documentos retificativos';

      my $code = $data[0];
      next unless $code;

      my $serie = $data[1];
      my $nif = $data[14];

      if ($nif ne $customer_nif) {
        print STDERR "Invalid NIF - $nif (expecting $customer_nif)\n";
      }

      next unless $nif eq $customer_nif;

      my $doc = "";

      if ($data[4] =~ /Fatura simplificada/i) {
        $doc = 'FS';
      }
      elsif ($data[4] =~ /^Nota de cr/i) {
        $doc = 'NC';
      }
      elsif ($data[4] =~ /^Fatura\-recibo/i) {
        $doc = 'FR';
      }
      elsif ($data[4] =~ /^Outros recibos emitidos/i) {
        $doc = 'RG';
      }
      elsif ($data[4] =~ /^Consultas de mesa/i) {
        $doc = 'CM';
      }
      elsif ($data[4] =~ /^Guia de transporte/i) {
        $doc = 'GT';
      }
      elsif ($data[4] =~ /^Fatura/i) {
        $doc = 'FT';
      }

      my $serie_txt = $doc . " " . $serie;

      if ($serie_txt !~ /$serie_config/) {
        print STDERR "Invalid serie - $serie_txt (expecting $serie_config)\n";
        next;
      }

      $info{$serie_txt} = $code;
    }
  }
}, ( $dir ));

die "No data..." unless scalar keys %info;

my @lines = read_file("/opt/pos/etc/config.ini");
my @new_lines = ();
my $did_changes = 0;

foreach my $l (@lines) {
  if ($l =~ /^SAFT_SERIES_CODES=/) {
    my @a = split /=/, $l;
    #print STDERR "### #$l#\n";
    next unless scalar @a == 2;

    if (! $a[1]) {
      push @new_lines, $l;
    } else {
      my @b = split /,/, $a[1];
      if (scalar @b == 2) {
        if (exists $info{$b[0]}) {
          $b[1] = $info{$b[0]};
          push @new_lines, "SAFT_SERIES_CODES=$b[0],$b[1]\n";
          $did_changes = 1;
        } else {
          push @new_lines, $l;
        }
      } else {
        push @new_lines, $l;
      }
    }
  } else {
    push @new_lines, $l;
  }
}

# we didn't change anything, we need to add new lines
if (! $did_changes) {
  foreach my $doc (sort keys %info) {
    my $atcud = $info{$doc};
    unshift @new_lines, "SAFT_SERIES_CODES=$doc,$atcud\n";
    $did_changes = 1;
  }
}

if ($did_changes) {
  my $new_config = join("", @new_lines);
  write_file("/opt/pos/etc/config.ini", $new_config);

  # restart pos
  system('ps xa | grep "/opt/pos/common/bin/pos" | grep -v grep | awk \'{ print $1 }\' | sudo xargs kill -9 2> /dev/null');
}

