#!/usr/bin/perl

use strict;
use warnings;
use File::Slurp qw( write_file );
use FindBin qw( $Bin );
use lib "$Bin/../../lib";
use Data::Dumper;
use App::POS::Config;
use App::POS::Machine::Server;

#
# This script creates the date_inserted column in the sales_hashes table
# and feed the existant records with the correct data
#

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

my $machine = undef;

if (exists $info->{STATION_NUMBER} && $info->{STATION_NUMBER} == 0) {
  $machine = App::POS::Machine::Server->new( config => $cfg );  
} else {
  die "Needs to be executed in the server machine...\n";
}

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

my %series;

foreach my $atcud (@{$info->{SAFT_SERIES_CODES}}) {
  my @a = split /,/, $atcud;
  next unless scalar @a == 2;
  $series{$a[0]} = $a[1];
}

eval {
  # fix cms without atcuds
  my $cms = $db->select(qq{
    SELECT id, fo_doc_number
    FROM sales_hashes
    WHERE doc_type = 6 AND business_date >= ? AND atcud IS NULL
  }, '2023-01-01');

  for (@$cms) {
    my( $serie, $num ) = $_->{fo_doc_number} =~ /^(.*?)\/(\d+)$/;
    $num ||= "";
    $serie ||= "";
    next unless $num && $serie && exists $series{$serie};
    my $atcud = $series{$serie} . "-" . $num;
    $db->do("UPDATE sales_hashes SET atcud = ? WHERE id = ?", $atcud, $_->{id});
  }
};

if ($@) {
  print STDERR "ERROR - $@\n";
}

# add date_inserted field, if it doens't exists
eval {
  $db->do(qq{
    DO
    \$\$
    BEGIN
    IF not EXISTS (SELECT column_name 
                   FROM information_schema.columns 
                   WHERE table_schema='public' and table_name='sales_hashes' and column_name='date_inserted') THEN
      ALTER TABLE sales_hashes ADD COLUMN date_inserted TIMESTAMP DEFAULT '2001-01-01 00:00:00';
      UPDATE sales_hashes SET date_inserted = REPLACE(system_entry_date, 'T', ' ')::TIMESTAMP;
    ELSE
    RAISE EXCEPTION 'Already exists';
    END IF;
    END
    \$\$
  });
};

# this means the field already exists, we'll stop here
if ($@) {
  exit;
}

# change default value for field
$db->do("ALTER TABLE sales_hashes ALTER date_inserted SET DEFAULT CURRENT_TIMESTAMP");

my $recs = $db->select("SELECT MAX(business_date) AS biz_date FROM sales_hashes");

if (scalar @$recs) {
  my $biz_date = $recs->[0]->{biz_date} || "";

  if ($biz_date) {
    my @a = split /\-/, $biz_date;
    my $table = "sales_hashes_".$a[0].$a[1];

    $recs = $db->select("SELECT system_entry_date, id FROM $table WHERE business_date = ?", $biz_date);

    for (@$recs) {
      # 2016-12-04T18:11:31
      my( $y, $m, $d, $H, $M, $S ) = $_->{system_entry_date} =~ /^(\d\d\d\d)\-(\d\d)\-(\d\d)T(\d\d):(\d\d):(\d\d)$/;

      $db->do(
        "UPDATE sales_hashes SET date_inserted = ? WHERE id = ?",
        "$y-$m-$d $H:$M:$S", $_->{id},
      );
    }
  }
}

write_file("/opt/pos/etc/.fix_sh_inserted_dates.txt", 1);

