#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Socket;

# use port 9100 as default
my $port = shift || 8089;
my $proto = getprotobyname('tcp');
my $server = "0.0.0.0";  # Host IP running the server

# create a socket, make it reusable
socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
   or die "Can't open socket $!\n";

setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)
   or die "Can't set socket option to SO_REUSEADDR $!\n";

# bind to a port, then listen
bind( SOCKET, pack_sockaddr_in($port, inet_aton($server)))
   or die "Can't bind to port $port! \n";

listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on port $port\n";

# accepting a connection
my $client_addr;
while ($client_addr = accept(NEW_SOCKET, SOCKET)) {
  # send them a message, close connection
  #my $name = gethostbyaddr($client_addr, AF_INET );
  #print STDERR "Connection recieved from...\n";

  my $received = "";

  while (<NEW_SOCKET>) {
    $received .= $_;
    last;
  }

  my $answer = integration($received);
  print NEW_SOCKET $answer . "§";

  close NEW_SOCKET;
}

#
# This function is used to do integration with foreign systems
# you should put inside the code to link to other system and
# return a text with the result. Remember that if the text has the
# word ERROR somewhere, the UI will stop and show the error
#

sub integration {
  my $txt_received = shift;
  $txt_received =~ s/[\r\n]+$//;

  my( $area, $check, $op, $manual_code ) = split /#/, $txt_received; # op can be: sale or void

  #return "This will\nGo to the Obs\nfield...\n$manual\n";
  #return "ERROR<br>AREA: $area, CHECK: $check";
  #return "DISCOUNT=1\nThis will\nGo to the Obs\nfield...\n$op\n$manual_code\n";
  return "DISCOUNT=1";
}


