#!/usr/bin/perl

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

my $second_check = shift;

my $cfg = App::POS::Config->new( file => "$Bin/../../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 "This script can run on the server machine only...\n";
}

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

my $recs = $db->select("SELECT id, fo_doc_number FROM sales_hashes WHERE doc_type = 6 ORDER BY date_inserted DESC LIMIT 2");
die "no records...\n" unless scalar @$recs == 2;

unless ($recs->[0]->{fo_doc_number} =~ /\/1$/ && $recs->[1]->{fo_doc_number} =~ /\/1$/) {

  if (defined $second_check) {
    cm_second_check($db);
  }

  die "All good...\n";
}

my $idx = 70000;

$recs = $db->select("SELECT id, fo_doc_number, business_date FROM sales_hashes WHERE doc_type = 6 ORDER BY date_inserted DESC");

foreach my $rec (@$recs) {
  my $fo = $rec->{fo_doc_number};
  last unless $fo =~ /\/1$/;

  $fo =~ s/\/\d+$/X\/$idx/;

  my( $y, $m ) = $rec->{business_date} =~ /^(\d\d\d\d)\-(\d\d)\-/;
  my $date_str = $y.$m;

  #print STDERR "### $fo - ".$rec->{business_date}." - $date_str\n";

  $db->do("UPDATE sales_hashes_".$date_str." SET fo_doc_number = '".$fo."' WHERE id = '".$rec->{id}."'");

  $idx--;
}

sub cm_second_check {
  my $db = shift;

  my $recs = $db->select(qq{
    select system_entry_date, fo_doc_number
    from sales_hashes where doc_type = 6 and fo_doc_number like '%/1'
    order by system_entry_date desc
  });

  if (scalar @$recs > 1) {
    if ($recs->[0]->{fo_doc_number} eq $recs->[1]->{fo_doc_number}) {
      my %did = ();
      my $recs2 = $db->select("select id, system_entry_date, fo_doc_number, business_date from sales_hashes where doc_type = 6 order by system_entry_date desc");

      my $idx = 70000;

      for (@$recs2) {
        if (exists $did{$_->{fo_doc_number}}) {
          my $fo = $_->{fo_doc_number};
          $fo =~ s/\/\d+$/X\/$idx/;
          $idx--;

          my( $y, $m ) = $_->{business_date} =~ /^(\d\d\d\d)\-(\d\d)\-/;
          my $date_str = $y.$m;

          print STDERR "#### $date_str - $fo\n";

          $db->do("UPDATE sales_hashes_".$date_str." SET fo_doc_number = '".$fo."' WHERE id = '".$_->{id}."'");
          #print STDERR "DUPPLICATE ##### ".$_->{fo_doc_number}." - ".$_->{business_date}." - ".$_->{id}." - $fo\n";
        }

        $did{$_->{fo_doc_number}} = 1;
      }
    }
  }
}



