#!/usr/bin/perl
use strict;
use warnings;
use FindBin qw( $Bin );
use lib "/opt/pos/lib";
use POSIX qw( strftime );
use Data::Dumper;
use App::POS::Config;
use App::POS::Machine::Server;
use App::POS::Machine::Station;
use File::Find qw( find );
use Encode qw( decode encode );
use Mojo::UserAgent;
use App::POS::Utils qw( post date_based_on_closing_hour );
use File::ChangeNotify;

my %ptkeys_vars;
my $mode = shift || "";
# possible modes
# - undef => normal mode, sends all the info to ptkeys
# - 1 => to be set in background mode 
# - 2 => to call 

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

my $name = $info->{SAFT_BusinessName} // "";
my $name1 = $info->{MACHINE_LABEL} // "";
my $pwd = $info->{INTERNET_DASHBOARD_PWD} // "";

if ($name1) {
  $name1 =~ s/,.*?$//;
  $name1 =~ s/'//g;
  $name = $name1;
}
else {
  $name =~ s/'//g;
}

my $machine = undef;
my $namespace = "";
my $DIR_AREAS = "";

if (exists $info->{STATION_NUMBER} && $info->{STATION_NUMBER} == 0) {
  $machine = App::POS::Machine::Server->new( config => $cfg );
  $namespace = `/opt/pos/common/bin/machine_id`;
  $DIR_AREAS = "/opt/pos/server/data/areas";
} else {
  $machine = App::POS::Machine::Station->new( config => $cfg );

  my $server_ip = $info->{NETWORK_SERVER_IP};
  $namespace = `echo "#HARDLOCK#" | nc $server_ip 8088`;
  $DIR_AREAS = "/shares/pos/server/data/areas";
}

$namespace =~ s/[\r\n]+$//;

my $config = $machine->config()->load();
my %AREAS_INFO;
my $area_idx = 0;

foreach my $area (@{ $config->{AREA} }) {
  my @t = split /,/, $area;
  $AREAS_INFO{$area_idx++} = \@t;
}

my $db = $machine->database();

my %products = ();
my %clerks = ();

my $tmp = $db->select("SELECT id, name FROM products");
map { $products{$_->{id}} = $_->{name} } @$tmp;

$tmp = $db->select("SELECT id, login FROM clerks");
map { $clerks{$_->{id}} = $_->{login} } @$tmp;

my $date = current_date($info->{END_BUSINESS_HOUR});
my $date_yesterday = yesterday_date($db, $date);
my $sales_today = sales($db, $date);
my $sales_by_clerk_yesterday = sales_by_clerk_yesterday($db, $date_yesterday);
my $medias_yesterday = medias_yesterday($db, $date_yesterday);
my $sales_yesterday = sales($db, $date_yesterday);
my $ncds_today = ncds($db, $date);
my $ncds_yesterday = ncds($db, $date_yesterday);
my $voids_today = voids($db, $date, 1);
my $voids_yesterday = voids($db, $date_yesterday);
my( $opentables_total, $products ) = opentables_total();
my( $sales_cur_month, $vat_cur_month ) = ! $mode ? sales_cur_month($db, $date) : undef;
my $sales_last_month = ! $mode ? sales_last_month($db, $date) : undef;
my( $sales_year, $tmd_year ) = ! $mode ? sales_year($db, $date) : undef;
my $sales_by_month_str = ! $mode ? sales_by_month($db) : undef;
my $sales_by_hour_str = ! $mode ? sales_by_hour($db) : undef;
my $sales_by_product = ! $mode ? sales_by_product($db) : undef;
my $sales_by_product_today = ! $mode ? sales_by_product_today($db, $date) : undef;

my $products_str = decode_products($products);

$sales_today ||= 0;
$sales_yesterday ||= 0;
$voids_today ||= 0;
$voids_yesterday ||= 0;
$ncds_today ||= 0;
$ncds_yesterday ||= 0;
$ncds_today *= -1 if $ncds_today;
$opentables_total ||= 0;

if ($mode eq '1') {
  # runs in background and waits for the check file 
  print "Mode 1 \n";

  my $watcher = File::ChangeNotify->instantiate_watcher(
    directories => [ '/opt/pos/server/data/tmp' ],
    filter      => qr/dashboard/,
  );

  while (1) {

    if (-e "/opt/pos/server/data/tmp/dashboard.txt") {
      unlink "/opt/pos/server/data/tmp/dashboard.txt";
      # calcula diario e manda para o ptkeys
      system('/opt/pos/server/apps/ptkeys.pl 2');
    }

    sleep 2;

=pod
    while (my @events = $watcher->wait_for_events()) {
      print STDERR Dumper \@events;
      foreach my $e (@events) {
        if ($e->type() eq 'create') {
          # calcula diario e manda para o ptkeys
          unlink "/opt/pos/server/data/tmp/dashboard.txt";
          system('/opt/pos/server/apps/ptkeys.pl 2');
        }

        if ($e->type() eq 'modify') {
          unlink "/opt/pos/server/data/tmp/dashboard.txt";
        }
      }
    }
=cut

  }
}
elsif ($mode eq '2') {
  # finds the check file, deletes it and then updates the todays values only
  print "Mode 2\n";

  %ptkeys_vars = (
    friendly_name => $name,
    app => 'OnlinePOS',
    namespace => $namespace . $pwd,
    sales_today => $sales_today,
    medias_yesterday => $medias_yesterday,
    ncds_today => $ncds_today,
    voids_today => $voids_today,
    voids_yesterday => $voids_yesterday,
    opentables_total => $opentables_total,
    products => $products_str,
    sales_by_clerk_yesterday => $sales_by_clerk_yesterday,
  );
}
else {
  # updates all the files 
  # print "no mode defined...\n";

  %ptkeys_vars = (
    friendly_name => $name,
    app => 'OnlinePOS',
    namespace => $namespace . $pwd,
    #sales_today => $sales_today + $opentables_total,
    sales_today => $sales_today,
    medias_yesterday => $medias_yesterday,
    sales_yesterday => $sales_yesterday,
    ncds_today => $ncds_today,
    tmd_year => $tmd_year,
    voids_today => $voids_today,
    voids_yesterday => $voids_yesterday,
    sales_cur_month => $sales_cur_month,
    sales_last_month => $sales_last_month,
    sales_year => $sales_year,
    opentables_total => $opentables_total,
    vat_cur_month => $vat_cur_month,
    products => $products_str,
    sales_by_month => $sales_by_month_str,
    sales_by_hour => $sales_by_hour_str,
    sales_by_product_today => $sales_by_product_today,
    sales_by_product => $sales_by_product,
    sales_by_clerk_yesterday => $sales_by_clerk_yesterday,
  );
}

=pod
# blocking
=cut

ptkeys_notify($info, \%ptkeys_vars) unless $mode eq '1';

#
# functions
#

sub decode_products {
  my $p = shift;
  my $str = "";

  foreach my $area (sort keys %$p) {
    $str .= $area . '@@';

    foreach my $table (sort { $a <=> $b } keys %{$p->{$area}}) {
      $str .= $table ."#";
=pod
          product => $pname,
          quantity => $arr[4],
          price => $arr[3],
          total => $total,
=cut
      foreach my $prod (@{$p->{$area}->{$table}}) {
        $prod->{product} ||= "";
        next unless $prod->{product};
        my $name = $prod->{product};
        $name =~ s/,/_/g;
        $str .= $name.",".$prod->{quantity}.",".$prod->{total}.'@';
      }

      $str =~ s/\@$//;
      $str .= "##";
    }

    #$str =~ s/##$//;

    $str .= '@@@@';
  }

  return $str;
}

sub current_date {
  my $end_hour = shift;
  $end_hour ||= '05:00';
  my $business_date = date_based_on_closing_hour(strftime("%Y-%m-%d %H:%M:%S", localtime), $end_hour.":00");
  return $business_date;

=pod
  return &strftime("%Y-%m-%d", localtime)
    unless -e "/opt/pos/.business_date";

  open(F, "< /opt/pos/.business_date");
  local $/ = undef;
  my $date = <F>;
  chop($date);
  close(F);

  $date //= "";

  if (! $date) {
    $date = strftime("%Y-%m-%d", localtime);
  }

  return $date;
=cut
}

sub yesterday_date {
  my( $db, $date ) = @_;

  my $recs = $db->select(qq{
    SELECT MAX(business_date) AS business_date
    FROM sales_hashes
    WHERE business_date <> ?
  }, $date);

  return scalar @$recs ? $recs->[0]->{business_date} : "";
}

sub opentables_total {
  my $vtotal = 0;
  my $products = {};

  # find voids in open tables
  find( sub {
    return unless /\.total$/;

    my $fname = $_;
    my $dir = $File::Find::dir;

    my( $check_num ) = $fname =~ /^(\d+)\.total$/;
    return unless defined $check_num;

    # ignore if check doesn't exists
    return unless -f $dir."/$check_num";

    # ignore if check is locked
    return if -f $dir."/$check_num.lock";

    my( $area ) = $dir =~ /areas\/(\d+)$/;
    return unless defined $area;

    my $area_info = $AREAS_INFO{$area};
    my $area_name = $area_info->[0];

    open(F, "< $File::Find::name");
    while (<F>) {
      my $l = $_;
      chop($l);
      $vtotal += $l;
    }
    close(F);

    my $read_details = 0;
    open(F, "< $dir/$check_num");
    while (<F>) {
      my $l = $_;
      chop($l);
      next unless $l;

      if ($read_details && $l ne 'EXTRA_DATA') {
        my @arr = split /#/, $l;
        next unless scalar @arr && scalar @arr > 4;

        my $product = $arr[1];
        my $clerk = $arr[7];
        my $total = $arr[3] * $arr[4];
        my $pname = $products{$product};
        my $cname = $clerks{$clerk};
        my $clerk_name = $clerks{$product};

        push @{ $products->{$area_name}->{$check_num} }, {
          product => "$pname ($cname)",
          quantity => $arr[3],
          price => $arr[4],
          total => $total,
        };
      }

      if ($l eq 'DETAILS') {
        $read_details = 1;
      }

      if ($l eq 'EXTRA_DATA') {
        last;
      }
    }
    close(F);

  }, ( "$DIR_AREAS" ) );

  return ( $vtotal, $products );
}

sub sales_year {
  my $db = shift;
  my $date = shift;

  my( $year, $month ) = $date =~ /^(\d+)\-(\d+)\-/;

  my $rec = $db->select(qq{
    SELECT SUM(value) AS sales, SUM(value)/COUNT(*) AS tmd
    FROM sales_headers
    WHERE EXTRACT(year FROM business_date) = ? AND (
      doc_type = 1 OR doc_type = 2 OR doc_type = 5 OR doc_type = 90 OR doc_type = 7 OR doc_type = 13
    )
  }, $year);

  return ( $rec->[0]->{sales}, $rec->[0]->{tmd} );
}

sub sales_by_month {
  my $db = shift;

  my $recs = $db->select(qq{
    SELECT
      EXTRACT(year FROM business_date) AS year,
      EXTRACT(month FROM business_date) AS month,
      SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END) AS sales
      -- SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value_net*-1 ELSE value_net END) AS sales_wo_vat,
      -- SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END - value_net) AS vat_amount,
      -- SUM(value)/COUNT(*) AS tmd
    FROM sales_hashes
    WHERE
      business_date >= DATE(now() - INTERVAL '11 months')
      AND (doc_type = 1 OR doc_type = 2 OR doc_type = 5 OR doc_type = 90 OR doc_type = 7 OR doc_type = 13)
    GROUP BY EXTRACT(year FROM business_date), EXTRACT(month FROM business_date)
    ORDER BY EXTRACT(year FROM business_date), EXTRACT(month FROM business_date)
    --ORDER BY EXTRACT(month FROM business_date)
  });

  my $str = "";

  foreach my $rec (@$recs) {
    $str .= $rec->{month}.",".$rec->{sales}.'@@@@';
  }
  #print Dumper $str;

  return $str;
}

sub sales_by_product {
  my $db = shift;

  my $recs = $db->select(qq{
    SELECT p.name AS product,
      SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END) AS sales
    FROM sales_details sd
    LEFT JOIN sales_headers sh ON (sd.header = sh.id)
    LEFT JOIN products p ON (sd.product = p.id)
    WHERE
      sd.business_date >= DATE(now() - INTERVAL '6 month') AND
      sd.operation_type = 1 AND
      (sh.doc_type = 1 OR sh.doc_type = 2 OR sh.doc_type = 5 OR sh.doc_type = 90 OR sh.doc_type = 7 OR doc_type = 13)
    GROUP BY p.name
    ORDER BY SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END) DESC LIMIT 5
  });

  my $str = "";

  foreach my $rec (@$recs) {
    $rec->{product} =~ s/,//g;
    $rec->{product} =~ s/\@//g;
    $str .= $rec->{product}.",".$rec->{sales}.'@@@@';
  }
  #print Dumper $str;

  return $str;
}

sub sales_by_product_today {
  my $db = shift;
  my $date = shift;

  my $recs = $db->select(qq{
    SELECT p.name AS product,
      SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END) AS sales
    FROM sales_details sd
    LEFT JOIN sales_headers sh ON (sd.header = sh.id)
    LEFT JOIN products p ON (sd.product = p.id)
    WHERE
      sd.business_date = ? AND
      sd.operation_type = 1 AND
      (sh.doc_type = 1 OR sh.doc_type = 2 OR sh.doc_type = 5 OR sh.doc_type = 90 OR sh.doc_type = 7 OR doc_type = 13)
    GROUP BY p.name
    ORDER BY SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END) DESC LIMIT 5
  }, $date);

  my $str = "";

  foreach my $rec (@$recs) {
    $rec->{product} =~ s/,//g;
    $rec->{product} =~ s/\@//g;
    $str .= $rec->{product}.",".$rec->{sales}.'@@@@';
  }
  #print Dumper $str;

  return $str;
}

sub sales_by_hour {
  my $db = shift;

  my $recs = $db->select(qq{
    SELECT
      EXTRACT(hour FROM date_closed) AS hour,
      SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END) AS sales
    FROM sales_headers
    WHERE
      business_date >= DATE(now() - INTERVAL '1 week')
      AND (doc_type = 1 OR doc_type = 2 OR doc_type = 5 OR doc_type = 90 OR doc_type = 7 OR doc_type = 13)
    GROUP BY EXTRACT(hour FROM date_closed)
    ORDER BY EXTRACT(hour FROM date_closed)
  });

  my $str = "";

  foreach my $rec (@$recs) {
    $str .= $rec->{hour}.",".$rec->{sales}.'@@@@';
  }
  #print Dumper $str;

  return $str;
}

sub sales_cur_month {
  my $db = shift;
  my $date = shift;

  my( $year, $month ) = $date =~ /^(\d+)\-(\d+)\-/;
  $month *= 1;

  my $rec = $db->select(qq{
    SELECT
      SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END) AS sales,
      SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value_net*-1 ELSE value_net END) AS sales_wo_vat,
      SUM(CASE WHEN doc_type = 2 OR doc_type = 13 THEN value*-1 ELSE value END - CASE WHEN doc_type = 2 OR doc_type = 13 THEN value_net*-1 ELSE value_net END) AS vat_amount,
      SUM(value)/COUNT(*) AS tmd
    FROM sales_hashes
    WHERE EXTRACT(year FROM business_date) = ? AND EXTRACT(month FROM business_date) = ? AND (
      doc_type = 1 OR doc_type = 2 OR doc_type = 13 OR doc_type = 5 OR doc_type = 90 OR doc_type = 7
    )
  }, $year, $month);

  return ( $rec->[0]->{sales}, $rec->[0]->{vat_amount} );
}

sub sales_last_month {
  my $db = shift;
  my $date = shift;

  my( $year, $month, $day ) = $date =~ /^(\d+)\-(\d+)\-(\d+)$/;
  $month *= 1;

  if ($month == 1) {
    $month = 12;
    $year--;
  }
  else {
    $month--;
  }

  my $rec = $db->select(qq{
    SELECT SUM(value) AS sales
    FROM sales_headers
    WHERE EXTRACT(year FROM business_date) = ? AND EXTRACT(month FROM business_date) = ? AND
      (
        doc_type = 1 OR doc_type = 2 OR doc_type = 13 OR doc_type = 5 OR doc_type = 90 OR doc_type = 7
      )
  }, $year, $month);

  return $rec->[0]->{sales};
}

sub sales_by_clerk_yesterday {
  my $db = shift;
  my $date = shift;

  my $recs = $db->select(qq{
    SELECT c.login,
      COUNT(sh.id) as nrecs,
      SUM(CASE WHEN sh.doc_type = 2 OR doc_type = 13 THEN sh.value*-1 ELSE sh.value END) AS totalvat,
      SUM(CASE WHEN sh.doc_type = 2 OR doc_type = 13 THEN sh.value_net*-1 ELSE sh.value_net END) AS totalwovat
    FROM sales_hashes sh
    LEFT JOIN clerks c ON (sh.clerk_close = c.id)
    WHERE sh.business_date = ? AND sh.doc_type IN (1, 5, 90, 7, 2)
    GROUP BY c.login
    ORDER BY c.login
  }, $date);

  my $str = "";

  foreach my $rec (@$recs) {
    $str .= $rec->{login}.",".$rec->{nrecs}.','.$rec->{totalvat}.','.$rec->{totalwovat}.'@@@@';
  }

  return $str;
}

sub medias_yesterday {
  my $db = shift;
  my $date = shift;

  my $recs = $db->select(qq{
    SELECT sp.payment_media, SUM(sp.value) AS total
    FROM sales_payments sp
    LEFT JOIN sales_headers sh ON (sp.header = sh.id)
    WHERE sp.business_date = ? AND (
      sh.doc_type = 1 OR sh.doc_type = 2 OR doc_type = 13 OR sh.doc_type = 5 OR sh.doc_type = 90 OR sh.doc_type = 7
    )
    GROUP BY sp.payment_media
    ORDER BY sp.payment_media
  }, $date);

  my $str = "";

  foreach my $rec (@$recs) {
    $str .= $rec->{payment_media}.",".$rec->{total}.'@@@@';
  }

  return $str;
}

sub sales {
  my $db = shift;
  my $date = shift;

  my $rec = $db->select(qq{
    SELECT SUM(value) AS sales
    FROM sales_headers
    WHERE business_date = ? AND (
      doc_type = 1 OR doc_type = 2 OR doc_type = 5 OR doc_type = 90 OR doc_type = 7 OR doc_type = 13
    )
  }, $date);

  return $rec->[0]->{sales};
}

sub ncds {
  my $db = shift;
  my $date = shift;

  my $rec = $db->select(qq{
    SELECT SUM(value) AS sales
    FROM sales_headers
    WHERE business_date = ? AND (
      doc_type = 2 OR doc_type = 13
    )
  }, $date);

  return $rec->[0]->{sales};
}

sub voids {
  my $db = shift;
  my $date = shift;
  my $read_open_tables = shift;

  my $vtotal = 0;

  if (defined ($read_open_tables)) {
    # find voids in open tables
    find( sub {
      return unless /\.deleted$/;

      open(F, "< $File::Find::name");
      while (<F>) {
        my $l = $_;
        chop($l);
        my @t = split /#/, $l;
        my $total = $t[3] * $t[4];
        $vtotal += $total;
      }
      close(F);
    }, ( "$DIR_AREAS" ) );
  }

  my $recs = $db->select(qq{
    SELECT sh.doc_type, sd.operation_type, SUM(sd.quantity*sd.price) AS voids
    FROM sales_details sd
    LEFT JOIN sales_headers sh ON (sd.header = sh.id)
    WHERE sh.business_date = ? AND sd.operation_type != 1
    GROUP BY sh.doc_type, sd.operation_type
  }, $date);

  for (@$recs) {
    $vtotal += $_->{voids};
  }

  return $vtotal;
}

# continuar aqui...
sub ptkeys_notify {
  my $cfg = shift;
  my $info = shift;

  my $app = $info->{app};
  my $namespace = $info->{namespace};

  my $date = current_date($cfg->{END_BUSINESS_HOUR});

  my( $year, $month ) = $date =~ /^(\d+)\-(\d+)\-/;
  $month *= 1;

  my $last_month = $month;

  if ($last_month == 1) {
    $last_month = 12;
  }
  else {
    $last_month--;
  }

  my %to_send = (
    app           => $info->{app},
    namespace     => $info->{namespace},
    update_last   => 1,
    friendly_name => $info->{friendly_name},
    field01_d     => 'Data',
    field01       => $date,
  );

  if (exists $info->{sales_today}) {
    $info->{sales_today} ||= 0;
    $to_send{field02_d} = 'Vendas hoje';
    $to_send{field02}   = sprintf("%.2f", $info->{sales_today});
  }

  if (exists $info->{sales_yesterday}) {
    $info->{sales_yesterday} ||= 0;
    $to_send{field03_d} = 'Vendas ontem';
    $to_send{field03}   = sprintf("%.2f", $info->{sales_yesterday});
  }

  if (exists $info->{ncds_today}) {
    $info->{ncds_today} ||= 0;
    $to_send{field04_d} = 'Estornos hoje';
    $to_send{field04}   = sprintf("%.2f", $info->{ncds_today});
  }

  if (exists $info->{voids_today}) {
    $info->{voids_today} ||= 0;
    $to_send{field05_d} = 'Anulacoes hoje';
    $to_send{field05}   = sprintf("%.2f", $info->{voids_today});
  }

  if (exists $info->{opentables_total}) {
    $info->{opentables_total} ||= 0;
    $to_send{field06_d} = 'Valor em aberto';
    $to_send{field06}   = sprintf("%.2f", $info->{opentables_total});
  }

  if (exists $info->{sales_cur_month}) {
    $info->{sales_cur_month} ||= 0;
    $to_send{field07_d} = 'Vendas mes '.$month*1;
    $to_send{field07}   = sprintf("%.2f", $info->{sales_cur_month});
  }

  if (exists $info->{vat_cur_month}) {
    $info->{vat_cur_month} ||= 0;
    $to_send{field08_d} = 'IVA mes '.$month*1;
    $to_send{field08}   = sprintf("%.2f", $info->{vat_cur_month});
  }

  if (exists $info->{sales_last_month}) {
    $info->{sales_last_month} ||= 0;
    $to_send{field09_d} = 'Vendas mes '.$last_month*1;
    $to_send{field09}   = sprintf("%.2f", $info->{sales_last_month});
  }

  if (exists $info->{sales_year}) {
    $info->{sales_year} ||= 0;
    $to_send{field10_d} = 'Vendas '.$year;
    $to_send{field10}   = sprintf("%.2f", $info->{sales_year});
  }

  if (exists $info->{tmd_year}) {
    $info->{tmd_year} ||= 0;
    $to_send{field11_d} = 'TMD '.$year;
    $to_send{field11}   = sprintf("%.2f", $info->{tmd_year});
  }

  if (exists $info->{sales_by_month}) {
    $info->{sales_by_month} ||= "";
    $to_send{field12_d} = 'Vendas mensais';
    $to_send{field12}   = $info->{sales_by_month};
  }

  if (exists $info->{sales_by_hour}) {
    $info->{sales_by_hour} ||= "";
    $to_send{field13_d} = 'Vendas p/ hora';
    $to_send{field13}   = $info->{sales_by_hour};
  }

  if (exists $info->{sales_by_product}) {
    $info->{sales_by_product} ||= "";
    $to_send{field14_d} = 'Vendas p/ produto';
    $to_send{field14}   = $info->{sales_by_product};
  }

  if (exists $info->{sales_by_product_today}) {
    $info->{sales_by_product_today} ||= "";
    $to_send{field15_d} = 'Vendas p/ produto - hoje';
    $to_send{field15}   = $info->{sales_by_product_today};
  }

  if (exists $info->{medias_yesterday}) {
    $info->{medias_yesterday} ||= "";
    $to_send{field16_d} = 'Tipos pagamento ontem';
    $to_send{field16}   = $info->{medias_yesterday};
  }

  if (exists $info->{sales_by_clerk_yesterday}) {
    $info->{sales_by_clerk_yesterday} ||= "";
    $to_send{field17_d} = 'Funcionarios ontem';
    $to_send{field17}   = $info->{sales_by_clerk_yesterday};
  }

  if (exists $info->{voids_yesterday}) {
    $info->{voids_yesterday} ||= 0;
    $to_send{field18_d} = 'Anulacoes ontem';
    $to_send{field18}   = sprintf("%.2f", $info->{voids_yesterday});
  }

  if (exists $info->{ncds_yesterday}) {
    $info->{ncds_yesterday} ||= 0;
    $to_send{field19_d} = 'Estornos ontem';
    $to_send{field19}   = sprintf("%.2f", $info->{ncds_yesterday});
  }

  if (exists $info->{products}) {
    $info->{products} ||= "";
    $to_send{field20_d} = 'Products';
    $to_send{field20}   = $info->{products};
  }

  $to_send{ws_namespace} = $namespace;

  my $ua = Mojo::UserAgent->new;
  #$ua->websocket('wss://go2web4free.com:10074/echo' => sub {
  $ua->websocket('ws://go2web4free.com:10073/echo' => sub {
    my ($ua, $tx) = @_;
    $tx->on(json => sub {
      my ($tx, $hash) = @_;
      print "message sent\n";
      $tx->finish;
    });

    eval {
      $tx->send({json => \%to_send});
    };

    if ($@) {
      delete $to_send{ws_namespace};
      delete $to_send{update_last};
      my $ret = post('http://www.ptcert.com/dashboard_update', \%to_send, 10);
    }
  });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
}

