#!/usr/bin/perl

use strict;
use warnings;
use lib "/opt/pos/lib";
use Data::Dumper;
use App::POS::Machine::Station;
use App::POS::Machine::Server;
use App::POS::Utils qw( fix_encoding );

my $encoding_to_apply = shift;
$encoding_to_apply //= "";

my $machine = undef;

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

if (exists $info->{STATION_NUMBER} && $info->{STATION_NUMBER} > 0) {
  $machine = App::POS::Machine::Station->new( config => $cfg );
}
else {
  $machine = App::POS::Machine::Server->new( config => $cfg );
}

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

#
# Groups
#

print STDERR "Groups...\n";

my $r = $db->select(qq{
  SELECT id, name FROM groups
});

for (@$r) {
  $db->do(
    "UPDATE groups SET name = ? WHERE id = ?",
    fix_encoding($_->{name}, $encoding_to_apply), $_->{id}
  );
}

#
# Products
#

print STDERR "Products...\n";

$r = $db->select(qq{
  SELECT id, name, button_text FROM products
});

for (@$r) {
  $db->do(
    "UPDATE products SET name = ?, button_text = ? WHERE id = ?",
    fix_encoding($_->{name}, $encoding_to_apply), fix_encoding($_->{button_text}, $encoding_to_apply), $_->{id}
  );
}

#
# Clerks
#

print STDERR "Clerks...\n";

$r = $db->select(qq{
  SELECT id, login FROM clerks
});

for (@$r) {
  $db->do(
    "UPDATE clerks SET login = ? WHERE id = ?",
    fix_encoding($_->{login}, $encoding_to_apply), $_->{id}
  );
}

#
# Customers
#

print STDERR "Customers...\n";

$r = $db->select(qq{
  SELECT id, name, card_number, nif, address, postal_code, city, contact,
    email
  FROM customers
});

for (@$r) {
  $db->do(qq{
    UPDATE customers SET
      name = ?, card_number = ?, nif = ?, address = ?, postal_code = ?,
      city = ?, contact = ?, email = ?
    WHERE id = ?
  }, fix_encoding($_->{name}, $encoding_to_apply), fix_encoding($_->{card_number}, $encoding_to_apply),
    fix_encoding($_->{nif}, $encoding_to_apply), fix_encoding($_->{address}, $encoding_to_apply),
    fix_encoding($_->{postal_code}, $encoding_to_apply), fix_encoding($_->{city}, $encoding_to_apply),
    fix_encoding($_->{contact}, $encoding_to_apply), fix_encoding($_->{email}, $encoding_to_apply),
    $_->{id});
}

