#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use lib "/opt/pos/lib";
use Data::Dumper;
use File::Path qw( make_path );
use IO::Socket;
use App::POS::Config;
use App::POS::Machine::Server;

use App::POS::Utils qw(
  translate my_round my_conv date_based_on_closing_hour md5_from_file
  send_mail execution_dates
);

my $cfg = App::POS::Config->new( file => "/opt/pos/etc/config.ini" );
my $info = $cfg->load_fixed();
my $LANG = $info->{LANG} || "";
my $SAFT_CompanyId = $info->{SAFT_CompanyId} || "";
my $SAFT_TaxRegistratioNumber = $info->{SAFT_TaxRegistratioNumber} || "";
my $SAFT_CompanyName = $info->{SAFT_CompanyName} || "";
my $SAFT_BusinessName = $info->{SAFT_BusinessName} || "";
my $SAFT_AddressDetail = $info->{SAFT_AddressDetail} || "";
my $SAFT_City = $info->{SAFT_City} || "";
my $SAFT_PostalCode = $info->{SAFT_PostalCode} || "";
my $INTERNET_SEND_DAILY_Z = $info->{INTERNET_SEND_DAILY_Z} || "";
my $INTERNET_SEND_MONTHLY_Z = $info->{INTERNET_SEND_MONTHLY_Z} || "";
my $INTERNET_REPORT_FORMAT = $info->{INTERNET_REPORT_FORMAT} || "pdf";
my $DOC_TYPE_SERIE = $info->{DOC_TYPE_SERIE} || "";

$info->{EXTERNAL_DOC} ||= [];
my %docs = ();

for (@{$info->{EXTERNAL_DOC}}) {
  my @a = split /,/, $_;

  if ($a[0] < 9990) {
    $docs{$a[0]} = $a[1];
  }
}

my $sep = ";";

if (exists $info->{STATION_NUMBER} && $info->{STATION_NUMBER} ne '0') {
  die "Must be executed in server machine...\n";
}

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

# check network connection
my $has_network = `/opt/pos/common/bin/has_network`;
die "No network connection...\n" unless $has_network =~ /YES/i;

my $dates = execution_dates($db, 'csv_export');
#print STDERR Dumper($dates);

foreach my $date (@$dates) {
  my $recs = $db->select(qq{
    SELECT sh.fo_doc_number, sh.date_closed, sh.hour, sha1.key_value AS external_doc_code, sha2.key_value AS external_doc_name,
      sd.product, sd.product_name, sd.vat, sd.quantity, sd.discount, sd.price, p.sell_price1, p.sell_vat1
    FROM sales_details sd
    LEFT JOIN sales_headers sh ON (sh.id = sd.header)
    LEFT JOIN sales_headers_aux sha1 ON (sh.id = sha1.header AND sha1.key_name = 'external_doc_code')
    LEFT JOIN sales_headers_aux sha2 ON (sh.id = sha2.header AND sha2.key_name = 'external_doc_name')
    LEFT JOIN products p ON (sd.product = p.id)
    WHERE sd.operation_type = 1 AND sha1.key_value IS NOT NULL AND sh.business_date = ? AND sd.business_date = ?
    ORDER BY sh.id, sd.gb_identifier
  }, $date, $date);

  if (! scalar @$recs) {
    print STDERR "No recs in date $date, skipping...\n";
    # mark this date as processed
    execution_dates($db, 'csv_export', $date);
    next;
  }

  next unless scalar @$recs;

  my $biz = $SAFT_BusinessName;
  $biz =~ s/\s//g;

  my $did = 0;
  open(F, "> /tmp/docs_external_".$biz."_$date.csv");

  foreach my $rec (@$recs) {
    $rec->{product_name} =~ s/"//g;
    $rec->{price} ||= 0;
    $rec->{discount} ||= 0;
    my $discount_w_vat = $rec->{discount} * (1 + $rec->{vat}/100);
    my $price = $rec->{price}-$discount_w_vat;
    my $line_total = $rec->{quantity}*$price;
    my $line_total_wo_vat = ($rec->{quantity}*$price)/(1+$rec->{vat}/100);
    my $fam_name = &my_conv($rec->{family_name});
    my $prod_name = &my_conv($rec->{product_name});
    my $sub_fam_name = &my_conv($rec->{subfamily_name});
    my $line_dept = $rec->{department};
    my $serie = $rec->{serie};

    $rec->{quantity} = sprintf("%.3f", $rec->{quantity});
    $rec->{unit_price} = sprintf("%.2f", $price);
    $rec->{line_total} = sprintf("%.2f", $line_total);
    $rec->{discount} = sprintf("%.2f", $discount_w_vat);
    $discount_w_vat = sprintf("%.2f", $discount_w_vat);
    $line_total = sprintf("%.2f", $line_total);

    $did = 1;

    my $doc_name = "";

    foreach my $k (%docs) {
      if ($rec->{fo_doc_number} =~ /$k/) {
        $doc_name = $docs{$k};
        last;
      }
    }

    my $p_price = $rec->{sell_price1};
    my $p_vat = $rec->{sell_vat1};
    $line_total = sprintf("%.2f", $p_price * $rec->{quantity});

    #print F $rec->{fo_doc_number}.$sep.$date.$sep.$rec->{hour}.$sep.$rec->{product}.$sep.$rec->{product_name}.$sep.
    #  $rec->{vat}.$sep.$rec->{quantity}.$sep.$rec->{price}.$sep.$discount_w_vat.$sep.$line_total.";$doc_name\n";

    print F $rec->{fo_doc_number}.$sep.$date.$sep.$rec->{hour}.$sep.$rec->{product}.$sep.$rec->{product_name}.$sep.
      $p_vat.$sep.$rec->{quantity}.$sep.$p_price.$sep.$line_total.$sep."$doc_name\n";

  }

  close(F);

  print STDERR "### did? $did\n";

  if ($did) {
    #my $to = 'mmanso@gmail.com';
    my $to = $INTERNET_SEND_DAILY_Z;

    eval {
      my $stat = send_mail(
        to         => $to,
        subject    => "[$LANG] CSV $SAFT_TaxRegistratioNumber / $SAFT_BusinessName / $date",
        content    => "$LANG<br>=========<p>$SAFT_BusinessName<br>",
        attachment => [ "/tmp/docs_external_".$biz."_$date.csv" ],
      );
      
      if ($stat) {
        # mark this date as processed
        execution_dates($db, 'csv_export', $date);
      }
    };

    print $@;
  }

  unlink "/tmp/docs_external_$date.csv";
}


