#!/usr/bin/perl

##############################################################################
# mercur pos terminal billing                    Rendering bill L_VERSION_3.001
###     John Jan Popovic, http://1stmuse.com
###     for Etranet
##############################################################################

use CGI qw (:standard -nph);
use CGI::Carp qw(fatalsToBrowser);

#use warnings;


our $main_path;
our $root;


my    $server = "$ENV{'SERVER_NAME'}";



if ($server =~ /mfb-test/) {
    $main_path = '';
    $root = '/home/www/etranet_data/';
}
elsif ($server =~ /fiskal-test/) {
    $main_path = '';
    $root = '/eftposwwwroottst/HT_SAAS_eftposwwwroottst/';
}
elsif ($server=~ /eftpos-test/) {
    $root = 'C:/inetpub/wwwroot/';
    $main_path = 'http://eftpos-test.telekomcloud.hr/';
}
elsif ($server=~ /fiskalizacija/) {
    $main_path = "http://fiskalizacija.telekomcloud.hr/";
    $root = '//172.26.173.9/ht_interno_eftpos/wwwroot_production/'; # remote disk / netshare
}
else {
    $main_path = "http://loyalty.hr/";
    $root   = "$ENV{'DOCUMENT_ROOT'}";
}
 
my %lookup_sifra;

###############################################
###                  Set Configurations Below
###############################################
### Specify database OPERE fields in the array below
my @fields = (
    "BILL_brRacuna",              "BILL_zki",
    "BILL_jir",                   "BILL_oib",
    "BILL_uSustavuPDV",           "BILL_datum",
    "BILL_vrijeme",               "BILL_miid",
    "BILL_tiid",                  "BILL_oibOper",
    "BILL_imeOper",               "BILL_ITEMS_COMPLEX",
    "BILL_total",                 "BILL_paymentModalities",
    "BILL_pdv_COMPLEX",           "BILL_pnp_COMPLEX",
    "BILL_ostali_porezi_COMPLEX", "BILL_povratne_naknade_COMPLEX",
    "BILL_iznos_oslobodjen_pdv",  "BILL_R1_R2_COMPLEX",
    "BILL_ReceiptMessage",        "BILL_Company_COMPLEX",
    "BILL_Shop_name",             "BILL_Annex_COMPLEX"
);

# sortiranje po imenu ducana
my $MIID_SORT_OK = undef;

# enable on TEST server
$MIID_SORT_OK = 1 if $ENV{SERVER_NAME} =~ /eftpos-test/;

# CGI parametar za sortiranje Trgovina
my $MIID_SORT_CGI = '';
if ($MIID_SORT_OK) {
    $MIID_SORT_CGI = '&sort_on=2';
}

my $script_name = $ENV{SCRIPT_NAME};

my $max_rows_returned     = "100";   # Max number of rows displayed per page
my $filter_html_tags      = "yes";   # Removes HTML tags from record entries
my $authenticate          = "yes";   # Prompts users for a user name and password

############## Global Viariables ##################

my $q             = CGI->new;
my $EXCLUSIVE     = 2;
my $UNLOCK        = 8;
my $user          = $q->param('user');
$user             = $q->cookie('user') if ($user eq "");
my $user_search   = $q->param('user_search');
$user_search      = "yes" if ($authenticate eq "no");
my $user_add      = $q->param('user_add');
$user_add         = "yes" if ($authenticate eq "no");
my $user_trans    = $q->param('user_trans');
$user_trans       = "yes" if ($authenticate eq "no");
my $user_modify   = $q->param('user_modify');
$user_modify      = "yes" if ($authenticate eq "no");
my $user_delete   = $q->param('user_delete');
$user_delete      = "yes" if ($authenticate eq "no");
my $sort          = $q->param('sort_on');

my $search_for    = $q->param('search_for');
my $search_oib    = $q->param('company_oib');
my $company_oib   = $q->param('company_oib');
my $company_id    = $q->param('company_id');
my $terminal_shop = $q->param('terminal_shop');

my $search_field = $q->param('search_field');
$search_field    = "all" if ($search_field eq "");
my $action       = $q->param('action');
$action          = $q->param('which_search') if ($action =~ /^View/i);
my $key          = $q->param('key');


################# Main Logic ##################
if ($q->param('operation') eq 'logout')    {$action = 'logout'}
if ($q->param('operation') eq 'main_menu') {$action = 'Main Menu'}
if ($q->param('operation') eq 'search')    {$action = 'search'}

if ($action eq "") {
    $action = "default"
}

if ($action =~ /logout/i) {
    logout(); 
}
elsif ($action =~ /search/i) {
    search_bills($search_for, $company_oib, $terminal_shop);
    $which_search = "search";
    $what   = "search";
    billing_results($company_oib);
}
elsif ($action =~ /default/i) {
    $title = "Main Menu";
    print_default($title);
}
else {
    print STDERR "UNSUPORTED ACTION IN mfb_bills: $action\n";
    logout();
}

exit;

############## Access Problem ##############

sub access_problem {
    html_header($title);
    print <<HTML;
<BR>
<FONT SIZE=4 FACE="ARIAL" COLOR=RED><B></B></FONT><P>
<FONT SIZE=4 FACE="ARIAL">$error_message</FONT><P>
<INPUT TYPE="button" VALUE="  Natrag  " onClick="history.go(-1)"><br><br>
HTML
    html_footer();
    exit;
}

################ Get Date ##################

sub get_date {
    my @days = (
        'Sunday',   'Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday', 'Saturday'
    );
    my @months = (
        'January',   'February', 'March',    'April',
        'May',       'June',     'July',     'August',
        'September', 'October',  'November', 'December'
    );
    my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
    if ($hour < 10) {$hour = "0$hour";}
    if ($min < 10)  {$min  = "0$min";}
    if ($sec < 10)  {$sec  = "0$sec";}
    $mon++;
    $year += 1900;
    my $date = "$mday/$mon/$year at $hour\:$min\:$sec";
    return $date;
}

############## Form Header #################

sub form_header {
    print <<HTML;
<FORM name="myForm" METHOD="post" ACTION="$script_name">
<INPUT TYPE="hidden" NAME="action" VALUE="$action">
<input type="hidden" name="terminal_shop" value="$terminal_shop">
HTML
}

############## Form Footer #################

sub form_footer {
    print "<input type=hidden name=\"user_search\" value=\"$user_search\">\n";
    print "<input type=hidden name=\"user_add\" value=\"$user_add\">\n";
    print "<input type=hidden name=\"user_modify\" value=\"$user_modify\">\n";
    print "<input type=hidden name=\"user_delete\" value=\"$user_delete\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"user\" VALUE=\"$user\">\n";
    print "<input type=hidden name=\"user_trans\" value=\"$user_trans\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"authenticate\" VALUE=\"$authenticate\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"message\" VALUE=\"$message\">\n";
}

############## HTML Header #################

sub html_header {
    my $company_oib = shift;
    my $company_id  = shift;

    print "Content-type: text/html; charset=utf8\n\n";
    print <<WWW;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="resource-type" content="document" />
	<meta http-equiv="imagetoolbar" content="false" />
	<meta name="Description" content="INSERT DESCRIPTION" />
	<meta name="Keywords" content="INSERT KEYWORDS" />
	<meta name="Author" content="webmaster\@t-com.hr" />
	<meta name="Robots" content="index,follow" />
	<link rel="Shortcut Icon" href="/images/favicon.ico" type="image/ico" />
<title>T-Hrvatski Telekom</title>
<link href="../css/prva.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../css/ht.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="okvir">
<div id="heder">
	<div id="maliMeni">
        <ul>
            <li><a href="$web_site/cgi-bin/mfb_signin.cgi?operation=signin&company_oib=$company_oib" title="Tvrtka">Tvrtka </a></li>
            <li><a href="$web_site/cgi-bin/mfb_shops.cgi?company_id=$company_id&company_oib=$company_oib$MIID_SORT_CGI" title="Trgovine">Trgovine</a></li>
            <li><a href="$web_site/cgi-bin/mfb_terminals.cgi?company_id=$company_id&company_oib=$company_oib" title="Uređaji">Uređaji</a></li>
    	    <li><a href="$web_site/cgi-bin/mfb_salesmen.cgi?company_id=$company_id&company_oib=$company_oib" title="Prodavači">Prodavači</a></li>
            <li><a href="$web_site/cgi-bin/mfb_bills.cgi?company_id=$company_id&company_oib=$company_oib"  title ="Računi">Računi</a></li>
            <li><a href="$web_site/cgi-bin/mfb_signin.cgi?operation=help&company_oib=$company_oib" title ="Podrška">Podrška</a></li>
            <li><a href="$web_site/mfb" title ="Odjava">Odjava</a></li>
        </ul>
	</div>
 <ul id="nav">
            <li><a href="$web_site/cgi-bin/mfb_signin.cgi?operation=signin&company_oib=$company_oib" title="Tvrtka">Tvrtka </a></li>
            <li><a href="$web_site/cgi-bin/mfb_shops.cgi?company_id=$company_id&company_oib=$company_oib$MIID_SORT_CGI" title="Trgovine">Trgovine</a></li>
            <li><a href="$web_site/cgi-bin/mfb_terminals.cgi?company_id=$company_id&company_oib=$company_oib" title="Uređaji">Uređaji</a></li>
	        <li><a href="$web_site/cgi-bin/mfb_salesmen.cgi?company_id=$company_id&company_oib=$company_oib" title="Prodavači">Prodavači</a></li>
            <li><a href="$web_site/cgi-bin/mfb_bills.cgi?company_id=$company_id&company_oib=$company_oib"  title ="Računi">Računi</a></li>
            <li><a href="$web_site/cgi-bin/mfb_signin.cgi?operation=help&company_oib=$company_oib" title ="Podrška">Podrška</a></li>
            <li><a href="$web_site/mfb" title ="Odjava">Odjava</a></li>
    </ul>	
</div>
<!-- top menu end -->
WWW
    
    form_header();
}

############## HTML Footer #################

sub html_footer {
    print <<HTML;
    <BR></TD></TR>
    <TR><TD BGCOLOR="#e0e0e0"><CENTER> 
HTML

    form_footer();

    print <<HTML;
</form>
<!-- Footer start -->
	<div style="height:90px; width:100%; clear:both; margin:0; margin-top:75px; padding:0;background-color:transparent;background-image:url('/images/pozadinafooter.png');background-repeat:repeat-x;position:relative;">
	<div id="fusszeile">
		<div id="telekom">
		  <p>© Hrvatski Telekom, MMXIII, crafted by Etranet</p>
		</div>
		<div id="fussnavi">
				<a href="../pravne-napomene.asp"  title="">Pravne napomene</a>
		</div>
		<div class="t-icons">					
			<a href="http://www.hrvatskitelekom.hr/privatni/" title ="Privatni korisnici">Privatni korisnici</a><a href="http://www.hrvatskitelekom.hr/poslovni/" title ="Poslovni korisnici" >Poslovni korisnici</a><a href="http://www.tportal.hr" target="_blank" title ="tportal.hr" >tportal.hr</a><a href="http://www.iskon.hr" target="_blank" title ="Iskon">Iskon</a><a href="http://www.combis.hr/" target="_blank" title ="Combis">Combis</a><a href="http://www.t.ht.hr/tis"title ="Infrastrukturne telekom usluge">Infrastrukturne telekom usluge
</a>
		</div>
	</div></div>
	&nbsp;
	<div>
	<!--GO-->
    <!-- Footer end --></div>
</BODY></HTML>
HTML

}

############ Print Next Page Buttons ###########################
sub next_page_buttons {
    my $rows_left_to_view = shift;
    if ($rows_left_to_view > 0 && $show ne "no") {
        print "<P><INPUT TYPE=\"hidden\" NAME=\"new_hits_seen\" VALUE=\"$new_hits_seen\">\n";
        print "<INPUT TYPE=\"hidden\" NAME=\"which_search\" VALUE=\"$which_search\">";

        if ($rows_left_to_view == 1) {
            print <<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit();"  VALUE="View Last Record" >
HTML
        }

        if ($rows_left_to_view <= $max_rows_returned) {
            print <<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit();"  VALUE="View Last $rows_left_to_view Records" >
HTML
        }

        if ($rows_left_to_view > $max_rows_returned) {
            print <<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit();"  VALUE="View Next $max_rows_returned Records" >
HTML
        }
    }

}

############### render_bill old version1 ################
sub render_bill_version1 {
    my $bill_record = shift;

    my (
        $key,                           $dbuser,
        $when_added,                    $BILL_brRacuna,
        $BILL_zki,                      $BILL_jir,
        $BILL_oib,                      $BILL_uSustavuPDV,
        $BILL_datum,                    $BILL_vrijeme,
        $BILL_miid,                     $BILL_tiid,
        $BILL_oibOper,                  $BILL_imeOper,
        $BILL_ITEMS_COMPLEX,            $BILL_total,
        $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
        $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
        $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
        $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
        $BILL_Company_COMPLEX,          $BILL_Shop_name,
        $BILL_Annex_COMPLEX
    ) = split(/\|/, $bill_record);

    #print "<br><br>BILL_RECORD: $bill_record<br>";

    #print "<br><br>BR: $BILL_brRacuna<br>";

    $complex_bill_number =
      $BILL_brRacuna . " - " . $BILL_miid . " - " . $BILL_tiid;

    #print "<br><br>CX BR: $complex_bill_number<br>";

    $r1_r2 = "0";

    my @a = ();
    if ($BILL_R1_R2_COMPLEX eq "") {$BILL_R1_R2_COMPLEX = "0;"}
    if ($BILL_R1_R2_COMPLEX ne "0;") {
        (
            $r1_r2, $tvrtka_klijenta, $adresa_klijenta,
            $postanski_broj_klijenta, $grad_klijenta, $oib_klijenta
        ) = split(/\;/, $BILL_R1_R2_COMPLEX);
    }

    if ($r1_r2 > 0) {
        $r1_r2 = "R" . $r1_r2;
    }
    $r1_r2 =~ s/r/R/g
      ; #flexibility -- it works for 1, R1, r1 (and 2, R2, r2) - all values are interpreted equaly

    $r1_r2_annex = qq~
<tr>
         <td colspan=2 ><hr></td>
</tr>
<tr>
         <td colspan=2 align="center"><b>Račun $r1_r2 </b></td>
         </tr>
         <tr>
         <td>Klijent: $tvrtka_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td>Adresa: $adresa_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td> Mjesto: $postanski_broj_klijenta $grad_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td>OIB: $oib_klijenta</td>
         <td></td>
<tr>
         <td colspan=2 ><hr></td>
</tr>
~;

    if ($r1_r2 eq "0") {
        $r1_r2_annex = "";
    }

    (
        $company_Ime,              $company_Adresa_Ulica,
        $company_Adresa_KucniBroj, $company_Adresa_KucniBrojDodatak,
        $company_Adresa_BrojPoste, $company_Adresa_Opcina,
        $shop_descriptive_name
    ) = split(/\;/, $BILL_Company_COMPLEX);

    $pj_annex = "";
    $shop_descriptive_name =~ s/\;//g;
    if ($shop_descriptive_name ne "") {
        $pj_annex = "PJ: $shop_descriptive_name";
    }

    $BILL_Shop_name =~ s/\;//g;
    if ($BILL_Shop_name ne "") {$pj_annex = "PJ: $BILL_Shop_name";}

    $pj_annex =~ s/\s+/ /g;
    if ($pj_annex eq "PJ: ") {$pj_annex = "";}

    $BILL_oib =~ s/HR//g;
    $pdv_broj = "HR" . $BILL_oib;

    print <<HTML;
$company_Ime<br>
$company_Adresa_Ulica $company_Adresa_KucniBroj $company_Adresa_KucniBrojDodatak, $company_Adresa_BrojPoste $company_Adresa_Opcina<br>
OIB:  <b> $BILL_oib</b> <br>
$pj_annex <br>
<br>
<table border="0" cellspacing="0"  width="400">
        <tbody>
$r1_r2_annex
<tr>
         <td>Datum: $BILL_datum</td>
         <td align="right">Vrijeme: $BILL_vrijeme</td>
         </tr>
        <tr>
         <td colspan=2 >Blagajnik: $BILL_imeOper, 
         OIB: $BILL_oibOper</td>
         </tr>
        <tr>
         <td>Oznaka prodajnog mjesta: $BILL_miid</td>
         <td></td>
         </tr>
        <tr>
         <td>Oznaka naplatnog uređaja: $BILL_tiid</td>
         <td></td>
         </tr>
        <tr>
         <td colspan=2 align="center"><b><br>RN: $complex_bill_number </b></td>
         </tr>
       	</tbody>
</table>
<br>
    <table border="0" cellspacing="0" width="400">
    <tbody>
   <tr><td colspan=4>ZKI: $BILL_zki</td></tr> 
   <tr><td colspan=4>JIR: $BILL_jir </td></tr> 
   <tr><td colspan=4><hr> </td></tr> 
        <tr>
         <td>Artikl&nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Količina</td>
         <td align="right">&nbsp;&nbsp;Jed.cij.</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Iznos&nbsp;(kn)</td>
         </tr>
HTML

    ($n_items, @a) = split(/\;/, $BILL_ITEMS_COMPLEX);
    $offset = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $quantity = $a[$offset + 1];

        #  $quantity =~ s/\.000//g;
        print qq|
      <tr>
         <td>$a[$offset] </td>
         <td align="right">$quantity   </td>
         <td align="right">$a[$offset+2] </td>
         <td align="right">$a[$offset+3]</td>
      </tr>|;

        $offset += 4;
    }

    my $paymentModality = "";
    if    ($BILL_paymentModalities eq "G") {$paymentModality = "Novčanice";}
    elsif ($BILL_paymentModalities eq "K") {$paymentModality = "Kartice";}
    elsif ($BILL_paymentModalities eq "T") {$paymentModality = "Transakcijski račun";}
    elsif ($BILL_paymentModalities eq "C") {$paymentModality = "Ček";}
    elsif ($BILL_paymentModalities eq "O") {$paymentModality = "Ostalo";}

    print <<ZZZ;
   <tr>
         <td colspan=4><hr> </td>
   </tr>    	
   <tr>
         <td>UKUPNO KN ($paymentModality):</td>
         <td></td>
         <td></td>
         <td align="right"><b>$BILL_total</b></td>
   </tr>  
   <tr>
         <td colspan=4><hr> </td>
   </tr> 
ZZZ

    $porezi_ispis = "";
    @a            = ();
    ($n_items, @a) = split(/\;/, $BILL_pdv_COMPLEX);
    $offset = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $porezi_ispis .= qq|
      <tr>
         <td>PDV ($a[$offset] %)</td>
         <td align="right">$a[$offset+1] </td>
         <td></td>
         <td align="right">$a[$offset+2] </td>
      </tr>|;
        $offset += 3;
    }

    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_pnp_COMPLEX);
    $offset = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $porezi_ispis .= qq|
      <tr>
         <td>PNP ($a[$offset] %) </td>
         <td align="right">$a[$offset+1] </td>
         <td></td>
         <td align="right">$a[$offset+2] </td>
      </tr>|;

        $offset += 3;
    }

########## ostali_porezi_COMPLEX
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_ostali_porezi_COMPLEX);
    $offset = 0;

    for ($i = 1 ; $i <= $n_items ; $i++) {
        $porezi_ispis .= qq|
      <tr>
         <td> $a[$offset] ($a[$offset +1] %) </td>
         <td align="right"> $a[$offset +2] kn</td>
         <td>  </td>
         <td>  </td>
         <td align="right"> $a[$offset+3]  kn</td>
      </tr>|;

        $offset += 4;
    }

########## end of ostali_porezi_COMPLEX

    print <<HTML;
   <tr>
         <td colspan=4 align="center"> POREZI  </td>
   </tr> 
   <tr>
         <td>Stopa</td>
         <td align="right">Osnovica</td>
         <td></td>
         <td align="right">Porez</td>
   </tr> 
$porezi_ispis
HTML

##########  povratne_naknade_COMPLEX
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_povratne_naknade_COMPLEX);

    if ($n_items > 0) {
        print <<HTML;
  
   <tr><td colspan=4><hr> </td></tr> 
   <tr><td colspan=4 align="center"> POVRATNE NAKNADE </td></tr> 
   <tr>
       <td>Naziv</td>
       <td align="right">Količina</td>
       <td></td>
       <td align="right">Iznos</td>
   </tr> 
HTML

        $offset = 0;

        for ($i = 1 ; $i <= $n_items ; $i++) {
            print qq|
      <tr>
         <td> $a[$offset]  </td>
         <td align="right"> $a[$offset+1]  </td>
         <td>  </td>
         
         <td align="right"> $a[$offset+2] kn</td>
      </tr>|;

            $offset += 3;
        }
    }
########## end of povratne_naknade_COMPLEX

    $tax_exemption = qq~
     <tr>
         <td>Oslobođeno PDV-a (kn):</td>
         <td align="right"> $BILL_iznos_oslobodjen_pdv</td>
         <td></td>
         <td align="right"> </td>
      </tr>
~;

    if ($BILL_iznos_oslobodjen_pdv == 0) {
        $tax_exemption = "";
    }

    print <<HTML;
    $tax_exemption

   <tr><td colspan=4><hr> </td></tr>    	
   <tr><td colspan=4 align="center">$BILL_ReceiptMessage </td></tr>    
   <tr><td colspan=4><hr> </td></tr> 
   <tr><td colspan=4 align="center"> </td></tr> 
   <tr><td colspan=4><hr> </td></tr> 
    </tbody></table>
HTML

    # K O P I J A
}
############### end of render_bill old ################

################ Default Screen ##################
sub print_default {

    my $title = shift;

    # Create terminal_select
    $terminal_shop   = "0:0:0:0";
    $terminal_select = terminal_dropdown();

    # end of creating of terminal_select

    html_header($search_oib, $company_id);
    print <<HTML;
<style type="text/css">
<!--
.gray_text {color: #555555}
-->
</style>
<div class="tekst1">
$title
  <TABLE BORDER=0 CELLSPACING="0" CELLPADDING="3" class="gray_text"><TR><TD COLSPAN=3>
  <TR>
<TD width="350"> Pretraživanje računa: <br>
<SELECT NAME="search_field">
<OPTION VALUE="0" >Broj računa
<OPTION VALUE="1" >ZKI
<OPTION VALUE="2" >JIR
<OPTION VALUE="5" >(dd.mm.yyyy)
<OPTION VALUE="40" >(mm.yyyy)
</SELECT>
<INPUT TYPE="text" NAME="search_for" SIZE="10" 
onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
           {myForm.action.value='search';this.form.submit();return false;} 
else return true;" ></TD>
          <TD width="234" > 
<br>
<input onclick="myForm.action.value='search';this.form.submit();" value="Dohvat" type="button"> 
</TD>
 <TD width="170">
<INPUT TYPE="hidden" NAME="search_oib"  value="$search_oib"  >
<INPUT TYPE="hidden" NAME="company_oib"  value="$company_oib"  >
<INPUT TYPE="hidden" NAME="company_id"  value="$company_id"  >
$terminal_select
 </TD> 
</TR>
<TR>
   <TD><BR>
   </TD>
<TD>
<input TYPE="hidden" NAME="sort_on" VALUE="5" >
</TD>
<TD><BR>
</TD></TR></TABLE><br>
</div>
HTML
    $footer = "default";
    html_footer();
}    # End of print_default subroutine.

########### Search BTerminal file TID_basic.csv #############
sub fetch_terminal_file {
    my $tid             = $_[0];
    my $err_message     = "";
    my $activity        = 1;
    my $miid_descriptor = "";

    $database_tid = "$root/mercur_data/B" . $tid . ".csv";

    my $TERMINAL_MIID;
    my $TERMINAL_PoslPr;
    my $TID_BASIC_PoslPr_Adresa;
    my $TID_BASIC_PoslPr_KucniBroj;
    my $TID_BASIC_PoslPr_KucniBrojDodatak;

    if (-e $database_tid) {
        open(DB, "$database_tid") or die " . \n";
        @record = <DB>;

        (
            $TERMINAL_TID,                      $TERMINAL_Ime_tvrtke,
            $TERMINAL_OIB,                      $U_sustavu_pdv,
            $TERMINAL_MIID,                     $TERMINAL_PoslPr,
            $TID_BASIC_PoslPr_Adresa,           $TID_BASIC_PoslPr_KucniBroj,
            $TID_BASIC_PoslPr_KucniBrojDodatak, $TID_BASIC_PoslPr_BrojPoste,
            $TID_BASIC_PoslPr_Naselje,          $TID_BASIC_PoslPr_Opcina,
            $Ostali_tipovi_posl_prostora,       $TERMINAL_Radno_vrijeme,
            $TERMINAL_TIID,                     $TERMINAL_NacPl,
            $TERMINAL_Status,                   $TERMINAL_Message
        ) = split(/\;/, $record[1]);

#  00010;Etranet d.o.o.;Da;9;Etranet shop;Radnička cesta;80;B;10000;Centar;Zagreb;;Pon-Pet: 8.00-16.00;01/01/13;otvoreno;;;GKT;active;

        $TERMINAL_TID =~ s/\s//g;

        $activity = 0;

        chomp $TERMINAL_Status;
        if ($TERMINAL_Status =~ /^active/i) {$activity = 1}
        if ($TERMINAL_Status == 1)          {$activity = 1}

        $miid_descriptor = "$TERMINAL_MIID\. $TERMINAL_PoslPr";
        $err_message     = "";

        close(DB);
    }
    else {
        $err_message = " - \n";
    }

    if ($activity == 0) {
        $err_message = " .";
    }

    return "$err_message~$miid_descriptor~$TERMINAL_TIID ($TERMINAL_Status)";

}

# End of Search Terminals BASIC Terminal File subroutine.

################ terminal_dropdown ##################
sub terminal_dropdown {

    my $terminal_select;
    my %record    = ();
    my @results   = ();
    my %shop_hash = ();

    # Create terminal_select
    $terminal_shop = "0:0:0:0";
    $terminal_select =
qq~Odaberite: <br><select name="dropdown_terminal_shop"  onClick="document.myForm.terminal_shop.value= document.myForm.dropdown_terminal_shop.value";
   id="dropdown_terminal_shop" onkeydown="return tabOnEnter (this, event);">~;
    $terminal_select .=
      qq~<option value="0:0:0:0"> sve trgovine  - sve uređaje  </option>~;

    $database_terminals =
      "$root/mercur/mercur_terminals.txt";  # Data file companies name and path

    my @TT_line = ();
    open(TERMILNALS, "<", $database_terminals)
      || die "Error opening database. $! $database_terminals \n";
    @TT_line = <TERMILNALS>;
    close(TERMILNALS);

    $k = 0;
    foreach $adonis_record (@TT_line) {
        chomp $adonis_record;
        @altro = ();
        (
            $key, $dbuser, $when_added, $TERMINAL_TID, $TERMINAL_CompanyID,
            $TERMINAL_ShopID, $TERMINAL_TIID, @altro
        ) = split(/\|/, $adonis_record);

        $DBADONIS_hash{$key} = $adonis_record;
        if ($TERMINAL_CompanyID == $company_id) {
            my $tid_complex = fetch_terminal_file($TERMINAL_TID);

            if ($tid_complex =~ /error/i) {
                print "$tid_complex<br>";
            }
            else {
                ($error_message, $MIID_descriptor, $TIID_descriptor) = split(
                    /\~/, $tid_complex
                  );
            }

            $k++;
            $TERMINAL_ShopID =~ s/^\s+//;    # - trimming leading whitespace
            $TERMINAL_ShopID =~ s/\s+$//;    # - trimming trailing whitespace

            $MIID_descriptor =~ s/^\s+//;    # - trimming leading whitespace
            $MIID_descriptor =~ s/\s+$//;    # - trimming trailing whitespace
            if ($MIID_descriptor eq "") {
                $MIID_descriptor = "neodređeno prodajno mjesto";
            }

            $shop_hash{$MIID_descriptor} = $TERMINAL_ShopID;

            push @results,
"$k\|$TERMINAL_TID\|$TERMINAL_TIID\|$TERMINAL_ShopID\|$MIID_descriptor";

        }
    }

    # end of creating @results

    my @shops = keys %shop_hash;

    foreach $curr (@results) {
        ($k, $terminal_TID, $terminal_TIID, $shop_id, $shop_MIID_descriptor) =
          split(/\|/, $curr);

        $code = '$record{$k} = { k => "$k", ';
        $code .= 'terminal_TID => "$terminal_TID", ';
        $code .= 'terminal_TIID => "$terminal_TIID", ';
        $code .= 'shop_id => "$shop_id", ';
        $code .= 'shop_MIID_descriptor => "$shop_MIID_descriptor" ';
        $code .= '};';

        eval $code;
    }    # End of foreach curr

    @results = ();

    foreach $rp (
        sort {
            $a->{shop_MIID_descriptor} cmp $b->{shop_MIID_descriptor}
              or $a->{terminal_TIID} cmp $b->{terminal_TIID}
        } values %record
      )
    {
        $new_rec = $rp->{k};
        $new_rec .= "\|$rp->{terminal_TID}";
        $new_rec .= "\|$rp->{terminal_TIID}";
        $new_rec .= "\|$rp->{shop_id}";
        $new_rec .= "\|$rp->{shop_MIID_descriptor}";
        push @results, $new_rec;
    }    # End of foreach

    foreach $curr (sort(@shops)) {
        ($shop_MIID, $shop_descriptor) = split(/\./, $curr);
        ($shop_name, $shop_address)    = split(/\,/, $curr);
        $terminal_select .=
qq~<option value="-1:-1:$shop_hash{$curr}:$shop_MIID"> $shop_name  - svi uređaji </option>\n~;

    }    # End of foreach curr

    foreach $curr (@results) {
        ($k, $terminal_TID, $terminal_TIID, $shop_id, $shop_MIID_descriptor) =
          split(/\|/, $curr);
        ($shop_MIID, $shop_descriptor) = split(/\./, $shop_MIID_descriptor);
        ($shop_name, $shop_address)    = split(/\,/, $shop_MIID_descriptor);
        $terminal_select .=
qq~<option value="$terminal_TID:$terminal_TIID:$shop_hash{$shop_MIID_descriptor}:$shop_MIID"> $shop_name  - uređaj $terminal_TIID  </option>\n~;
    }    # End of foreach curr

    $terminal_select .= qq~</select>~;

    return $terminal_select;

}

########### Search & Sort Database #############
sub search_bills {
    my $search_for = shift;
    my $search_oib = shift;
    my %record     = ();
    @results = ();
    my %jir_hash    = ();
    my %zki_hash    = ();
    my %jir_counter = ();
    my %zki_counter = ();

    my ($tid, $tiid, $mid, $miid) = split(/\:/, $terminal_shop);    # 701889:1:801554:Primosten
    my $oib = $search_oib;
    $oib =~ s/HR//g;

    my $db_oib = "$root/mercur_billing/billing_oib" . "_" . $oib . ".txt";    # new naming

    $search_for =~ s/\s//g;
    $search_for =~ s/[\/]/\./g;    # normalise flexible calendar format

    if ($search_for =~ /d+\.d+\.d+/) {
        my ($dd, $mm, $yyyy) = split(/\./, $search_for);
        if ($yyyy < 100) {$yyyy = 2000 + $yyyy}
        $mm = sprintf("%02d", $mm);
        $search_for = "$dd.$mm.$yyyy";
    }
    elsif ($search_for =~ /^d+\.d+$/) {
        my ($mm, $yyyy) = split(/\./, $search_for);
        if ($yyyy < 100) {$yyyy = 2000 + $yyyy}
        $mm = sprintf("%02d", $mm);
        $search_for = "$mm.$yyyy";
    }

    if (-e $db_oib) {
        open(my $DB, "<", $db_oib) || die "Error opening database. $db_oib $!\n";

        while (<$DB>) {
            (
                $key,           $dbuser,           $when_added,
                $BILL_brRacuna, $BILL_zki,         $BILL_jir,
                $BILL_oib,      $BILL_uSustavuPDV, $BILL_datum,
                $BILL_vrijeme,  $BILL_miid,        $BILL_tiid,
                $BILL_oibOper,  $BILL_imeOper,     @altro
            ) = split(/\|/, $_);

            $search_oib =~ s/\s//g;
            $BILL_oib =~ s/HR//g;

            if ($BILL_oib eq $search_oib) {

                # patch: računi se se sada  MOGU PRIKAZATI i pretraživati zasebno po uređajima i kod naziva MIIDA više od 9 znakova!
                my $BILL_miid9 = $BILL_miid;
                if (length($BILL_miid) > 8) {
                    $BILL_miid9 = substr($BILL_miid, 0, 8);
                }

                my $miid9 = $miid;
                if (length($miid) > 8) {
                    $miid9 = substr($miid, 0, 8);
                }

                # end of patch

                if (
                    (($tiid == -1) && ($BILL_miid9 eq $miid9))
                    || (($tiid == 0)
                        || (   ($BILL_tiid eq $tiid)
                            && ($BILL_miid9 eq $miid9)))
                  )
                {    # one particular shop 1st line # one particular terminal

                    if ($search_for =~ /\-/) {    # brRacuna
                        my ($rn_a, $rn_b, $rn_c) = split(/\-/, $search_for);

                        # RN: $BILL_brRacuna-$BILL_miid-$BILL_tiid
                        if (   ($BILL_brRacuna == $rn_a)
                            && ($BILL_miid == $rn_b)
                            && ($BILL_tiid == $rn_c))
                        {
                            push @results, $_;
                        }
                    }
                    else {
                        if ($BILL_brRacuna == $search_for) {
                            push @results, $_;
                        }
                    }

                    # end brRacuna

                    if ($BILL_zki eq $search_for) {
                        push @results, $_;
                    }    # zki
                    elsif ($BILL_jir eq $search_for) {
                        push @results, $_;
                    }   # jir
                    elsif ($BILL_datum eq $search_for) {
                        push @results, $_;
                    }   # calendar date
                    elsif ($BILL_datum =~ m/$search_for/) {
                        push @results, $_;
                    }   # calendar month
                }
            }
        }    # End of while.
        close($DB);
    }
    else {
        $error_message = "Potrebno je napraviti zatvaranje dana (zaključni obračun) na uređaju, kako biste mogli vidjeti Vaše račune u internetskoj aplikaciji.";
        access_problem($error_message);
        exit;
    }

    for my $curr (@results) {
        my ($key, $dbuser, $when_added, @rest) = split(/\|/, $curr);
        $max  = @fields;
        $code = '$record{$key} = { key => "$key", ';
        $code .= 'dbuser => "$dbuser", ';
        $code .= 'when_added => "$when_added", ';
        for ($x = 0 ; $x < $max ; $x++) {
            $code .= "\$fields[$x] => \"\$rest[$x]\",\n";
        }    # End of for
        $code .= '};';
        eval $code;
    }    # End of foreach curr

    $sort_datum   = $fields[5];
    $sort_vrijeme = $fields[6];
    @results      = ();

    foreach $rp (
        sort {
            $a->{$sort_datum} cmp $b->{$sort_datum}
              or $a->{$sort_vrijeme} cmp $b->{$sort_vrijeme}
        } values %record
      )
    {
        $new_rec = $rp->{key};
        $new_rec .= "\|$rp->{dbuser}";
        $new_rec .= "\|$rp->{when_added}";
        for ($x = 0 ; $x < $max ; $x++) {
            $new_rec .= "\|$rp->{$fields[$x]}";
        }    # End of for
        push @results, $new_rec;
    }    # End of foreach

############## export start #################################################3

#### export LEDO billing #############################################################3

    %zki_hash    = ();
    %jir_counter = ();
    %zki_counter = ();

    $key = time();
    $export_csv = $root . "/mercur_export/$key" . "_" . $search_oib . "ledo_billing.csv";
    $ledo_URL = $main_path . "/mercur_export/$key" . "_" . $search_oib . "ledo_billing.csv";

    open(LEDO, ">$export_csv") or die "Nepostojeća datoteka: $export_csv $!\n";

########### Create price listing hash for LEDO #############

    $test = "$root/mercur/test_ledo.txt";
    open(TEST, ">>", "$test")
      || die "Error loading update_directives. $! $test\n";
    $date_time = get_date();
    print TEST "$date_time\n";

    $pricelisting_ = "$root/mercur_billing/ledo_complete_listing.csv";
    my @price_record = ();

    if (-e $pricelisting_) {
        open(PRICES, "$pricelisting_") or die " . \n";
        @price_record = <PRICES>;
        close(PRICES);

        foreach $r (@price_record) {
            chop $r;
            (
                $cjenik_Grupa,    $cjenik_Sifra, $cjenik_Naziv,
                $cjenik_JedMjere, $cjenik_cjena, $cjenik_StopaPDV,
                @altro
            ) = split(/\;/, $r);
            $sifra = $cjenik_Sifra;
            $cjenik_hash{$sifra} = $r;

            $naziv_key = $cjenik_Naziv;
            $naziv_key =~ s/\W//g;
            $naziv_key = lc($naziv_key);
            $lookup_sifra{$naziv_key} = "$cjenik_Sifra";
            print TEST "$naziv_key $lookup_sifra{$naziv_key}\n";
        }
    }

    print TEST " \n";
    $naziv_sifra_lookup = "$root/mercur_billing/ledo_sifre_artikala.csv";
    my @lookup_record = ();

    if (-e $naziv_sifra_lookup) {
        open(LOOKUP, "$naziv_sifra_lookup") or die " $naziv_sifra_lookup . \n";
        @lookup_record = <LOOKUP>;
        close(LOOKUP);

        foreach $lookup (@lookup_record) {
            $lookup =~ s/\s//g;
            chop $lookup;
            ($ledo_sifra, $naziv_artikla) = split(/\;/, $lookup);
            $naziv_key = $naziv_artikla;
            $naziv_key =~ s/\W//g;
            $naziv_key = lc($naziv_key);
            $lookup_sifra{$naziv_key} = "$ledo_sifra";
            print TEST "$naziv_key $lookup_sifra{$naziv_key}\n";
        }
        close(TEST);
    }

    # End of LEDO price listing hash  ########################

    # build LEDO billing records  ########################

    my @ledo_bills = ();
    foreach $record (@results) {
        my (
            $key,                           $dbuser,
            $when_added,                    $BILL_brRacuna,
            $BILL_zki,                      $BILL_jir,
            $BILL_oib,                      $BILL_uSustavuPDV,
            $BILL_datum,                    $BILL_vrijeme,
            $BILL_miid,                     $BILL_tiid,
            $BILL_oibOper,                  $BILL_imeOper,
            $BILL_ITEMS_COMPLEX,            $BILL_total,
            $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
            $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
            $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
            $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
            $BILL_Company_COMPLEX,          $BILL_Shop_name,
            $BILL_Annex_COMPLEX
        ) = split(/\|/, $record);

        chomp $record;
        $record =~ s/\n//g;
        $record =~ s/\r//g;

        $BILL_oib =~ s/HR//g;

        if ($oib == $BILL_oib) {
            if (($old_jir ne $BILL_jir) || ("N/A" eq $BILL_jir)) {

                $bill_key = $BILL_brRacuna . $BILL_datum . $BILL_miid;
                $bill_key =~ s/\W//g;
                $clean_jir = $BILL_jir;
                $clean_jir =~ s/\W//g;
                $jir_hash{$bill_key} .= $clean_jir . ",";
                push @ledo_bills, $record;

            }
            $old_zki = $BILL_zki;
            $old_jir = $BILL_jir;
        }

    }    # End of foreach record loop.

#   pogledati da li N/A račun extended_billing($record) ima također i JIR račun?
#   u pivot tabeli oni "N/A" računi koji imaju i JIR račun NE PRIKAZUJU SE u tabeli!
#   u proširenoj pivot - extended pivot tabeli ne bi se trebali nalaziti oni slogovi, koji su naknadno dobili JIR

    print LEDO
qq~Datum prodaje;Vrijeme prodaje;Datum ulaska u bazu;Blagajnik ime;Blagajnik OIB;Prodajno mjesto sifra;Prodajno mjesto naziv;Oznaka naplatnog uređaja;Broj računa;Način plačanja;Artikl šifra;Artikl opis;Količina;Iznos kn;Osnovica za PDV kn;Iznos PDV-a kn;ZKI;JIR\n~;

    foreach $record (@ledo_bills) {
        my (
            $key,                           $dbuser,
            $when_added,                    $BILL_brRacuna,
            $BILL_zki,                      $BILL_jir,
            $BILL_oib,                      $BILL_uSustavuPDV,
            $BILL_datum,                    $BILL_vrijeme,
            $BILL_miid,                     $BILL_tiid,
            $BILL_oibOper,                  $BILL_imeOper,
            $BILL_ITEMS_COMPLEX,            $BILL_total,
            $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
            $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
            $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
            $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
            $BILL_Company_COMPLEX,          $BILL_Shop_name,
            $BILL_Annex_COMPLEX
        ) = split(/\|/, $record);

        chomp $record;
        $record =~ s/\n//g;
        $record =~ s/\r//g;

        $BILL_oib =~ s/HR//g;

        $bill_key = $BILL_brRacuna . $BILL_datum . $BILL_miid;
        $bill_key =~ s/\W//g;
        $bill_signed = NAbill_with_jir($jir_hash{$bill_key});

        if (($bill_signed == 0) && ("N/A" eq $BILL_jir)) {

            # "N/A"  BILL is not signed, i.e. the bill has not jir
            print_ledo_billing($record);
        }

        if ($BILL_jir ne "N/A") {
            print_ledo_billing($record);
        }

    }    # End of foreach record loop.

    $n_results = @results;

    if ($n_results == 1) {
        print_ledo_billing($record);
    }

    close(LEDO);

######### LEDO export end ######################################################

#### export  billing / strojni eksport #######################################

    %jir_hash    = ();
    %zki_hash    = ();
    %jir_counter = ();
    %zki_counter = ();

    my @export_bills = ();

    $key = time();
    $export_csv = "$root/mercur_export/$key" . "_" . $search_oib . "export_billing.csv";
    $export_URL = $main_path . "/mercur_export/$key" . "_" . $search_oib . "export_billing.csv";

    foreach $r (@results) {
        my (
            $key,                           $dbuser,
            $when_added,                    $BILL_brRacuna,
            $BILL_zki,                      $BILL_jir,
            $BILL_oib,                      $BILL_uSustavuPDV,
            $BILL_datum,                    $BILL_vrijeme,
            $BILL_miid,                     $BILL_tiid,
            $BILL_oibOper,                  $BILL_imeOper,
            $BILL_ITEMS_COMPLEX,            $BILL_total,
            $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
            $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
            $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
            $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
            $BILL_Company_COMPLEX,          $BILL_Shop_name,
            $BILL_Annex_COMPLEX
        ) = split(/\|/, $r);

        chomp $r;
        $r =~ s/\n//g;
        $r =~ s/\r//g;

        if (($old_jir ne $BILL_jir) || ("N/A" eq $BILL_jir)) {

            $bill_key = $BILL_brRacuna . $BILL_datum . $BILL_miid;
            $bill_key =~ s/\W//g;
            $clean_jir = $BILL_jir;
            $clean_jir =~ s/\W//g;
            $jir_hash{$bill_key} .= $clean_jir . ",";
            push @export_bills, $r;

        }
        $old_zki = $BILL_zki;
        $old_jir = $BILL_jir;

    }    # End of foreach record loop.

    flock EXPORTDB, $EXCLUSIVE;
    open(EXPORTDB, ">$export_csv")
      or die "Nepostojeća datoteka: $export_csv $!\n";

    foreach $record (@export_bills) {
        my (
            $key,                           $dbuser,
            $when_added,                    $BILL_brRacuna,
            $BILL_zki,                      $BILL_jir,
            $BILL_oib,                      $BILL_uSustavuPDV,
            $BILL_datum,                    $BILL_vrijeme,
            $BILL_miid,                     $BILL_tiid,
            $BILL_oibOper,                  $BILL_imeOper,
            $BILL_ITEMS_COMPLEX,            $BILL_total,
            $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
            $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
            $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
            $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
            $BILL_Company_COMPLEX,          $BILL_Shop_name,
            $BILL_Annex_COMPLEX
        ) = split(/\|/, $record);

        chomp $record;
        $record =~ s/\n//g;
        $record =~ s/\r//g;

        $record =~ s/\'//g;
        $record =~ s/\"//g;

        $BILL_oib =~ s/HR//g;

        $zki_hash{$BILL_zki} += 1;
        $zki_counter = $zki_hash{$BILL_zki};

        $jir_counter{$BILL_jir} += 1;

        $bill_key = $BILL_brRacuna . $BILL_datum . $BILL_miid;
        $bill_key =~ s/\W//g;
        $bill_signed = NAbill_with_jir($jir_hash{$bill_key});

        if (($bill_signed == 0) && ("N/A" eq $BILL_jir) && ($zki_counter < 2)) {

# "N/A"  BILL is not signed  AND  the bill has not jir AND it is not double ZKI bill, i.e.  ZKI must be enlisted only once
            print EXPORTDB "$record\n";
        }

        if (($BILL_jir ne "N/A") && ($jir_counter{$BILL_jir} < 2)) {

#  BILL is  signed, i.e. the bill has jir, AND one BILL_jir must be enlisted only once
            print EXPORTDB "$record\n";
        }

    }    # End of foreach record loop.

    $n_results = @results;

    if ($n_results == 1) {
        $record = $results[0];
        print EXPORTDB "$record\n";
    }

    close(EXPORTDB);
    flock EXPORTDB, $UNLOCK;
#### end of export csv billing .. strojni export  #####################################

#### export EXTENDED billing

    %zki_hash    = ();
    %jir_counter = ();
    %zki_counter = ();

    $key = time();
    $export_csv = $root . "/mercur_export/$key" . "_" . $search_oib . "extended_billing.csv";
    $extended_URL = $main_path . "/mercur_export/$key" . "_" . $search_oib . "extended_billing.csv";

    open(EXT, ">$export_csv") or die "Nepostojeća datoteka: $export_csv $!\n";

    print EXT
qq~Datum prodaje;Vrijeme prodaje;Datum ulaska u bazu;Blagajnik ime;Blagajnik OIB;Prodajno mjesto sifra;Prodajno mjesto naziv;Oznaka naplatnog uređaja;Broj računa;Način plačanja;Artikl šifra;Artikl opis;Količina;Iznos;Osnovica za PDV;Stopa PDV-a;ZKI;JIR;Iznos PDV-a\n~;

#   pogledati da li N/A račun extended_billing($record) ima također i JIR račun?
#   u pivot tabeli oni "N/A" računi koji imaju i JIR račun NE PRIKAZUJU SE u tabeli!
#   u proširenoj pivot tabeli ne bi se trebali nalaziti oni slogovi, koji su naknadno dobili JIR

    foreach $record (@export_bills) {
        my (
            $key,                           $dbuser,
            $when_added,                    $BILL_brRacuna,
            $BILL_zki,                      $BILL_jir,
            $BILL_oib,                      $BILL_uSustavuPDV,
            $BILL_datum,                    $BILL_vrijeme,
            $BILL_miid,                     $BILL_tiid,
            $BILL_oibOper,                  $BILL_imeOper,
            $BILL_ITEMS_COMPLEX,            $BILL_total,
            $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
            $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
            $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
            $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
            $BILL_Company_COMPLEX,          $BILL_Shop_name,
            $BILL_Annex_COMPLEX
        ) = split(/\|/, $record);

        chomp $record;
        $record =~ s/\n//g;
        $record =~ s/\r//g;

        $BILL_oib =~ s/HR//g;

        $zki_hash{$BILL_zki} += 1;
        $zki_counter = $zki_hash{$BILL_zki};

        $jir_counter{$BILL_jir} += 1;

        $bill_key = $BILL_brRacuna . $BILL_datum . $BILL_miid;
        $bill_key =~ s/\W//g;
        $bill_signed = NAbill_with_jir($jir_hash{$bill_key});

        if (($bill_signed == 0) && ("N/A" eq $BILL_jir) && ($zki_counter < 2)) {

# "N/A"  BILL is not signed  AND  the bill has not jir AND it is not double ZKI bill, i.e.  ZKI must be enlisted only once
            print_extended_billing($record);
        }

        if (($BILL_jir ne "N/A") && ($jir_counter{$BILL_jir} < 2)) {

#  BILL is  signed, i.e. the bill has jir, AND one BILL_jir must be enlisted only once
            print_extended_billing($record);
        }

    }    # End of foreach record loop.

    $n_results = @results;

    if ($n_results == 1) {
        $record = $results[0];
        print_extended_billing($record);
    }

    close(EXT);

######### EXTENDED export end ######################################################

    $count = @results;
    if ($count < 1) {
        $message =
"NE POSTOJI NITI JEDAN ZAPIS PO TRAŽENOM KRITERIJU: $search_for / $terminal_shop"
          ;    # NE POSTOJI NITI JEDAN ZAPIS PO TRAŽENOM KRITERIJU
        $title = "Main Menu";
        print_default($message);
        exit;
    }
    $total_row_count = @results;
    if ($total_row_count > $max_rows_returned) {
        $hits_seen = $q->param('new_hits_seen');
        for ($i = 1 ; $i <= $hits_seen ; $i++) {$seen_row = shift(@results);}
        $length_of_database_rows = @results;
        for ($i = $length_of_database_rows - 1 ;
            $i >= $max_rows_returned ; $i--)
        {
            $extra_row = pop(@results);
        }
        $new_hits_seen = $hits_seen + @results;
    }
    else {$show = "no";}
}    # End of search_bill subroutine.

############# Results Screen ################
sub billing_results {
    my $r;
    my $oib = $_[0];
    $oib =~ s/HR//g;

    html_header($search_oib, $company_id);
    my $rows_left_to_view = $total_row_count - $new_hits_seen;
    my $start_hit         = $hits_seen + 1;
    my $end_hit           = $new_hits_seen;
    my $hits_displayed    = $end_hit - $start_hit + 1;
    
    if ($total_row_count > 1) {

        # print qq~<P>Total Found: <B>$total_row_count</B> records<BR>~;
        if ($total_row_count > $max_rows_returned) {
            if ($hits_displayed == 2) {
                print qq~<B>Last two</B> records shown below<BR>~;
            }
            elsif ($hits_displayed == 1) {
                print qq~<B>Last</B> record shown below<BR>~;
            }
            else {
                print qq~<B>$start_hit</B> - <B>$end_hit</B> shown below<BR>~;
            }
        }    #end if
    }    #end if ... > 1
    else {print qq~<P>Total Found: <B>1</B> record\n~;}

    print "<br><center>";

    if ($oib == 87955947581) {    # LEDO is the special case 87955947581
        $ledo_URL =~ s/$main_path//;
        print
qq~<a href="csv_to_excel.cgi?file=$ledo_URL"> Izvoz ovih podataka u XLSX datoteku </a> (za Microsoft Excel) <br><br>~;
    }
    else {

        $extended_URL =~ s/$main_path//;

        print
qq~<br> <br> <a href="$export_URL"> Izvoz ovih podataka u CSV datoteku</a> (za strojnu obradu)<br>  ~;

        print
qq~<a href="csv_to_excel.cgi?file=$extended_URL"> Izvoz ovih podataka u XLSX datoteku</a> (za Microsoft Excel) <br> 
( Podaci u ovom izvještaju dostupni su ukoliko je preuzeta verzija aplikacije 4.28 ili viša)<br><br>~;
    }

# dprelec, 2014-02-27: for testing
#print qq~<br><a href="csv_to_html.cgi?file=$extended_URL">Izvoz ovih podataka u HTML obliku</a><br>~;

    print "<br> $terminal_shop <br> ";

    print
qq~ <input onclick="myForm.action.value='ispis';this.form.submit();" value="Ispis" type="button"> <br>~;

    next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"company_id\" VALUE=\"$company_id\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"company_oib\" VALUE=\"$company_oib\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_oib\" VALUE=\"$search_oib\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"terminal_shop\" VALUE=\"$terminal_shop\">\n";

    $old_jir = 0;
    $old_zki = 0;
    for my $r (@results) {
        my (
            $key,                           $dbuser,
            $when_added,                    $BILL_brRacuna,
            $BILL_zki,                      $BILL_jir,
            $BILL_oib,                      $BILL_uSustavuPDV,
            $BILL_datum,                    $BILL_vrijeme,
            $BILL_miid,                     $BILL_tiid,
            $BILL_oibOper,                  $BILL_imeOper,
            $BILL_ITEMS_COMPLEX,            $BILL_total,
            $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
            $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
            $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
            $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
            $BILL_Company_COMPLEX,          $BILL_Shop_name,
            $BILL_Annex_COMPLEX
        ) = split(/\|/, $r);

        $BILL_oib =~ s/HR//g;

        $r1_r2 = 0;
        if ($BILL_R1_R2_COMPLEX eq "") {$BILL_R1_R2_COMPLEX = "0;"}
        if ($BILL_R1_R2_COMPLEX ne "0;") {
            (
                $r1_r2, $tvrtka_klijenta, $adresa_klijenta,
                $postanski_broj_klijenta, $grad_klijenta, $oib_klijenta
            ) = split(/\;/, $BILL_R1_R2_COMPLEX);
        }

        $rendering_version = 1;
        my @x = split(/\;/, $BILL_Annex_COMPLEX);
        $n_x = @x;
        if ($n_x > 10) {$rendering_version = 2;}
        if ($BILL_Annex_COMPLEX =~ /L_VERSION_3/) {$rendering_version = 3;}

        if ($oib eq $BILL_oib) {
            if (($old_jir ne $BILL_jir) || ("N/A" eq $BILL_jir)) {
                print "<br><br><center><hr>";
                if ($rendering_version == 3) {
                    if ($r1_r2 > 0) {
                        render_bill_version3b($r);
                    }
                    else {
                        render_bill_version3($r);
                    }
                }
                elsif ($rendering_version == 2) {
                    render_bill_version2($r);
                }
                elsif ($rendering_version == 1) {
                    render_bill_version1($r);
                }
            }
            $old_zki = $BILL_zki;
            $old_jir = $BILL_jir;
        }
    }   

    print "<br><br></center>";
    $which_search = "ispis";

    next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_field\" VALUE=\"$search_field\">\n";
    print "<p>";
   
    html_footer();
}   


sub NAbill_with_jir {
    my $jir_complex = shift;
    my $has_jir     = 0;
    if (($jir_complex =~ /NA/i) && ($jir_complex =~ /\d+/)) {
        $has_jir = 1;
    }
    return $has_jir;
}

############################################ print_ledo_billing

sub print_ledo_billing {

    my $bill_record = $_[0];

    (
        $k,                             $dbuser,
        $when_added,                    $BILL_brRacuna,
        $BILL_zki,                      $BILL_jir,
        $BILL_oib,                      $BILL_uSustavuPDV,
        $BILL_datum,                    $BILL_vrijeme,
        $BILL_miid,                     $BILL_tiid,
        $BILL_oibOper,                  $BILL_imeOper,
        $BILL_ITEMS_COMPLEX,            $BILL_total,
        $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
        $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
        $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
        $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
        $BILL_Company_COMPLEX,          $BILL_Shop_name,
        $BILL_Annex_COMPLEX
    ) = split(/\|/, $bill_record);

    my @xls_naziv_artikla = ();
    my @xls_kolicina      = ();
    my @xls_jed_cjena     = ();
    my @xls_iznos         = ();

    $BILL_Shop_name =~ s/\;//g;

    if ($BILL_R1_R2_COMPLEX eq "") {$BILL_R1_R2_COMPLEX = "0;"}
    $tvrtka_klijenta = "";
    $oib_klijenta    = "";
    if ($BILL_R1_R2_COMPLEX ne "0;") {
        (
            $r1_r2, $tvrtka_klijenta, $adresa_klijenta,
            $postanski_broj_klijenta, $grad_klijenta, $oib_klijenta
        ) = split(/\;/, $BILL_R1_R2_COMPLEX);
    }

    my $paymentModality = "";
    if    ($BILL_paymentModalities eq "G") {$paymentModality = "Novčanice";}
    elsif ($BILL_paymentModalities eq "K") {$paymentModality = "Kartice";}
    elsif ($BILL_paymentModalities eq "T") {$paymentModality = "Transakcijski račun";}
    elsif ($BILL_paymentModalities eq "C") {$paymentModality = "Ček";}
    elsif ($BILL_paymentModalities eq "O") {$paymentModality = "Ostalo";}

    # LEDO BILL HEADER
    $ledo_record_header = $BILL_datum . ";";
    $ledo_record_header .= $BILL_vrijeme . ";";
    $ledo_record_header .= $when_added . ";";
    $ledo_record_header .= $BILL_imeOper . ";";
    $ledo_record_header .= $BILL_oibOper . ";";
    $ledo_record_header .= $BILL_miid . ";";
    $ledo_record_header .= $BILL_Shop_name . ";";
    $ledo_record_header .= $BILL_tiid . ";";
    $ledo_record_header .= $BILL_brRacuna . ";";
    $ledo_record_header .= $paymentModality . ";";

    $LEDO_footer = $BILL_zki . ";";
    $LEDO_footer .= $BILL_jir . ";";

# extract ITEMS_COMPLEX [Artikl    	   Količina 	   cjena 	   Iznos (kn)]  listing
    my @a = ();
    ($n_items, @a) = split(/\;/, $BILL_ITEMS_COMPLEX);
    $offset = 0;
    for (my $i = 0 ; $i < $n_items ; $i++) {
        $xls_naziv_artikla[$i] = $a[$offset];
        $xls_kolicina[$i]      = $a[$offset + 1];
        $xls_jed_cjena[$i]     = $a[$offset + 2];
        $xls_iznos[$i]         = $a[$offset + 3];
        $offset += 4;
    }

# assembling and printing all records of LEDO report
# osnovica_kn = (jedinična_cjena_kn - popust_kn - iznos_povratne_naknade_kn) / (1.0 + 0.01*(PDV + PNP + Ostali1 + Ostali2 + Ostali3 ) # general case
# osnovica_kn = jedinična_cjena_kn / (1.0 + 0.01*PDV  ) # LEDO case
# iznos_pdv_kn = osnovica_kn * (stopa_pdv * 0.01) # LEDO case

    # Artikl šifra	Artikl opis			Osnovica za PDV	         	ZKI	JIR
    @altro = ();
    for ($i = 0 ; $i < $n_items ; $i++) {

        $naziv_key = @xls_naziv_artikla[$i];
        $naziv_key =~ s/\s//g;    # trim initial blanks
        $naziv_key =~ s/\W//g;
        $naziv_key = lc($naziv_key);

        $ledo_sifra = $lookup_sifra{$naziv_key};
        $sifra      = "$ledo_sifra";
        if ($sifra eq "") {$sifra = "n/a";}
        ;                         #Kornet Strac.-Šum.voće

        $cjenik_record = $cjenik_hash{$sifra};
        (
            $cjenik_Grupa, $cjenik_Sifra,    $cjenik_Naziv, $cjenik_JedMjere,
            $cjenik_cjena, $cjenik_StopaPDV, @altro
        ) = split(/\;/, $cjenik_record);

        $ledo_record = $ledo_record_header;
        $ledo_record .= "$sifra\;"
          ;    # "$cjenik_Sifra\;"; Artikl šifra ### price_listing parsing 1

        $naziv_artikla = @xls_naziv_artikla[$i];
        $naziv_artikla =~ s/^\s+//;    # trim initial blanks
        $ledo_record .= "$naziv_artikla\;";       # old method
        $ledo_record .= "@xls_kolicina[$i]\;";    # Količina
        $ledo_record .= "@xls_iznos[$i]\;";       # Iznos

        $osnovica_kn =
          @xls_iznos[$i] / (1.0 + 0.25);    # in LEDO case, pdv 25 % HARDCODED
        $osnovica_kn = sprintf("%.2f", $osnovica_kn);
        $ledo_record .= "$osnovica_kn\;";    # Osnovica za PDV

        $pdv_kn =
          @xls_iznos[$i] -
          $osnovica_kn;    ## price_listing parsing 2,  LEDO_ Iznos PDV-a kn
        $pdv_kn = sprintf("%.2f", $pdv_kn);
        $ledo_record .= "$pdv_kn\;";

        $ledo_record .= $LEDO_footer;

        print LEDO "$ledo_record\n";

    }

}

################# end of print LEDO record

############### render_bill  Lversion2.0 ################
sub render_bill_version2 {
    my $bill_record = $_[0];

    my (
        $key,                           $dbuser,
        $when_added,                    $BILL_brRacuna,
        $BILL_zki,                      $BILL_jir,
        $BILL_oib,                      $BILL_uSustavuPDV,
        $BILL_datum,                    $BILL_vrijeme,
        $BILL_miid,                     $BILL_tiid,
        $BILL_oibOper,                  $BILL_imeOper,
        $BILL_ITEMS_COMPLEX,            $BILL_total,
        $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
        $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
        $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
        $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
        $BILL_Company_COMPLEX,          $BILL_Shop_name,
        $BILL_Annex_COMPLEX
    ) = split(/\|/, $bill_record);

    my $paymentModality = "";
    if    ($BILL_paymentModalities eq "G") {$paymentModality = "Novčanice";}
    elsif ($BILL_paymentModalities eq "K") {$paymentModality = "Kartice";}
    elsif ($BILL_paymentModalities eq "T") {$paymentModality = "Transakcijski račun";}
    elsif ($BILL_paymentModalities eq "C") {$paymentModality = "Ček";}
    elsif ($BILL_paymentModalities eq "O") {$paymentModality = "Ostalo";}

    $r1_r2 = "0";

    @a = ();
    if ($BILL_R1_R2_COMPLEX eq "") {$BILL_R1_R2_COMPLEX = "0;"}
    if ($BILL_R1_R2_COMPLEX ne "0;") {
        (
            $r1_r2, $tvrtka_klijenta, $adresa_klijenta,
            $postanski_broj_klijenta, $grad_klijenta, $oib_klijenta
        ) = split(/\;/, $BILL_R1_R2_COMPLEX);
    }

    if ($r1_r2 > 0) {$r1_r2 = "R" . $r1_r2}
    $r1_r2 =~ s/r/R/g
      ; #flexibility -- it works for 1, R1, r1 (and 2, R2, r2) - all values are interpreted equaly

    $r1_r2_annex = qq~
<tr>
         <td colspan=2 ><hr></td>
</tr>
<tr>
         <td colspan=2 align="center"><b>Račun $r1_r2 </b></td>

         </tr>
         <tr>
         <td>Klijent: $tvrtka_klijenta</td>
         <td></td>
         </tr>

         <tr>
         <td>Adresa: $adresa_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td> Mjesto: $postanski_broj_klijenta $grad_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td>OIB: $oib_klijenta</td>
         <td></td>
       

<tr>
         <td colspan=2 ><hr></td>
</tr>
~;

    if ($r1_r2 eq "0") {$r1_r2_annex = "";}

    (
        $company_Ime,              $company_Adresa_Ulica,
        $company_Adresa_KucniBroj, $company_Adresa_KucniBrojDodatak,
        $company_Adresa_BrojPoste, $company_Adresa_Opcina,
        $shop_descriptive_name
    ) = split(/\;/, $BILL_Company_COMPLEX);

    $pj_annex = "";
    if ($shop_descriptive_name ne "") {
        $pj_annex = "PJ: $shop_descriptive_name";
    }

    $BILL_Shop_name =~ s/\;//g;
    if ($BILL_Shop_name ne "") {$pj_annex = "PJ: $BILL_Shop_name";}

    $pj_annex =~ s/\s+/ /g;
    if ($pj_annex eq "PJ: ") {$pj_annex = "";}

    print <<HTML;
$company_Ime<br>
$company_Adresa_Ulica $company_Adresa_KucniBroj $company_Adresa_KucniBrojDodatak, $company_Adresa_BrojPoste $company_Adresa_Opcina<br>
OIB:$BILL_oib<br>
$pj_annex  <br>
<br>
<table border="0" cellspacing="0"  width="400">
        <tbody>
$r1_r2_annex
<tr>
         <td>Datum: $BILL_datum</td>
         <td align="right">Vrijeme: $BILL_vrijeme</td>
         </tr>

        <tr>
         <td colspan=2 >Blagajnik: $BILL_imeOper, 
         OIB: $BILL_oibOper</td>
         </tr>

        <tr>
         <td>Oznaka prodajnog mjesta: $BILL_miid</td>
         <td></td>
         </tr>

        <tr>
         <td>Oznaka naplatnog uređaja: $BILL_tiid</td>
         <td></td>
         </tr>
        <tr>
         <td colspan=2 align="center"><b><br>RN: $BILL_brRacuna-$BILL_miid-$BILL_tiid </b></td>
         </tr>
       	</tbody>
</table>

<br>

    <table border="0" cellspacing="0" width="450">
    <tbody>
   <tr>
         <td colspan=6>ZKI: $BILL_zki</td>
   </tr> 
   <tr>
         <td colspan=6>JIR: $BILL_jir </td>
   </tr> 
   <tr>
         <td colspan=6><hr> </td>
   </tr> 
        <tr>
         <td colspan=5>Naziv&nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;Porezna stopa&nbsp;</td>
         </tr>

        <tr>
         <td>Šifra&nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Jed.cij.</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Količina</td>
         <td align="right">&nbsp;&nbsp;&nbsp;J.M.</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Popust</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Iznos&nbsp;(kn)</td>
         </tr>

HTML

    ($n_items,   @a) = split(/\;/, $BILL_ITEMS_COMPLEX);
    ($n_items_b, @b) = split(/\;/, $BILL_Annex_COMPLEX);

    $offset_a = 0;
    $offset_b = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {

        $artikl   = @a[$offset_a];       # naziv usluge ili proizvoda
        $quantity = @a[$offset_a + 1];
        $quantity =~ s/\.000//g;
        $cjena = @a[$offset_a + 2];
        $iznos = @a[$offset_a + 3];

        $sifra  = @b[$offset_b];         # Šifra usluge ili proizvoda
        $jm     = @b[$offset_b + 1];
        $popust = @b[$offset_b + 2];
        if ($popust != 0) {
            $popust = "$popust %";
        }
        else {
            $popust = "";
        }

        $pdv_integer = sprintf("%d", $pdv);

        print qq|
        <tr>
         <td colspan=5>$artikl&nbsp;&nbsp;</td>
         <td align="right">&nbsp;(PDV&nbsp;$pdv_integer)&nbsp;</td>
         </tr>

        <tr>
         <td>$sifra &nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;&nbsp;&nbsp;$cjena&nbsp;kn </td>
         <td align="right">&nbsp;&nbsp;&nbsp;$quantity</td>
         <td align="right">&nbsp;&nbsp;&nbsp;$jm </td>
         <td align="right">&nbsp;&nbsp;&nbsp;$popust</td>
         <td align="right">&nbsp;&nbsp;&nbsp;$iznos&nbsp;kn </td>
         </tr>
    |;

        $offset_a += 4;
        $offset_b += 14;
    }

    print <<HTML;
   <tr>
         <td colspan=6><hr> </td>
   </tr>    	
   <tr>
         <td>UKUPNO KN ($paymentModality):</td>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td align="right"><b>$BILL_total</b> kn</td>
   </tr>  
   <tr>
         <td colspan=6><hr> </td>
   </tr> 
HTML

    $porezi_ispis = "";
    @a            = ();
    ($n_items, @a) = split(/\;/, $BILL_pdv_COMPLEX);
    $offset = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $porezi_ispis .= qq|
      <tr>
         <td>PDV (@a[$offset] %)</td>
         <td align="right">@a[$offset+1] kn</td>
         <td></td>
         <td></td>
         <td align="right">@a[$offset+2] kn</td>
      </tr>|;

        $offset += 3;
    }

    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_pnp_COMPLEX);
    $offset = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $porezi_ispis .= qq|
      <tr>
         <td>PNP (@a[$offset] %) </td>
         <td align="right">@a[$offset+1] </td>
         <td></td>
         <td></td>
         <td align="right">@a[$offset+2] </td>
      </tr>|;

        $offset += 3;
    }

########## ostali_porezi_COMPLEX
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_ostali_porezi_COMPLEX);
    $offset = 0;

    for ($i = 1 ; $i <= $n_items ; $i++) {
        $porezi_ispis .= qq|
      <tr>
         <td> @a[$offset] (@a[$offset +1] %) </td>
         <td align="right"> @a[$offset +2] kn</td>
         <td>  </td>
         <td>  </td>
         <td align="right"> @a[$offset+3] kn</td>
      </tr>|;

        $offset += 4;
    }

########## end of ostali_porezi_COMPLEX

    if ($porezi_ispis ne "") {
        print <<HTML;
   <tr>
         <td colspan=6 align="center"> POREZI </td>
   </tr> 
   <tr>
         <td>Stopa</td>
         <td align="right">Osnovica</td>
         <td></td>
         <td></td>
         <td align="right">Porez</td>
   </tr> 
$porezi_ispis
HTML
    }

##########  povratne_naknade_COMPLEX
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_povratne_naknade_COMPLEX);

    if ($n_items) {
        print <<HTML;
  
   <tr>
         <td colspan=6><hr> </td>
   </tr> 
   <tr>
         <td colspan=6 align="center"> POVRATNE NAKNADE </td>
   </tr> 
   <tr>
         <td>Naziv</td>
         <td align="right">Količina</td>
         <td></td>
         <td></td>
         <td align="right">Iznos</td>
   </tr> 

HTML
######

        $offset = 0;

        for ($i = 1 ; $i <= $n_items ; $i++) {
            print qq|
      <tr>
         <td> @a[$offset]  </td>
         <td align="right"> @a[$offset +1]  </td>
         <td>  </td>
         <td>  </td>
         <td align="right"> @a[$offset+2] kn</td>
      </tr>|;

            $offset += 3;
        }
    }
########## end of povratne_naknade_COMPLEX

    $tax_exemption = qq~
     <tr>
         <td>Oslobođeno PDV-a (kn):</td>
         <td align="right"> $BILL_iznos_oslobodjen_pdv</td>
         <td></td>
         <td align="right"> </td>
      </tr>
~;

    if ($BILL_iznos_oslobodjen_pdv == 0) {$tax_exemption = ""}

    print <<HTML;

   $tax_exemption
HTML

    print <<HTML;
   <tr>
         <td colspan=6><hr> </td>
   </tr>    	
   <tr>
         <td colspan=6 align="center">$BILL_ReceiptMessage </td>
   </tr>    
   <tr>
         <td colspan=6><hr> </td>
   </tr> 
   <tr>
         <td colspan=6  align="center">      </td>
   </tr> 

   <tr>
         <td colspan=6><hr> </td>
   </tr> 

</tbody></table>

HTML

    # K O P I J A
}
############### end of render_bill Lversion2.0 ################

############################################ print_extended_billing pivot table (EXTENDED pivot table was inspired by LEDO specification)
# Izvoz   podataka u PROŠIRENOJ pivot csv datoteci
# Podaci u ovom izvještaju dostupni su za račune izdane od 01.08.2013. ukoliko je preuzeta verzija aplikacije 4.28 ili viša

sub print_extended_billing {
    my $bill_record = shift;

    my (
        $k,                             $dbuser,
        $when_added,                    $BILL_brRacuna,
        $BILL_zki,                      $BILL_jir,
        $BILL_oib,                      $BILL_uSustavuPDV,
        $BILL_datum,                    $BILL_vrijeme,
        $BILL_miid,                     $BILL_tiid,
        $BILL_oibOper,                  $BILL_imeOper,
        $BILL_ITEMS_COMPLEX,            $BILL_total,
        $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
        $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
        $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
        $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
        $BILL_Company_COMPLEX,          $BILL_Shop_name,
        $BILL_Annex_COMPLEX
    ) = split(/\|/, $bill_record);

    $rendering_version = 1;
    my @x = split(/\;/, $BILL_Annex_COMPLEX);
    $n_x = @x;

    if ($n_x > 10) {
        $rendering_version = 2;
    }

    if ($BILL_Annex_COMPLEX =~ /L_VERSION_3/) {
        $rendering_version = 3;
    }

    #  4 core components for each item
    my @xls_naziv_artikla = ();
    my @xls_kolicina      = ();
    my @xls_jed_cjena     = ();
    my @xls_iznos         = ();

    # annex - 14 additional components for rendering_version 2 and 3
    my @xls_sifra_artikla    = ();
    my @xls_jedinica_artikla = ();
    my @xls_popust           = ();
    my @xls_tax_free_flag    = ();
    my @xls_pdv_value        = ();
    my @xls_pnp_value        = ();
    my @xls_tax1_tag         = ();
    my @xls_tax1_value       = ();
    my @xls_tax2_tag         = ();
    my @xls_tax2_value       = ();
    my @xls_tax3_tag         = ();
    my @xls_tax3_value       = ();
    my @xls_povrat_tag       = ();
    my @xls_povrat_value     = ();

    $BILL_Shop_name =~ s/\;//g;

    if ($BILL_R1_R2_COMPLEX eq "") {
        $BILL_R1_R2_COMPLEX = "0;";
    }

    $tvrtka_klijenta = "";
    $oib_klijenta    = "";

    if ($BILL_R1_R2_COMPLEX ne "0;") {
        (
            $r1_r2, $tvrtka_klijenta, $adresa_klijenta,
            $postanski_broj_klijenta, $grad_klijenta, $oib_klijenta
        ) = split(/\;/, $BILL_R1_R2_COMPLEX);
    }

    my $paymentModality = "";
    if    ($BILL_paymentModalities eq "G") {$paymentModality = "Novčanice";}
    elsif ($BILL_paymentModalities eq "K") {$paymentModality = "Kartice";}
    elsif ($BILL_paymentModalities eq "T") {$paymentModality = "Transakcijski račun";}
    elsif ($BILL_paymentModalities eq "C") {$paymentModality = "Ček";}
    elsif ($BILL_paymentModalities eq "O") {$paymentModality = "Ostalo";}

    # ext BILL HEADER
    $ext_record_header = $BILL_datum . ";";
    $ext_record_header .= $BILL_vrijeme . ";";
    $ext_record_header .= $when_added . ";";
    $ext_record_header .= $BILL_imeOper . ";";
    $ext_record_header .= $BILL_oibOper . ";";
    $ext_record_header .= $BILL_miid . ";";
    $ext_record_header .= $BILL_Shop_name . ";";
    $ext_record_header .= $BILL_tiid . ";";
    $ext_record_header .= $BILL_brRacuna . ";";
    $ext_record_header .= $paymentModality . ";";

    $ext_footer = $BILL_zki . ";";
    $ext_footer .= $BILL_jir . ";";

# extract ITEMS_COMPLEX [Artikl    	   Količina 	   cjena 	   Iznos (kn)]  listing
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_ITEMS_COMPLEX);

    $offset = 0;
    for (my $i = 0 ; $i < $n_items ; $i++) {
        $xls_naziv_artikla[$i] = $a[$offset];
        $xls_kolicina[$i]      = $a[$offset + 1];
        $xls_jed_cjena[$i]     = $a[$offset + 2];
        $xls_iznos[$i]         = $a[$offset + 3];

        $offset += 4;
    }

    for (my $i = 0 ; $i < 20 ; $i++) {
        $xls_sifra_artikla[$i]    = "n/a";
        $xls_jedinica_artikla[$i] = "n/a";
        $xls_popust[$i]           = "n/a";
        $xls_tax_free_flag[$i]    = "n/a";
        $xls_pdv_value[$i]        = "n/a";
        $xls_pnp_value[$i]        = "n/a";
        $xls_tax1_tag[$i]         = "n/a";
        $xls_tax1_value[$i]       = "n/a";
        $xls_tax2_tag[$i]         = "n/a";
        $xls_tax2_value[$i]       = "n/a";
        $xls_tax3_tag[$i]         = "n/a";
        $xls_tax3_value[$i]       = "n/a";
        $xls_povrat_tag[$i]       = "n/a";
        $xls_povrat_value[$i]     = "n/a";
        $xls_prolazna_stavka[$i]  = "n/a";
        $xls_iznos_osnovice[$i]   = "n/a";
    }

# parsing BILL_Annex_COMPLEX  [ARTICLE_cyphr, ARTICLE_unit, ARTICLE_discount; ARTICLE_tax_COMPLEX]  listing
# 11;kom;14.32;   0;25.00;0.00;N/A;0.00;N/A;0.00;N/A;0.00;N/A;0.00;

# PDV Free flag (0, 1) - 0
# Postotak PDV-a       - 25.00
# Postotak PNP-a       - 0.00
# Label -Ime ostalog poreza 1 ("N/A", znači da nema tog poreza (vrijedi za sve ostale)
# Postotak ostalog p. 1
# Ime ostalog poreza 2 ("N/A", znači da nema tog poreza (vrijedi za sve ostale)
# Postotak ostalog p. 2
# Ime ostalog poreza 3 ("N/A", znači da nema tog poreza (vrijedi za sve ostale)
# Postotak ostalog p. 3
# Naziv povratne naknade
# Iznos povratne naknade

    $rendering_version = 1;
    my @x = split(/\;/, $BILL_Annex_COMPLEX);
    $n_x = @x;

    if ($n_x > 10) {
        $rendering_version = 2;
    }

    if ($BILL_Annex_COMPLEX =~ /L_VERSION_3/) {
        $rendering_version = 3;
    }

    if ($rendering_version == 2) {
        @x = ();
        ($n_annex, @x) = split(/\;/, $BILL_Annex_COMPLEX);
        $offset = 0;
        if ($n_annex > 0) {
            for (my $i = 0 ; $i < $n_annex ; $i++) {
                $xls_sifra_artikla[$i]    = $x[$offset];
                $xls_jedinica_artikla[$i] = $x[$offset + 1];
                $xls_popust[$i]           = $x[$offset + 2];
                $xls_tax_free_flag[$i]    = $x[$offset + 3];
                $xls_pdv_value[$i]        = $x[$offset + 4];
                $xls_pnp_value[$i]        = $x[$offset + 5];
                $xls_tax1_tag[$i]         = $x[$offset + 6];
                $xls_tax1_value[$i]       = $x[$offset + 7];
                $xls_tax2_tag[$i]         = $x[$offset + 8];
                $xls_tax2_value[$i]       = $x[$offset + 9];
                $xls_tax3_tag[$i]         = $x[$offset + 10];
                $xls_tax3_value[$i]       = $x[$offset + 11];
                $xls_povrat_tag[$i]       = $x[$offset + 12];
                $xls_povrat_value[$i]     = $x[$offset + 13];

                $offset += 14;
            }
        }

    }    # end $rendering_version == 2

    if ($rendering_version == 3) {
        @x = ();
        ($n_annex, @x) = split(/\;/, $BILL_Annex_COMPLEX);
        $offset = 0;
        if ($n_annex > 0) {
            for (my $i = 0 ; $i < $n_annex ; $i++) {
                $xls_sifra_artikla[$i]    = $x[$offset];
                $xls_jedinica_artikla[$i] = $x[$offset + 1];
                $xls_popust[$i]           = $x[$offset + 2];
                $xls_tax_free_flag[$i]    = $x[$offset + 3];
                $xls_pdv_value[$i]        = $x[$offset + 4];
                $xls_pnp_value[$i]        = $x[$offset + 5];
                $xls_tax1_tag[$i]         = $x[$offset + 6];
                $xls_tax1_value[$i]       = $x[$offset + 7];
                $xls_tax2_tag[$i]         = $x[$offset + 8];
                $xls_tax2_value[$i]       = $x[$offset + 9];
                $xls_tax3_tag[$i]         = $x[$offset + 10];
                $xls_tax3_value[$i]       = $x[$offset + 11];
                $xls_povrat_tag[$i]       = $x[$offset + 12];
                $xls_povrat_value[$i]     = $x[$offset + 13];
                $xls_prolazna_stavka[$i]  = $x[$offset + 14];
                $xls_iznos_osnovice[$i]   = $x[$offset + 15];

                $offset += 16;
            }
        }
    }    # end $rendering_version == 3

# assembling and printing all records of ext report
# osnovica_kn  = (jedinična_cjena_kn - popust_kn - iznos_povratne_naknade_kn) / (1.0 + 0.01*(PDV + PNP + Ostali1 + Ostali2 + Ostali3 ) # general case
# iznos_pdv_kn = osnovica_kn * (stopa_pdv * 0.01)        # ext case

    # Artikl šifra	Artikl opis			Osnovica za PDV	         	ZKI	JIR

    my $ext_record = '';
    for (my $i = 0 ; $i < $n_items ; $i++) {
        $ext_record = $ext_record_header;
        $ext_record .= "$xls_sifra_artikla[$i]\;";    # Artikl šifra
        $ext_record .= "$xls_naziv_artikla[$i]\;";    # Artikl opis
        $ext_record .= "$xls_kolicina[$i]\;";         # Količina
        $ext_record .= "$xls_iznos[$i]\;";            # Iznos

        $popust_kn = $xls_popust[$i];
        $pdv       = $xls_pdv_value[$i];
        $pnp       = $xls_pnp_value[$i];
        $tax1      = $xls_tax1_value[$i];
        $tax2      = $xls_tax2_value[$i];
        $tax3      = $xls_tax3_value[$i];

        my $iznos_pdv_kn  = 0;
        my $iznos_pdv_str = '';

=dumper
use Data::Dumper;
print STDERR Dumper(
    {
        osnovica_kn => $osnovica_kn, 
        pdv => $pdv, 
        xls_kolicina => $xls_kolicina[$i], 
        rendering_version => $rendering_version, 
        xls_iznos_osnovice => $xls_iznos_osnovice[$i],
    }
);
=cut

        if ($rendering_version == 3) {
            if ($xls_iznos_osnovice[$i] == 0) {
                $osnovica_kn =
                  ($xls_jed_cjena[$i] - $popust_kn - $xls_povrat_value[$i])
                  / (1.0 + 0.01 * ($pdv + $pnp + $tax1 + $tax2 + $tax3));

                # dprelec, 2014-02-26:
                # - pdv izracun
                # - dodaj na kraj CIJELOG rekorda!
                # - izracun treba uzimati u obzir i prodanu kolicinu
                $iznos_pdv_kn = abs($osnovica_kn * ($pdv * 0.01) * $xls_kolicina[$i]);
                $iznos_pdv_str = sprintf("%.2f", $iznos_pdv_kn);

                #print STDERR "iznos_pdv_kn $iznos_pdv_kn\n";

                $ext_record .= "$osnovica_kn\;"; # Osnovica koja se oporezuje kn
            }
            else {
                # dprelec, 2014-03-21:
                # - pdv izracun mora biti i ovdje
                $iznos_pdv_kn = abs($xls_iznos_osnovice[$i] * ($pdv * 0.01) * $xls_kolicina[$i]);
                $iznos_pdv_str = sprintf("%.2f", $iznos_pdv_kn);

                #print STDERR "iznos_pdv_kn $iznos_pdv_kn\n";

                $ext_record .= "$xls_iznos_osnovice[$i]\;";
            }

            $ext_record .= "$pdv\;";
        }
        # dprelec, 2014-03-24: John kaze ova verzija se vise ne koristi
        elsif ($rendering_version == 2) {
            $osnovica_kn =
              ($xls_jed_cjena[$i] - $popust_kn - $xls_povrat_value[$i]) /
              (1.0 + 0.01 * ($pdv + $pnp + $tax1 + $tax2 + $tax3));
            $ext_record .= "$osnovica_kn\;";    # Osnovica koja se oporezuje kn
            $ext_record .= "$pdv\;";
        }
        elsif ($rendering_version == 1) {
            $ext_record .= "n/a\;";             # Osnovica koja se oporezuje kn
            $ext_record .= "n/a\;";             # porez kn
        }

        # dprelec, 2014-03-05:
        # iznos PDV-a ide na kraj cijelog rekorda
        if ($iznos_pdv_str ne '') {
            $ext_record .= "$ext_footer$iznos_pdv_str";
        }
        else {
            $ext_record .= $ext_footer;
        }

        print EXT "$ext_record\n";
    }
}

################# end of extended billing

############### render_bill    L_VERSION_3.00 BIS ################
sub render_bill_version3b {
    my $bill_record = $_[0];

    my (
        $key,                           $dbuser,
        $when_added,                    $BILL_brRacuna,
        $BILL_zki,                      $BILL_jir,
        $BILL_oib,                      $BILL_uSustavuPDV,
        $BILL_datum,                    $BILL_vrijeme,
        $BILL_miid,                     $BILL_tiid,
        $BILL_oibOper,                  $BILL_imeOper,
        $BILL_ITEMS_COMPLEX,            $BILL_total,
        $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
        $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
        $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
        $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
        $BILL_Company_COMPLEX,          $BILL_Shop_name,
        $BILL_Annex_COMPLEX
    ) = split(/\|/, $bill_record);

    my @pristojba_jc = ();
    my @pristojba_k  = ();
    my @pristojba_i  = ();

    # 4 core components for each item
    my @xls_naziv_artikla = ();
    my @xls_kolicina      = ();
    my @xls_jed_cjena     = ();
    my @xls_iznos         = ();

    # annex - 14 additional components for rendering_version 2
    my @xls_sifra_artikla    = ();
    my @xls_jedinica_artikla = ();
    my @xls_popust           = ();
    my @xls_tax_free_flag    = ();
    my @xls_pdv_value        = ();
    my @xls_pnp_value        = ();
    my @xls_tax1_tag         = ();
    my @xls_tax1_value       = ();
    my @xls_tax2_tag         = ();
    my @xls_tax2_value       = ();
    my @xls_tax3_tag         = ();
    my @xls_tax3_value       = ();
    my @xls_povrat_tag       = ();
    my @xls_povrat_value     = ();

    # annex - 2 more additional components for rendering_version 3.00
    my @xls_prolazna_stavka =
      ();    # (integer: 0....obični artikl, >0 prolazna stavka)
    my @xls_iznos_osnovice = ();    # potreban je samo kod R1 i R2 računa

    my $suma_pristojbe = 0.0;

# extract ITEMS_COMPLEX [Artikl    	   Količina 	   cjena 	   Iznos (kn)]  listing
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_ITEMS_COMPLEX);
    $offset = 0;
    for ($i = 0 ; $i < $n_items ; $i++) {

        @xls_naziv_artikla[$i] = @a[$offset];
        @xls_kolicina[$i]      = @a[$offset + 1];
        @xls_jed_cjena[$i]     = @a[$offset + 2];
        @xls_iznos[$i]         = @a[$offset + 3];

        $offset += 4;
    }

    @x = ();
    ($n_annex, @x) = split(/\;/, $BILL_Annex_COMPLEX);
    $offset = 0;
    if ($n_annex > 0) {
        for ($i = 0 ; $i < $n_annex ; $i++) {
            $xls_sifra_artikla[$i]    = $x[$offset];
            $xls_jedinica_artikla[$i] = $x[$offset + 1];
            $xls_popust[$i]           = $x[$offset + 2];
            $xls_tax_free_flag[$i]    = $x[$offset + 3];
            $xls_pdv_value[$i]        = $x[$offset + 4];
            $xls_pnp_value[$i]        = $x[$offset + 5];
            $xls_tax1_tag[$i]         = $x[$offset + 6];
            $xls_tax1_value[$i]       = $x[$offset + 7];
            $xls_tax2_tag[$i]         = $x[$offset + 8];
            $xls_tax2_value[$i]       = $x[$offset + 9];
            $xls_tax3_tag[$i]         = $x[$offset + 10];
            $xls_tax3_value[$i]       = $x[$offset + 11];
            $xls_povrat_tag[$i]       = $x[$offset + 12];
            $xls_povrat_value[$i]     = $x[$offset + 13];
            $xls_prolazna_stavka[$i]  = $x[$offset + 14];
            $xls_iznos_osnovice[$i]   = $x[$offset + 15];

            $offset += 16;
        }
    }

    my $paymentModality = "";
    if    ($BILL_paymentModalities eq "G") {$paymentModality = "Novčanice";}
    elsif ($BILL_paymentModalities eq "K") {$paymentModality = "Kartice";}
    elsif ($BILL_paymentModalities eq "T") {$paymentModality = "Transakcijski račun";}
    elsif ($BILL_paymentModalities eq "C") {$paymentModality = "Ček";}
    elsif ($BILL_paymentModalities eq "O") {$paymentModality = "Ostalo";}

    $r1_r2 = "0";

    @a = ();
    if ($BILL_R1_R2_COMPLEX eq "") {$BILL_R1_R2_COMPLEX = "0;"}
    if ($BILL_R1_R2_COMPLEX ne "0;") {
        (
            $r1_r2, $tvrtka_klijenta, $adresa_klijenta,
            $postanski_broj_klijenta, $grad_klijenta, $oib_klijenta
        ) = split(/\;/, $BILL_R1_R2_COMPLEX);
    }

    if ($r1_r2 > 0) {$r1_r2 = "R" . $r1_r2}
    $r1_r2 =~ s/r/R/g
      ; #flexibility -- it works for 1, R1, r1 (and 2, R2, r2) - all values are interpreted equaly

    $r1_r2_annex = qq~
<tr>
         <td colspan=2 ><hr></td>
</tr>
<tr>
         <td colspan=2 align="center"><b>Račun $r1_r2 </b></td>
         </tr>
         <tr>
         <td>Klijent: $tvrtka_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td>Adresa: $adresa_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td> Mjesto: $postanski_broj_klijenta $grad_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td>OIB: $oib_klijenta</td>
         <td></td>
<tr>
         <td colspan=2 ><hr></td>
</tr>
~;

    if ($r1_r2 eq "0") {$r1_r2_annex = "";}

    (
        $company_Ime,              $company_Adresa_Ulica,
        $company_Adresa_KucniBroj, $company_Adresa_KucniBrojDodatak,
        $company_Adresa_BrojPoste, $company_Adresa_Opcina,
        $shop_descriptive_name
    ) = split(/\;/, $BILL_Company_COMPLEX);

    $pj_annex = "";
    if ($shop_descriptive_name ne "") {
        $pj_annex = "PJ: $shop_descriptive_name";
    }

    $BILL_Shop_name =~ s/\;//g;
    if ($BILL_Shop_name ne "") {$pj_annex = "PJ: $BILL_Shop_name";}

    $pj_annex =~ s/\s+/ /g;
    if ($pj_annex eq "PJ: ") {$pj_annex = "";}

    print <<HTML;
$company_Ime<br>
$company_Adresa_Ulica $company_Adresa_KucniBroj $company_Adresa_KucniBrojDodatak, $company_Adresa_BrojPoste $company_Adresa_Opcina<br>
OIB:$BILL_oib<br>
$pj_annex  <br>
<br>
<table border="0" cellspacing="0"  width="400">
        <tbody>
$r1_r2_annex
<tr>
         <td>Datum: $BILL_datum</td>
         <td align="right">Vrijeme: $BILL_vrijeme</td>
         </tr>

        <tr>
         <td colspan=2 >Blagajnik: $BILL_imeOper, 
         OIB: $BILL_oibOper</td>
         </tr>

        <tr>
         <td>Oznaka prodajnog mjesta: $BILL_miid</td>
         <td></td>
         </tr>

        <tr>
         <td>Oznaka naplatnog uređaja: $BILL_tiid</td>
         <td></td>
         </tr>
        <tr>
         <td colspan=2 align="center"><b><br>RN: $BILL_brRacuna-$BILL_miid-$BILL_tiid </b></td>
         </tr>
       	</tbody>
</table>
<br>
    <table border="0" cellspacing="0" width="450">
    <tbody>
   <tr>
         <td colspan=6>ZKI: $BILL_zki</td>
   </tr> 
   <tr>
         <td colspan=6>JIR: $BILL_jir </td>
   </tr> 
   <tr>
         <td colspan=6><hr> </td>
   </tr> 
        <tr>
         <td colspan=5>Naziv&nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;Porezna stopa&nbsp;</td>
         </tr>
        <tr>
         <td>Šifra&nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;&nbsp;Jed.cij.</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Količina</td>
         <td align="right">&nbsp;&nbsp;&nbsp;J.M.</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Popust</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Iznos&nbsp;(kn)</td>
         </tr>
HTML

    @a = ();
    @b = ();
    ($n_items,   @a) = split(/\;/, $BILL_ITEMS_COMPLEX);
    ($n_items_b, @b) = split(/\;/, $BILL_Annex_COMPLEX);

    $offset_a = 0;
    $offset_b = 0;

    $suma_osnovice = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {

        $artikl   = $a[$offset_a];       # naziv usluge ili proizvoda
        $quantity = $a[$offset_a + 1];
        $quantity =~ s/\.000//g;
        $cjena = $a[$offset_a + 2];
        $iznos = $a[$offset_a + 3];

        $sifra  = $xls_sifra_artikla[$i - 1];      # Šifra usluge ili proizvoda
        $jm     = $xls_jedinica_artikla[$i - 1];
        $popust = $xls_popust[$i - 1];             #

        $popust = "$popust %";

        $osnovica = $xls_iznos_osnovice[$i - 1];
        $osnovica = sprintf("%.2f", $osnovica);

        $pdv = $xls_pdv_value[$i - 1];

        if ($artikl =~ /pristojba/i) {
            push @pristojba_jc, $cjena;
            push @pristojba_k,  $quantity;
            push @pristojba_i,  $iznos;
        }

        if ($artikl !~ /pristojba/i) {
            $subtotal = $osnovica * (1.0 - $popust * 0.01) * $quantity;
            $suma_osnovice += $subtotal;
            $suma_osnovice = sprintf("%.2f", $suma_osnovice);
            $subtotal      = sprintf("%.2f", $subtotal);
            $pdv_integer   = sprintf("%d", $pdv);
            print qq|
        <tr>
         <td colspan=5>$artikl&nbsp;&nbsp;</td>
         <td align="right">&nbsp;(PDV&nbsp;$pdv_integer)&nbsp;</td>
        </tr>
        <tr>
         <td>$sifra &nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;&nbsp;&nbsp;$osnovica&nbsp;kn </td>
         <td align="right">&nbsp;&nbsp;&nbsp;$quantity</td>
         <td align="right">&nbsp;&nbsp;&nbsp;$jm </td>
         <td align="right">&nbsp;&nbsp;&nbsp;$popust</td>
         <td align="right"> &nbsp;$subtotal&nbsp;kn </td>
        </tr>
    |;
        }

        $offset_a += 4;
        $offset_b += 16;
    }

    $porezi_ispis = "";
    $x1           = 0;
    $x2           = 0;
    $x3           = 0;
    @a            = ();
    ($n_items, @a) = split(/\;/, $BILL_pdv_COMPLEX);
    $offset = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $ukupno = @a[$offset + 1] + @a[$offset + 2];
        $ukupno = sprintf("%.2f", $ukupno);

        $x1 += @a[$offset + 1];
        $x2 += @a[$offset + 2];
        $x3 += $ukupno;

        $porezi_ispis .= qq|
      <tr>
         <td>PDV (@a[$offset] %)</td>
         <td align="right">@a[$offset+1] kn</td>
         <td></td>
         <td></td>
         <td align="right">@a[$offset+2] kn</td>
         <td align="right"> $ukupno  kn</td>
      </tr>|;

        $offset += 3;
    }

    $tax_exemption = qq~
     <tr>
         <td>Oslobođeno PDV-a </td>
         <td align="right"> $BILL_iznos_oslobodjen_pdv kn</td>
         <td></td>
         <td></td>
         <td align="right"> 0.00 kn</td>
         <td align="right"> $BILL_iznos_oslobodjen_pdv kn</td>
      </tr>
~;

    if ($BILL_iznos_oslobodjen_pdv == 0) {$tax_exemption = ""}

    $porezi_ispis .= $tax_exemption;

    $x1 += $BILL_iznos_oslobodjen_pdv;
    $x3 += $BILL_iznos_oslobodjen_pdv;
    $x1 = sprintf("%.2f", $x1);
    $x2 = sprintf("%.2f", $x2);
    $x3 = sprintf("%.2f", $x3);

    $pdv_ukupno = qq~
     <tr>
         <td>UKUPNO </td>
         <td align="right"> $x1 kn</td>
         <td></td>
         <td></td>
         <td align="right"> $x2 kn</td>
         <td align="right"> $x3 kn</td>
      </tr>
~;

    $total1 = $x3;

    $porezi_ispis .= $pdv_ukupno;

    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_pnp_COMPLEX);
    $offset = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $y1 = sprintf("%.2f", @a[$offset + 1]);
        $y2 = sprintf("%.2f", @a[$offset + 2]);

        $ukupno = @a[$offset + 1] + @a[$offset + 2];
        $porezi_ispis .= qq|
      <tr>
         <td>PNP (@a[$offset] %) </td>
         <td align="right"> $y1 kn </td>
         <td></td>
         <td></td>
         <td align="right"> $y2 kn</td>
         <td align="right">  </td>
      </tr>|;

        $offset += 3;
    }

########## ostali_porezi_COMPLEX
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_ostali_porezi_COMPLEX);
    $offset = 0;

    for ($i = 1 ; $i <= $n_items ; $i++) {
        $ukupno = @a[$offset + 2] + @a[$offset + 3];
        $porezi_ispis .= qq|
      <tr>
         <td> @a[$offset] (@a[$offset +1] %) </td>
         <td align="right"> @a[$offset +2] kn</td>
         <td>  </td>
         <td>  </td>
         <td align="right"> @a[$offset+3] kn</td>
         <td align="right">  </td>
      </tr>|;

        $offset += 4;
    }
    $porezi_ispis .= qq|
   <tr>
         <td colspan=6><hr> </td>
   </tr> 
   |;

########## end of ostali_porezi_COMPLEX

    print <<HTML;
   <tr>
         <td colspan=6><hr> </td>
   </tr>    	
   <tr>
         <td>UKUPNO KN (Osnovica):</td>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td align="right"><b>$suma_osnovice</b> kn</td>
   </tr>  
   <tr>
         <td colspan=6><hr> </td>
   </tr> 
HTML

    print <<HTML;
   <tr>
         <td colspan=6 align="center"> POREZI  </td>
   </tr> 
   <tr>
         <td>Porez</td>
         <td align="right">Osnovica</td> 
         <td></td>
         <td></td>
         <td align="right">Iznos</td>
         <td align="right">Ukupno</td>
   </tr> 
$porezi_ispis
HTML

##########  povratne_naknade_COMPLEX
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_povratne_naknade_COMPLEX);

    if (($n_items > 0) || ($BILL_ITEMS_COMPLEX =~ /pristojba/)) {

        print <<HTML;
   
   <tr>
         <td colspan=6 align="center"> PROLAZNE STAVKE </td>
   </tr> 
   <tr>
         <td>Naziv</td>
         <td align="right">Jed. cjena</td>
         <td align="right">Količina</td>
         <td></td>
         <td></td>
         <td align="right">Iznos</td>
   </tr> 

HTML
######

        $offset = 0;
        $ukupno = 0;
        for ($i = 1 ; $i <= $n_items ; $i++) {

            $jc = @a[$offset + 2] / @a[$offset + 1];
            $jc = sprintf("%.2f", $jc);
            $ukupno += @a[$offset + 2];

            print qq|
      <tr>
         <td> Povratna naknada </td>
         <td align="right"> $jc  </td>
         <td align="right"> @a[$offset +1]  </td>
         <td>  </td>
         <td>  </td>
         <td align="right"> @a[$offset+2] kn</td>

      </tr>|;

            $offset += 3;
        }
    }
########## end of povratne_naknade_COMPLEX

##########  PROLAZNE STAVKE
    $n_pristojbi = @pristojba_k;
    if ($n_pristojbi > 0) {
        for ($p = 0 ; $p < $n_pristojbi ; $p++) {

            $subtotal = $pristojba_k[$p] * $pristojba_jc[$p];
            $subtotal = sprintf("%.2f", $subtotal);
            print qq|
      <tr>
         <td> Boravišna pristojba </td>
         <td align="right"> $pristojba_jc[$p]  </td>
         <td align="right"> $pristojba_k[$p]    </td>
         <td>  </td>
         <td>  </td>
         <td align="right"> $subtotal  kn</td>
      </tr>|;

            $suma_pristojbe += $subtotal;
        }
    }
    $suma_pristojbe += $ukupno;
    $suma_pristojbe = sprintf("%.2f", $suma_pristojbe);
    $suma_pristojbe = sprintf("%.2f", $suma_pristojbe);

    if (($n_pristojbi > 0) && ($suma_pristojbe > 0)) {
        print qq|
   <tr>  
         <td colspan=5 align="LEFT"> UKUPNO PROLAZNE STAVKE </td>
         <td align="right">  $suma_pristojbe kn</td>
   </tr> 

   |;
    }
##########  end of PROLAZNE STAVKE

    # $BILL_total had a value bug, $grand_total was a patch
    # $grand_total = $suma_pristojbe + $total1;

    print <<HTML;
   <tr><td colspan=6><hr> </td></tr>    	
   <tr>
         <td>UKUPNO KN ($paymentModality):</td>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td align="right"><b>$BILL_total</b> kn</td>
   </tr>  
   <tr><td colspan=6><hr> </td></tr>    	
   <tr><td colspan=6 align="center">$BILL_ReceiptMessage </td></tr>    
   <tr><td colspan=6><hr></td></tr> 
   <tr><td colspan=6  align="center">      </td></tr> 
   <tr><td colspan=6><hr> </td></tr> 
</tbody></table>
HTML

    # K O P I J A
}

############### end of render_bill    L_VERSION_3.b  R1 & R2 ################


############### render_bill    L_VERSION_3.00 / simple bills ################
sub render_bill_version3 {
    my $bill_record = $_[0];

    my (
        $key,                           $dbuser,
        $when_added,                    $BILL_brRacuna,
        $BILL_zki,                      $BILL_jir,
        $BILL_oib,                      $BILL_uSustavuPDV,
        $BILL_datum,                    $BILL_vrijeme,
        $BILL_miid,                     $BILL_tiid,
        $BILL_oibOper,                  $BILL_imeOper,
        $BILL_ITEMS_COMPLEX,            $BILL_total,
        $BILL_paymentModalities,        $BILL_pdv_COMPLEX,
        $BILL_pnp_COMPLEX,              $BILL_ostali_porezi_COMPLEX,
        $BILL_povratne_naknade_COMPLEX, $BILL_iznos_oslobodjen_pdv,
        $BILL_R1_R2_COMPLEX,            $BILL_ReceiptMessage,
        $BILL_Company_COMPLEX,          $BILL_Shop_name,
        $BILL_Annex_COMPLEX
    ) = split(/\|/, $bill_record);

    my @pristojba_jc = ();
    my @pristojba_k  = ();
    my @pristojba_i  = ();

    # 4 core components for each item
    my @xls_naziv_artikla = ();
    my @xls_kolicina      = ();
    my @xls_jed_cjena     = ();
    my @xls_iznos         = ();

    # annex - 14 additional components for rendering_version 2
    my @xls_sifra_artikla    = ();
    my @xls_jedinica_artikla = ();
    my @xls_popust           = ();
    my @xls_tax_free_flag    = ();
    my @xls_pdv_value        = ();
    my @xls_pnp_value        = ();
    my @xls_tax1_tag         = ();
    my @xls_tax1_value       = ();
    my @xls_tax2_tag         = ();
    my @xls_tax2_value       = ();
    my @xls_tax3_tag         = ();
    my @xls_tax3_value       = ();
    my @xls_povrat_tag       = ();
    my @xls_povrat_value     = ();

    # annex - 2 more additional components for rendering_version 3.00
    my @xls_prolazna_stavka =
      ();    # (integer: 0....obični artikl, >0 prolazna stavka)
    my @xls_iznos_osnovice = ();    # potreban je samo kod R1 i R2 računa

    my $suma_pristojbe = 0.0;

# extract ITEMS_COMPLEX [Artikl    	   Količina 	   cjena 	   Iznos (kn)]  listing
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_ITEMS_COMPLEX);
    $offset = 0;
    for ($i = 0 ; $i < $n_items ; $i++) {

        $xls_naziv_artikla[$i] = $a[$offset];
        $xls_kolicina[$i]      = $a[$offset + 1];
        $xls_jed_cjena[$i]     = $a[$offset + 2];
        $xls_iznos[$i]         = $a[$offset + 3];

        $offset += 4;
    }

    @x = ();
    ($n_annex, @x) = split(/\;/, $BILL_Annex_COMPLEX);
    $offset = 0;
    if ($n_annex > 0) {
        for ($i = 0 ; $i < $n_annex ; $i++) {
            $xls_sifra_artikla[$i]    = $x[$offset];
            $xls_jedinica_artikla[$i] = $x[$offset + 1];
            $xls_popust[$i]           = $x[$offset + 2];
            $xls_tax_free_flag[$i]    = $x[$offset + 3];
            $xls_pdv_value[$i]        = $x[$offset + 4];
            $xls_pnp_value[$i]        = $x[$offset + 5];
            $xls_tax1_tag[$i]         = $x[$offset + 6];
            $xls_tax1_value[$i]       = $x[$offset + 7];
            $xls_tax2_tag[$i]         = $x[$offset + 8];
            $xls_tax2_value[$i]       = $x[$offset + 9];
            $xls_tax3_tag[$i]         = $x[$offset + 10];
            $xls_tax3_value[$i]       = $x[$offset + 11];
            $xls_povrat_tag[$i]       = $x[$offset + 12];
            $xls_povrat_value[$i]     = $x[$offset + 13];
            $xls_prolazna_stavka[$i]  = $x[$offset + 14];
            $xls_iznos_osnovice[$i]   = $x[$offset + 15];

            $offset += 16;
        }
    }

    my $paymentModality = "";
    if    ($BILL_paymentModalities eq "G") {$paymentModality = "Novčanice";}
    elsif ($BILL_paymentModalities eq "K") {$paymentModality = "Kartice";}
    elsif ($BILL_paymentModalities eq "T") {$paymentModality = "Transakcijski račun";}
    elsif ($BILL_paymentModalities eq "C") {$paymentModality = "Ček";}
    elsif ($BILL_paymentModalities eq "O") {$paymentModality = "Ostalo";}

    $r1_r2 = "0";

    @a = ();
    if ($BILL_R1_R2_COMPLEX eq "") {$BILL_R1_R2_COMPLEX = "0;"}
    if ($BILL_R1_R2_COMPLEX ne "0;") {
        (
            $r1_r2, $tvrtka_klijenta, $adresa_klijenta,
            $postanski_broj_klijenta, $grad_klijenta, $oib_klijenta
        ) = split(/\;/, $BILL_R1_R2_COMPLEX);
    }

    if ($r1_r2 > 0) {$r1_r2 = "R" . $r1_r2}
    $r1_r2 =~ s/r/R/g
      ; #flexibility -- it works for 1, R1, r1 (and 2, R2, r2) - all values are interpreted equaly

    $r1_r2_annex = qq~
<tr>
         <td colspan=2 ><hr></td>
</tr>
<tr>
         <td colspan=2 align="center"><b>Račun $r1_r2 </b></td>

         </tr>
         <tr>
         <td>Klijent: $tvrtka_klijenta</td>
         <td></td>
         </tr>

         <tr>
         <td>Adresa: $adresa_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td> Mjesto: $postanski_broj_klijenta $grad_klijenta</td>
         <td></td>
         </tr>
         <tr>
         <td>OIB: $oib_klijenta</td>
         <td></td>
<tr>
         <td colspan=2 ><hr></td>
</tr>
~;

    if ($r1_r2 eq "0") {$r1_r2_annex = "";}

    (
        $company_Ime,              $company_Adresa_Ulica,
        $company_Adresa_KucniBroj, $company_Adresa_KucniBrojDodatak,
        $company_Adresa_BrojPoste, $company_Adresa_Opcina,
        $shop_descriptive_name
    ) = split(/\;/, $BILL_Company_COMPLEX);

    $pj_annex = "";
    if ($shop_descriptive_name ne "") {
        $pj_annex = "PJ: $shop_descriptive_name";
    }

    $BILL_Shop_name =~ s/\;//g;
    if ($BILL_Shop_name ne "") {$pj_annex = "PJ: $BILL_Shop_name";}

    $pj_annex =~ s/\s+/ /g;
    if ($pj_annex eq "PJ: ") {$pj_annex = "";}

    print <<HTML;
$company_Ime<br>
$company_Adresa_Ulica $company_Adresa_KucniBroj $company_Adresa_KucniBrojDodatak, $company_Adresa_BrojPoste $company_Adresa_Opcina<br>
OIB:$BILL_oib<br>
$pj_annex  <br>
<br>
<table border="0" cellspacing="0"  width="400">
        <tbody>
$r1_r2_annex
<tr>
         <td>Datum: $BILL_datum</td>
         <td align="right">Vrijeme: $BILL_vrijeme</td>
         </tr>
        <tr>
         <td colspan=2 >Blagajnik: $BILL_imeOper, 
         OIB: $BILL_oibOper</td>
         </tr>
        <tr>
         <td>Oznaka prodajnog mjesta: $BILL_miid</td>
         <td></td>
         </tr>
        <tr>
         <td>Oznaka naplatnog uređaja: $BILL_tiid</td>
         <td></td>
         </tr>
        <tr>
         <td colspan=2 align="center"><b><br>RN: $BILL_brRacuna-$BILL_miid-$BILL_tiid </b></td>
         </tr>
       	</tbody>
</table>
<br>
    <table border="0" cellspacing="0" width="450">
    <tbody>
   <tr><td colspan=6>ZKI: $BILL_zki</td></tr> 
   <tr><td colspan=6>JIR: $BILL_jir</td></tr> 
   <tr><td colspan=6><hr> </td>
   </tr> 
        <tr>
         <td colspan=5>Naziv&nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;Porezna stopa&nbsp;</td>
         </tr>
        <tr>
         <td>Šifra&nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Jed.cij.</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Količina</td>
         <td align="right">&nbsp;&nbsp;&nbsp;J.M.</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Popust</td>
         <td align="right">&nbsp;&nbsp;&nbsp;Iznos&nbsp;(kn)</td>
         </tr>
HTML

    ($n_items,   @a) = split(/\;/, $BILL_ITEMS_COMPLEX);
    ($n_items_b, @b) = split(/\;/, $BILL_Annex_COMPLEX);

    @x = ();
    ($n_annex, @x) = split(/\;/, $BILL_Annex_COMPLEX);
    $offset = 0;
    if ($n_annex > 0) {
        for ($i = 0 ; $i < $n_annex ; $i++) {

            $xls_sifra_artikla[$i]    = $x[$offset];
            $xls_jedinica_artikla[$i] = $x[$offset + 1];
            $xls_popust[$i]           = $x[$offset + 2];
            $xls_tax_free_flag[$i]    = $x[$offset + 3];
            $xls_pdv_value[$i]        = $x[$offset + 4];
            $xls_pnp_value[$i]        = $x[$offset + 5];
            $xls_tax1_tag[$i]         = $x[$offset + 6];
            $xls_tax1_value[$i]       = $x[$offset + 7];
            $xls_tax2_tag[$i]         = $x[$offset + 8];
            $xls_tax2_value[$i]       = $x[$offset + 9];
            $xls_tax3_tag[$i]         = $x[$offset + 10];
            $xls_tax3_value[$i]       = $x[$offset + 11];
            $xls_povrat_tag[$i]       = $x[$offset + 12];
            $xls_povrat_value[$i]     = $x[$offset + 13];
            $xls_prolazna_stavka[$i]  = $x[$offset + 14];
            $xls_iznos_osnovice[$i]   = $x[$offset + 15];

            $offset += 16;
        }
    }

    $offset_a = 0;
    $offset_b = 0;

    for ($i = 1 ; $i <= $n_items ; $i++) {

        $artikl   = @a[$offset_a];       # naziv usluge ili proizvoda
        $quantity = @a[$offset_a + 1];
        $quantity =~ s/\.000//g;
        $cjena = @a[$offset_a + 2];
        $iznos = @a[$offset_a + 3];

        $sifra  = @xls_sifra_artikla[$i - 1];      # Šifra usluge ili proizvoda
        $jm     = @xls_jedinica_artikla[$i - 1];
        $popust = @xls_popust[$i - 1];             #

        if ($popust != 0) {
            $popust = "$popust %";
        }
        else {
            $popust = "";
        }

        $osnovica = @xls_iznos_osnovice[$i - 1];
        $osnovica = sprintf("%.2f", $osnovica);

        $pdv = $xls_pdv_value[$i - 1];

        if ($artikl =~ /pristojba/i) {
            push @pristojba_jc, $cjena;
            push @pristojba_k,  $quantity;
            push @pristojba_i,  $iznos;
        }

        $pdv_integer = sprintf("%d", $pdv);

        print qq|
        <tr>
         <td colspan=5>$artikl&nbsp;&nbsp;</td>
         <td align="right">&nbsp;(PDV&nbsp;$pdv_integer)&nbsp;</td>
         </tr>

        <tr>
         <td>$sifra &nbsp;&nbsp;&nbsp;</td>
         <td align="right">&nbsp;&nbsp;&nbsp;$cjena&nbsp;kn </td>
         <td align="right">&nbsp;&nbsp;&nbsp;$quantity</td>
         <td align="right">&nbsp;&nbsp;&nbsp;$jm </td>
         <td align="right">&nbsp;&nbsp;&nbsp;$popust</td>
         <td align="right">&nbsp;&nbsp;&nbsp;$iznos&nbsp;kn </td>
         </tr>
    |;

        $offset_a += 4;
        $offset_b += 14;
    }

    print <<HTML;
   <tr>
         <td colspan=6><hr> </td>
   </tr>    	
   <tr>
         <td>UKUPNO KN ($paymentModality):</td>
         <td></td>
         <td></td>
         <td></td>
         <td></td>
         <td align="right"><b>$BILL_total</b> kn</td>
   </tr>  
   <tr>
         <td colspan=6><hr> </td>
   </tr> 
HTML

    $porezi_ispis = "";
    $x1           = 0;
    $x2           = 0;
    $x3           = 0;
    @a            = ();
    ($n_items, @a) = split(/\;/, $BILL_pdv_COMPLEX);
    $offset = 0;
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $ukupno = @a[$offset + 1] + @a[$offset + 2];
        $x3 += $ukupno;
        $x1 += @a[$offset + 1];
        $x2 += @a[$offset + 2];
        $y1  = sprintf("%.2f", @a[$offset + 1]);
        $y2  = sprintf("%.2f", @a[$offset + 2]);
        $y3a = sprintf("%.2f", $ukupno);
        $porezi_ispis .= qq|
      <tr>
         <td>PDV (@a[$offset] %)</td>
         <td align="right">$y1 kn</td>
         <td></td>
         <td></td>
         <td align="right">$y2 kn</td>
         <td align="right"> $y3a kn</td>
      </tr>|;

        $offset += 3;
    }

    $tax_exemption = qq~
     <tr>
         <td>Oslobođeno PDV-a </td>
         <td align="right"> $BILL_iznos_oslobodjen_pdv kn</td>
         <td></td>
         <td></td>
         <td align="right"> 0.00 kn</td>
         <td align="right"> $BILL_iznos_oslobodjen_pdv kn</td>
      </tr>
~;

    if ($BILL_iznos_oslobodjen_pdv == 0) {$tax_exemption = ""}

    $porezi_ispis .= $tax_exemption;

    $x1 += $BILL_iznos_oslobodjen_pdv;
    $x3 += $BILL_iznos_oslobodjen_pdv;
    $x1 = sprintf("%.2f", $x1);
    $x2 = sprintf("%.2f", $x2);
    $x3 = sprintf("%.2f", $x3);
    $pdv_ukupno = qq~
     <tr>
         <td>UKUPNO </td>
         <td align="right"> $x1 kn</td>
         <td></td>
         <td></td>
         <td align="right"> $x2 kn</td>
         <td align="right"> $x3 kn</td>
      </tr>
~;

    $porezi_ispis .= $pdv_ukupno;

    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_pnp_COMPLEX);
    $offset = 0;
    $y1     = sprintf("%.2f", @a[$offset + 1]);
    $y2     = sprintf("%.2f", @a[$offset + 2]);
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $ukupno = @a[$offset + 1] + @a[$offset + 2];
        $porezi_ispis .= qq|
      <tr>
         <td>PNP (@a[$offset] %) </td>
         <td align="right">$y1  kn </td>
         <td></td>
         <td></td>
         <td align="right">$y2  kn</td>
         <td align="right">  </td>
      </tr>|;

        $offset += 3;
    }

########## ostali_porezi_COMPLEX
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_ostali_porezi_COMPLEX);
    $offset = 0;
    $y2     = sprintf("%.2f", @a[$offset + 2]);
    $y3b    = sprintf("%.2f", @a[$offset + 3]);
    for ($i = 1 ; $i <= $n_items ; $i++) {
        $ukupno = @a[$offset + 2] + @a[$offset + 3];
        $porezi_ispis .= qq|
      <tr>
         <td> @a[$offset] (@a[$offset +1] %) </td>
         <td align="right"> $y2 kn </td>
         <td></td>
         <td></td>
         <td align="right"> $y3b kn</td>
         <td align="right">  </td>
      </tr>|;

        $offset += 4;
    }

########## end of ostali_porezi_COMPLEX

    if ($y3a + $y3b > 0.0) {
        print <<HTML;
   <tr>
         <td colspan=6 align="center"> POREZI  </td>
   </tr> 
   <tr>
         <td>Porez</td>
         <td align="right">Osnovica</td> 
         <td></td>
         <td></td>
         <td align="right">Iznos</td>
         <td align="right">Ukupno</td>
   </tr> 
$porezi_ispis
HTML
    }

##########  povratne_naknade_COMPLEX
    @a = ();
    ($n_items, @a) = split(/\;/, $BILL_povratne_naknade_COMPLEX);

    if (($n_items > 0) || ($BILL_ITEMS_COMPLEX =~ /pristojba/)) {

        print <<HTML;
   <tr>
         <td colspan=6><hr> </td>
   </tr>     
   <tr>
         <td colspan=6 align="center"> PROLAZNE STAVKE </td>
   </tr> 
   <tr>
         <td>Naziv</td>
         <td align="right">Jed. cjena</td>
         <td align="right">Količina</td>
         <td></td>
         <td></td>
         <td align="right">Iznos</td>
   </tr> 

HTML
######

        $offset = 0;
        $ukupno = 0;
        for ($i = 1 ; $i <= $n_items ; $i++) {
            $jc = @a[$offset + 2] / @a[$offset + 1];
            $jc = sprintf("%.2f", $jc);
            $ukupno += @a[$offset + 2];
            print qq|
      <tr>
         <td> Povratna naknada </td>
         <td align="right"> $jc  </td>
         <td align="right"> @a[$offset +1]  </td>
         <td>  </td>
         <td>  </td>
         <td align="right"> @a[$offset+2] kn</td>
      </tr>|;

            $offset += 3;
        }
    }
########## end of povratne_naknade_COMPLEX

##########  PROLAZNE STAVKE
    $n_pristojbi = @pristojba_k;
    if ($n_pristojbi > 0) {
        for ($p = 0 ; $p < $n_pristojbi ; $p++) {
            $subtotal = $pristojba_k[$p] * $pristojba_jc[$p];
            $subtotal = sprintf("%.2f", $subtotal);
            print qq|
      <tr>
         <td> Boravišna pristojba </td>
         <td align="right"> $pristojba_jc[$p]  </td>
         <td align="right"> $pristojba_k[$p]    </td>
         <td>  </td>
         <td>  </td>
         <td align="right"> $subtotal  kn</td>
      </tr>|;

            $suma_pristojbe += $subtotal;
        }

    }

    $suma_pristojbe += $ukupno;
    $suma_pristojbe = sprintf("%.2f", $suma_pristojbe);
    $suma_pristojbe = sprintf("%.2f", $suma_pristojbe);

    if ($n_pristojbi > 0) {
        print qq|
   <tr>   
         <td colspan=5 align="LEFT"> UKUPNO PROLAZNE STAVKE </td>
         <td align="right">  $suma_pristojbe kn</td>
   </tr> 

   |;
    }
##########  end of PROLAZNE STAVKE

    print <<HTML;
   <tr><td colspan=6><hr> </td></tr>    	
   <tr><td colspan=6 align="center">$BILL_ReceiptMessage </td></tr>    
   <tr><td colspan=6><hr> </td></tr> 
   <tr><td colspan=6  align="center">    </td></tr> 
   <tr><td colspan=6><hr> </td></tr> 
    </tbody></table>
HTML

    # K O P I J A
}
############### end of render_bill 3.0 - simple bills ################

