#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use lib "$Bin/../../lib";
use Data::Dumper;
use App::POS::Config;
use App::POS::Machine::Server;
use UUID::Tiny;
use File::Copy qw( copy );

my $clean_customers = shift;

print "This will remove ALL the sales, are you sure? [y/n]\n";
my $ans = <STDIN>;
chop($ans);
exit unless uc($ans) eq 'Y';

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";
}

system("rm -f /opt/pos/server/data/database/pos_*.db 2> /dev/null");
system("rm -f /opt/pos/server/data/database/daily_specials_avbl_qtys.ui 2> /dev/null");
system("rm -f /opt/pos/server/data/tmp/transport_begin.txt 2> /dev/null");
system("rm -f /opt/pos/server/data/tmp/money_transit.txt 2> /dev/null");
system("rm -f /opt/pos/server/data/export/* 2> /dev/null");

system("rm -rf /opt/pos/server/data/opened_cashiers/* 2> /dev/null");
system("rm -rf /opt/pos/server/data/historial_fills/* 2> /dev/null");

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

$db->do("UPDATE customers SET total_credit = 0, points = 0");

$db->do("TRUNCATE split_docs_link");
$db->do("TRUNCATE counters");
$db->do("TRUNCATE card_sets");
$db->do("TRUNCATE time_clock CASCADE");
$db->do("TRUNCATE transfer_products CASCADE");
$db->do("TRUNCATE transfers CASCADE");
$db->do("TRUNCATE sales_hashes_products CASCADE");
$db->do("TRUNCATE sales_hashes CASCADE");
$db->do("TRUNCATE sales_details_aux CASCADE");
$db->do("TRUNCATE sales_headers_aux CASCADE");
$db->do("TRUNCATE sales_payments_aux CASCADE");
$db->do("TRUNCATE sales_payments CASCADE");
$db->do("TRUNCATE sales_details CASCADE");
$db->do("TRUNCATE sales_headers CASCADE");
$db->do("TRUNCATE cashdrawer_opens CASCADE");
$db->do("TRUNCATE vouchers CASCADE");
$db->do("TRUNCATE document_operations CASCADE");
$db->do("TRUNCATE document_history CASCADE");
$db->do("TRUNCATE schedules CASCADE");
$db->do("TRUNCATE cashier_operations CASCADE");
$db->do("TRUNCATE cashiers CASCADE");

if (defined $clean_customers) {
  $db->do("TRUNCATE customers CASCADE");
}

my $recs = $db->select(qq{
  SELECT table_name
  FROM information_schema.tables
  WHERE table_type = 'BASE TABLE' AND table_name LIKE '%_%' AND table_schema = 'public'
});

foreach my $table (@$recs) {
  if ($table =~ /_2/ || $table =~ /_copy/) {
    $db->do("DROP TABLE $table CASCADE");
  }
}

system("/opt/pos/server/apps/reinit_tables.pl 2> /dev/null");
system("/etc/init.d/memcached restart 2> /dev/null");
system("/opt/pos/common/bin/restart_hardware_handler.sh");

