#!/usr/bin/perl
#use cPanelUserConfig;

###############################################
###                                                                                  
###     John Jan Popovic, http://1stmuse.com
###     for Etranet                                    
###                                                                                 
###                                    
###                                                                             
###############################################

use CGI qw (:standard);
use CGI::Carp qw(fatalsToBrowser);
use lib qw(.);
use CGI qw(nph);

# use Encode;
 
  

$SIG{__DIE__} = sub {
    use Carp;
    my $err = shift;
    print "<pre>";
    print "ERROR: $err";
    print Carp::longmess();
    print "</pre>";
};

our $FS   = ';';
our $ROOT;
 
###############################################
###                  Set Configurations Below
###############################################
### Specify database OPERE fields in the array below 
@fields = 
( 
"CARD_Broj_kartice",
"CARD_Tel",
"CARD_Ime",
"CARD_Prezime",
"CARD_Datum_rodjenja",
"CARD_Exp_date",
"CARD_Bodovi",
"CARD_Brand",
"CARD_Email",
"CARD_Popup_message",
"CARD_Popup_autodelete",
"CARD_Referral",
"CARD_Limit",
"CARD_Type", # (Collection_only, Redemption_only,Collection_and_Redemption)
"CARD_Password", 
"CARD_Cart",
"CARD_Address",
"CARD_New_order",
"CARD_Spol"
);



$upload_1x_URL ="./$script_name?operation=upload_1x";
$upload_y_URL ="./detempore_upload_csv.cgi";


### Set URL and email fields to be hyperlinks 
### The number used corresponds to its placement in the array above 
### Remeber to start your count at zero
### Leave the variables empty to remove the hyperlink
$script_name ="$ENV{'SCRIPT_NAME'}";
  
$homedir = $ENV{'DOCUMENT_ROOT'};
$root_   = $ENV{'DOCUMENT_ROOT'};

### Specify the required fields below. This may be left empty 
@required = ();

### Specify the filtered words below.  This may be left empty 
@filter = ("word1","word2");
#$luhn_counter   = "$ENV{'DOCUMENT_ROOT'}/detempore/luhn_counter.txt";    # Parametres file name and path

$database    = "$ENV{'DOCUMENT_ROOT'}/detempore/detempore_clients.txt";	# Data file OPERE name and path
$user_file   = "$ENV{'DOCUMENT_ROOT'}/detempore/users.txt";			   # User file name and path

	   # This script name
$db_name = "detempore - cards";	   	   # The database name
$table_width = "90%";		           # The display width of the entire table
$record_width = "80%";			   # The display width of the database records
$max_rows_returned = "20";	  	   # Max number of rows displayed per page
$filter_html_tags = "yes";		   # Removes HTML tags from record entries
$check_user_duplicates = "yes";		   # Checks for duplicate user names in user file
$use_external_html = "no";		   # Set to "yes" to use your own html template
$external_html_header = "header.html";     # File name and path to html template header
$external_html_footer = "footer.html";	   # File name and path to html template footer
$authenticate = "yes";			   # Prompts users for a user name and password
$register     = "yes";		   # Allows new user registration
$record_ownership = "yes";		   # Users can modify/delete only their records
$admin_user_name = "admin";		   # This is the default Administrator user name
$default_user_permission_search = "yes";   # Gives newly registered users Search permission
$default_user_permission_add = "yes";	   # Gives newly registered users Add permission
$default_user_permission_modify = "no";    # Gives newly registered users Modify permission
$default_user_permission_delete = "no";    # Gives newly registered users Delete permission
$defult_search_index = "0";
$main_path = 'http://loyalty.hr/';

###############################################
###            Change Nothing Below This Line                 
###############################################


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

$q = new CGI;
$field_count = @fields;
$colspan = $field_count+1;
$EXCLUSIVE = 2;
$UNLOCK    = 8;
$loyalty_orders_email = "jjpcondor@gmail.com";
$user = $q->param(user);
$user   = $q->cookie(user) if($user eq "");
$user_search = $q->param(user_search);
$user_search = "yes" if($authenticate eq "no");
$user_add = $q->param(user_add);
$user_add = "yes" if($authenticate eq "no");
$user_trans = $q->param(user_trans);
$user_trans = "yes" if($authenticate eq "no");
$user_modify = $q->param(user_modify);
$user_modify = "yes" if($authenticate eq "no");
$user_delete = $q->param(user_delete);
$user_delete = "yes" if($authenticate eq "no");
$selected_user = $q->param(selected_user);
$admin_add    = $q->param(admin_add);
$sort         = $q->param(sort_on);
$search_for   = $q->param(search_for);
$expired_cards= $q->param(expired_cards);
$soon_expiring= $q->param(soon_expiring);
$detempore_customer= $q->param(detempore_customer);
$Supply       = $q->param(Supply);
$search_field = $q->param(search_field);
$action       = $q->param(action);
$display      = $q->param(display);
@keys         = $q->param(key);
$key          = $q->param(key);
$bodovi       = $q->param(bodovi);
$email        = $q->param(email);
$customer_key = $q->param(customer_key);
$key_matches  = @keys;
$search_field = "all" if($search_field eq "");
$search_for   = '.'   if ($search_for eq "");
$action = $q->param(which_search) if($action =~ /^View/i);
$find_           = $q->param(find_);
$id_             = $q->param(id_);
$filter_         = $q->param(filter_);
$search_field_   = $q->param(search_field_);

################# Main Logic ##################
if($q->param('operation') eq 'opere')  { $action='opere'};
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'};
########


## loyalty.hr/cgi-bin/detempore_clients.cgi?operation=addtocart&broj_kartice=123456&product_=blabla&price_=3982.65

	if($q->param('operation') eq 'addtocart') 	{ 
	 $action='addToCart';
	 $broj_kartice = $q->param('broj_kartice');
	 $product_key  = $q->param('product_');
	 $price        = $q->param('price_');	 
	}



## loyalty.hr/cgi-bin/detempore_clients.cgi?operation=confirmcart&broj_kartice=123456

	if($q->param('operation') eq 'confirmcart') 	{ 
	 $action='confirmCart';
	 $broj_kartice = $q->param('broj_kartice');	 
	}


## loyalty.hr/cgi-bin/detempore_clients.cgi?operation=cancelcart&broj_kartice=123456

	if($q->param('operation') eq 'cancelcart') 	{ 
	 $action='cancelCart';
	 $broj_kartice = $q->param('broj_kartice');	 
	}
	
## To perform search NADJI, click here:
## http://1stmuse.com/cgi-bin/detempore_clients.cgi?operation=nadji_card&find_=1938


	if($q->param('operation') eq 'nadji_card') 	{ 
	 $action='nadji_card';
	 my $find_ = $q->param('find_');	 
         $search_for = $find_;
	}


########
if($action =~ /add administrator/i){ &add_user; exit;}
if ($authenticate eq "yes"){ unless (-e $user_file){ $title="Set Administrative Password"; &create_admin; } }
if($register eq "yes" && $action =~ /register/i){ &register; exit;}
if($action =~ /add user/i){ &add_user; exit;}
if($action =~ /submit login/i){ &authenticate; exit;}
if ($authenticate eq "yes" && $user eq ""){ &login; exit;}
if($action =~ /logout/i){ &logout; exit;}

if($authenticate eq "yes"){
# the following operations can be performed, only if AUTHENTICATION IS VALID
	if($q->param('operation') eq 'search')  { 
	    $action='search';
	    my $buffer;
	    my $id = 0;
	    my $filter_ = $q->param('filter_');
	    my $find_   = $q->param('find_');
	    my $search_field_   = $q->param('search_field_');
	    my $id_     = $q->param('id_');
	    my $user_   = $q->param('user_');
	    $search_for = $find_;
	    $user=$user_;
	    $search_field = $search_field_;
	}

	if($q->param('operation') eq 'main_menu')
	  { 
	    $action='main_menu';
	    my $buffer;
	    my $user_   = $q->param('user_');
	    $search_for = $find_;
	    $user=$user_;
	}

	if($q->param('operation') eq 'upload_1x') { 
	 $action='upload_1x';
	 my $buffer;
	 my $user_ = $q->param('user_');
	 $search_for = $find_;
	 $user=$user_;
	}

	if($action =~ /new_card/i){ &print_add_screen;}
	elsif($action =~ /conferma opera/i){ 
    # &increment_nx_counter; 
    &add_record; $message="Record Added"; $title="Main Menu"; &print_default($title, $message);
  }
	elsif($action =~ /Edit_opera/i){ $title="Edition Error"; $error_message="You forgot to select a record to modify!"; &access_problem if($key < 1); &search_db($key);  &print_modify_page;}
	elsif($action =~ /addToCart/i){ &ajax_addToCart($broj_kartice,$product_key,$price);}
	elsif($action =~ /confirmCart/i){ &ajax_confirmCart($broj_kartice);}
	elsif($action =~ /cancelCart/i){ &ajax_cancelCart($broj_kartice);}

	elsif($action =~ /modify this record/i){ $title="Modify"; &delete_records; $key=$keys[0]; &add_record; &print_back;}
	elsif($action =~ /conferma_Edit/i){ $title="Modify"; &delete_records; $key=$keys[0]; &add_record; &print_back;}
	elsif($action =~ /delete record/i){ $title="Delete Record"; $error_message="You forgot to select a record to delete!"; &access_problem if($key < 1); &delete_records; $message="Record Updated"; $title="Main Menu"; &print_default($title, $message);}
	elsif($action =~ /modify/i){ &search_db($search_for); $title="Modify Which Record?"; $button_text="Modify Record"; $choose="modify"; &search_results;}
	elsif($action =~ /billing_report/i){ $title="Billing results"; &billing_results($search_for,3); }
	elsif($action =~ /email_billing/i){ $title="Billing results"; &mail_billing($search_for,3); }

        elsif($action =~ /populate/i){ $title="Update Cards SYNC";  &load_cards;}	
        elsif($action =~ /mailinglist/i){ $title="Extract mailinglist"; &extract_mailinglist; $message="Mailinglist was created."; $title="Main Menu"; &print_default($title, $message);}
        elsif($action =~ /new_orders/i){ $title="New orders"; &new_orders; $message="New orders are created."; }
        elsif($action =~ /confirm_new/i ){ $title="Order confirmed"; &confirm_new; $message="New orders are confirmed."; }

        elsif($action =~ /upload_1x/i){ $title="upload 1 of 2"; &print_upload_1x_page($ITEM_type);}
        elsif($action =~ /upload_2x/i){ $title="upload 2 of 2"; &upload_2x;}

        elsif($action =~ /backup/i){ $title="Backup Archive"; &backup_detempore; $message="The backup was successful."; $title="Main menu"; &print_default($title, $message);}
	elsif($action =~ /delete/i){ &search_db($search_for); $title="Delete Which Record?"; $button_text="Eliminate card"; $choose="delete"; &search_results;}
	elsif($action =~ /search/i){ &search_db($search_for,$expired_cards,$soon_expiring); $title="Search Results"; $button_text = "";  $choose="search"; $what="search"; &search_results;}
	elsif($action =~ /email_search_/i){ &search_db($search_for); $title="Search Results"; $button_text = "";  $choose="email_search_"; $what="email_search_"; &search_email_results;}
	elsif($action =~ /user manager/i){ $title="User Manager"; &user_manager;}
	elsif($action =~ /create new user/i){ $title="User Manager - Create New User"; $perform="add"; $button_text ="Add User"; &edit_user;}
	elsif($action =~ /edit selected user/i){ $title="User Manager - Edit Selected User"; $perform="edit"; $button_text ="Edit User"; &edit_user;}
	elsif($action =~ /edit user/i){ $old_password = $q->param(old_password); &delete_user; $perform="edit"; &add_user;}
	elsif($action =~ /remove selected user/i){ $perform="delete"; &delete_user; $title="User Manager"; &user_manager;}
        elsif($action =~ /nadji_card/i){ &search_cards($search_for);}
	else { $title="Main Menu"; &print_default($title); }
}

exit;

################# Add Record ##################

sub add_record {
  foreach $required (@required){
  if($q->param($required) eq "") { 
  $title = "Add A Record"; $error_message = "You did not fill out the required information!"; &access_problem($error_message); exit; } }
  $when_added = &get_date;
  $key   = time();
  $record=$key;
  $record  .= "\|$user";
  $record  .= "\|$when_added";
  foreach $field (@fields){ ${$field}  = $q->param($field); ${$field}  = filter(${$field}); $record  .= "\|${$field}"; }
   unless (-e $database){ open (DB, ">$database") || die "Error creating database.  $!\n"; }
   else { open (DB, ">>$database") || die "Error opening database.  $!\n"; }
   flock DB, $EXCLUSIVE;
   seek DB, 0, 2;
   print DB "$record\n";
   flock DB, $UNLOCK;
  close(DB);
} # End of add_record subroutine.




################# Add Screen: Add new Card ##################

sub print_add_screen{
$title="Add new Card";


##### Read Luhn Number
 
##### end of Luhn Number

&html_header($title);

$card_number =$currentnumber;
 
 $date_time = &get_date;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
 ++$yy;
# Format $dd,$mm numbers with up to 2 leading zeroes
$dd = sprintf("%02d", $dd);
$mm = sprintf("%02d", $mm);
$exp_date = "$dd\.$mm\.$yy";

  print<<HTML;
<SCRIPT LANGUAGE="JavaScript">

<!-- This script locksout <CR> i.e. Enter Key and requires the SUBMIT button to be clicked to send form -->
<!-- Begin

function tabOnEnter (field, evt) {
      var keyCode = document.layers ? evt.which : document.all ? 
     evt.keyCode : evt.keyCode;
      if (keyCode != 13)
        return true;
      else {
        getNextElement(field).focus();
        return false;
      }
}


function getNextElement (field) {
    var frm = field.form;
    var bIs = false;
    for (var e=0;e<frm.length;e++)
    {
      if(frm[e].type!="hidden" && bIs) return frm.elements[e];
      if (field==frm[e]) bIs=true;
    }
}

//  End -->
</script>

     <P>
      <TABLE BORDER=0 CELLSPACING=0>

HTML

  foreach $field (@fields){

    $input_txt="<INPUT TYPE=TEXT NAME=\"$field\"   onkeydown=\"return tabOnEnter (this, event);\"  >";
    $cerca=$search_for;

    if ($field eq "CARD_Broj_kartice") {
    	$input_txt="<INPUT TYPE=TEXT NAME=\"CARD_Broj_kartice\" value=\"$card_number\"  onkeydown=\"return tabOnEnter (this, event);\"  >";
    }; 

    if ($field eq "CARD_Tel") {
    	$input_txt="<INPUT TYPE=TEXT NAME=\"CARD_Tel\" value=\"$CARD_Tel\"  onkeydown=\"return tabOnEnter (this, event);\"  >";
    }; 

    if ($field eq "CARD_Password") {
    	$input_txt="<INPUT TYPE=TEXT NAME=\"CARD_Password\" value=\"$card_number\"  onkeydown=\"return tabOnEnter (this, event);\"  >";
    }; 


    if ($field eq "CARD_New_order") {
    	$input_txt="<INPUT TYPE=\"hidden\" NAME=\"CARD_New_order\" value=\"yes\"  >";
      $field="";
    };

    if ($field eq "CARD_Exp_date") {
    	$input_txt="<INPUT TYPE=TEXT NAME=\"CARD_Exp_date\" value=\"$exp_date\"  onkeydown=\"return tabOnEnter (this, event);\"  >";
    }; 

    if ($field eq "CARD_Spol") {
$input_txt =qq~
<select name="CARD_Spol">
<option value="M" >Muški</option>
<option value="Ž" >Ženski</option>
</select> ~;
    }; 


    $input_html=$input_txt;



print<<HTML;
        <TR>
         <TD><B>\u$field</B></TD>
         <TD>$input_html</TD>
         </TR>
HTML

  } # End of foreach.
      print<<HTML;
       <TR>
        <TD COLSPAN=2>
         <CENTER><BR>
<INPUT TYPE=button  onClick=" myForm.action.value='Conferma opera';this.form.submit();"  VALUE="Save" >

         </CENTER>
        </TD>
       </TR>
      </TABLE>
     <P>
    </FONT>
<SCRIPT LANGUAGE="JavaScript" >
 
function getElementIndex(obj) {
	var theform = obj.form;
	for (var i=0; i<theform.elements.length; i++) {
		if (obj.name == theform.elements[i].name) {
			return i;
			}
		}
	return -1;
	}

 
function tabNext(obj) {
	if (navigator.cgiatform.toUpperCase().indexOf("SUNOS") != -1) {
		obj.blur(); return; // Sun's onFocus() is messed up
		}
	var theform = obj.form;
	var i = getElementIndex(obj);
	var j=i+1;
	if (j >= theform.elements.length) { j=0; }
	if (i == -1) { return; }
	while (j != i) {
		if ((theform.elements[j].type!="hidden") && 
		    (theform.elements[j].name != theform.elements[i].name) && 
			(!theform.elements[j].disabled)) {
			theform.elements[j].focus();
			break;
			}
		j++;
		if (j >= theform.elements.length) { j=0; }
		}
	}
</SCRIPT>
HTML
&html_footer;
} # End of print_add_screen subroutine.






############## Delete Records #################

sub delete_records   {              
  open (DATABASE, "$database") or die "Error opening file: $!\n";
  while (<DATABASE>)   {
    $line = $_;
    chop $line;
    @dbfields = split (/\|/, $line);
    $deleted = "no";
    if ($dbfields[0] eq $q->param(key)) { $deleted = "yes"; if ($user eq $dbfields[1]) { $security_satisfied = "yes"; } }
    elsif ($deleted ne "yes") { $new_data .= "$line\n"; }
    } #end of while
  close (DATABASE);
  if ($authenticate ne "yes") { $security_satisfied = "yes"; }
  if ($security_satisfied ne "yes" && $record_ownership eq "yes" && $admin_user_name ne "$user")
    {
    $error_message = "Lei non ha le permessi necessari per l\92accesso a questa card!";
    &access_problem($error_message);
    exit;
    }  else  {
    flock DATABASE, $EXCLUSIVE;
    open (DATABASE, ">$database") or die "Error opening file: $!\n";
    print DATABASE "$new_data";
    close (DATABASE);
    flock DATABASE, $UNLOCK;
    }
  } 









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

&html_header;
 print<<HTML;
  <TABLE BORDER=0 CELLSPACING="0" CELLPADDING="3"><TR><TD COLSPAN=3>
  <TR>
<TD width="210"><B>Search for:</B><BR>
<INPUT TYPE="text" NAME="search_for" SIZE="35" 
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="Find" type="button">
</TD>
 <TD width="170">

Expired cards only:&nbsp;&nbsp;&nbsp;
<input type="checkbox" name="expired_cards" id="expired_cards" onclick="Calc(this.form)" value="expired_cards_only" onkeydown="return tabOnEnter (this, event);" >

<br>
Soon expiring cards:
<input type="checkbox" name="soon_expiring" id="soon_expiring" onclick="Calc(this.form)" value="soon_expiring_only" onkeydown="return tabOnEnter (this, event);" >

 </TD>      
        </TR>
<TR>
    <TD><B>Search in the fields:</B><BR><SELECT NAME="search_field"><OPTION VALUE="all">All 
HTML
   $x=0;
   $selected='';
   foreach $field (@fields){  
      print "<OPTION VALUE=$x $selected>\u$field";
      $x++;
      $selected='';
      if ($x eq $defult_search_index) { $selected='selected';}
  }
  print<<HTML;
    </SELECT></TD><TD><B>Sort on:</B><BR><SELECT NAME="sort_on">
HTML
  $x=0;
  $selected='';
  foreach $field (@fields){  print "<OPTION VALUE=$x  $selected>\u$field";  
      $x++;
      $selected='';
      if ($x eq $defult_search_index) { $selected='selected';}
  }
  print<<HTML;
</SELECT></TD>
	<TD><B>Display: </B><BR><SELECT NAME="display">
HTML
if($display eq "rows") { print "<OPTION VALUE=\"rows\" SELECTED>Cards"; }
else { print "<OPTION VALUE=\"rows\">cards"; }
if($display eq "columns") { print "<OPTION VALUE=\"columns\" SELECTED>Table"; }
else { print "<OPTION VALUE=\"columns\">Tabellone"; }
  print<<HTML;
</SELECT></TD></TR></TABLE><br>
HTML
$footer="default";
&html_footer;
} # End of print_default subroutine.













########### Search & Sort Database #############
sub search_db{
  my $search_for    = $_[0];
  my $expired_cards = $_[1];
  my $soon_expiring = $_[2];

     $date_time = &get_date;
     $date_time =~ s/at/~/g;
    ($date,$day_time) = split (/\~/,$date_time);
  my $jd_today      =julian_day($date);

   unless (-e $database){ open (DB, ">$database") || die "Error creating database.  $!\n"; }
   else { open (DB, "$database") || die "Error opening database.  $!\n"; }
    while(<DB>){
      ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $_);
    my $expiery_date =$field_vals[5];
    my $jd_Exp_date  =julian_day($expiery_date);
    my $delta = $jd_today - $jd_Exp_date;


 #   if (($delta >0)||($expired_cards eq "expired_cards_only")) { # 	Expired cards only
      if($search_field =~ /all/i) {
          if (/$search_for/oi){ push @results, $_};
      } else {       
          if ($field_vals[$search_field] =~ /$search_for/oi) { push @results, $_};
      } # End of else.
 #  }


    } # End of while.
  close (DB);
  foreach $curr (@results){
    ($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_on = "$fields[$sort]";
   @results=();
  foreach $rp (sort { $a->{$sort_on} cmp $b->{$sort_on} } 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
$count = @results;
if($count < 1){ 
  $message="No Matches Found For '$search_for'";
  $title="Main Menu";
  &print_default($title, $message);  
### intervention
  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_db subroutine.





################### Filter ####################
sub filter{
  $temp = $_[0];
  $temp =~ s/\|//g; 
  $temp =~ s/\"/'/g; 
  foreach $removed (@filter) { $temp =~ s/$removed/\?\$\%\&/gi; }
  if ($filter_html_tags eq "yes") { $temp =~ s/<[^>]*>//gs;  }
  return ($temp);
}

############### Check Item #################

sub check_item{
  $r_val = $_[0];
  $index = $_[1];
  if($r_val =~ /^\s*$/){$r_val="&nbsp;"; return($r_val);}
  if( ($index_of_image_url ne "") && (($index eq $index_of_image_url)|($index eq $index2_of_image_url)) ) { 
  if ($r_val =~ /http:\/\//i){ $link = "$r_val"; }                        
  else { $link = "http://1stmuse.com/"; $link .= "$r_val";  }
  $r_val2 = "<a href=\"$link\">$r_val</a>"; $r_val = $r_val2; 
   }
  if($index_of_URL ne "" && $index eq $index_of_URL) { $r_val2 = "<a href=\"$r_val\">$r_val</a>"; $r_val = $r_val2; }
  if($index_of_email ne "" && $index eq $index_of_email) { $r_val2 = "<a href=\"mailto:$r_val\">$r_val</a>"; $r_val = $r_val2; }
  return($r_val);
}
################### Login ###################
sub login {
$message = $_[0];
$title = "Login";
&html_header($title,$message);
print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30"></TD></TR>
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30" onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
    {myForm.action.value='Submit Login';this.form.submit();return false;} 
    else return true;"></TD>
</TR>
<TR><TD ALIGN=MIDDLE><BR>
<INPUT TYPE=button  onClick=\" myForm.action.value='Submit Login';this.form.submit();\"  VALUE="Submit Login" >
HTML
if($register eq "yes") { print "<INPUT TYPE=button onClick=\" myForm.action.value='Register';this.form.submit();\" VALUE=\"Register\">"; }
print<<HTML;
</TD>
</TR>
</TABLE>
HTML
$footer = "login";
&html_footer;
}

################ Authenticate ################

sub authenticate {
    $form_password = $q->param(password);
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    $user_matched = 0;
    while (<USERFILE>) {
	chop($_);
	($password, $user, $u_search, $u_add, $u_modify, $u_delete) = split(/\|/, $_);
	if ($q->param(user) eq $user) {
	    $user_matched = 1;
	    $username = $user;
	    $user_add = $u_add;
	    $user_modify = $u_modify;
	    $user_search = $u_search;
	    $user_delete = $u_delete;
	if (&auth_encrypt ($form_password, $password) eq $password) {
  	    $cookie = cookie(-NAME=>'user',-VALUE=>"$user",-EXPIRES=>'+3d');
	} # End of if passwords match
	} # End of if username matches
    } # End of While
    close (USERFILE);
    if ($user_matched == 1 && $cookie eq "") {
	    $footer = "login";
	    $title = "Login";
	    $error_message = "Your password did not match your user name!";
	    &access_problem($error_message);
	    exit;    }
    if ($user_matched == 0) {
	    $footer = "login";
	    $title = "Login";
	    $error_message = "Your user name was not found!";
	    &access_problem($error_message);
	    exit;    }
print header(-cookie=>[$cookie]);
$set_cookie = "yes";
$message = "User \"$username\" is now logged in";
$title = "Main Menu"; 
$user = $username;
&print_default($title, $message);
exit;
}

############### Register Form ################

sub register {
$title = "Register A New User";
&html_header($title);
 print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30"></TD></TR>
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML

 print<<HTML;
<TR><TD ALIGN=MIDDLE><BR>
<INPUT TYPE="hidden" NAME="search" value="$default_user_permission_search">
<INPUT TYPE="hidden" NAME="add" value="$default_user_permission_add">
<INPUT TYPE="hidden" NAME="modify" value="$default_user_permission_modify">
<INPUT TYPE="hidden" NAME="delete" value="$default_user_permission_delete">
<INPUT TYPE=button  onClick=" myForm.action.value='Add User';this.form.submit();"  VALUE="Add User" >
<INPUT TYPE=button  onClick=" myForm.action.value='Back To Login';this.form.submit();"  VALUE="Back To Login" >
</TD>
</TR>
</TABLE>
HTML
$footer = "login";
&html_footer;
}

################ Add User ##################

sub add_user {
$user = $q->param(user);
$password = $q->param(password);
$password2 = $q->param(password2);
if ($perform eq "edit" && $password eq "") { $use_old = "yes"; $password = "$old_password"; $password2 = "$old_password";}
	if ($password ne $password2 || $password eq "" || $password2 eq "") {
	    $footer = "login";
	    $title = "Register A New User";
	    $error_message = "Your passwords didn't match!";
	    &access_problem($error_message);
	    exit;	}
@form_vars = ('user', 'search', 'add', 'modify', 'delete');
    foreach $x (@form_vars) {
	if ($q->param($x) eq "" || $q->param($x) =~ /\|/) {
             $footer = "login";
	    $title = "Register A New User";
	    $error_message = "You must fill in all of the fields in the registration form!";
	    &access_problem($error_message);
	    exit;	}     }
    if ($check_user_duplicates eq "yes") {
	open (USERFILE, "$user_file");
	$user_matched = 0;
	while (<USERFILE>) {
	    chop($_);
	    @f = split(/\|/, $_);
	    if ($f[1] eq $user) {
		$user_matched = 1;
		last;	    }	} # End of while userfile open
	close (USERFILE);
	if ($user_matched == 1) {
	    $footer = "login";
	    $title = "Register A New User";
	    $error_message = "That user name is already taken!";
	    &access_problem($error_message);
	    exit;	} # End of user matched (found duplicate)    
	} # End of if check duplicates on
    srand(time|$$);
    $random = "abcdefghijklmnopqrstuvwxyz1234567890";
    $real_password = $password;
    $salt = "";
    for (1..2) { $salt .= substr($random,int(rand(36)),1); }
  if ($use_old ne "yes") {  $password = &auth_encrypt ($password, $salt); }
  $auth=$password;
  foreach $field (@form_vars){
    ${$field}  = $q->param($field);
    $auth   .= "\|${$field}";  }
   unless (-e $user_file){
    open (AUTH_FILE, ">$user_file") || die "Error creating user file.  $!\n";
  } else {
    open (AUTH_FILE, ">>$user_file") || die "Error opening user file.  $!\n";
  }
   flock AUTH_FILE, $EXCLUSIVE;
   seek AUTH_FILE, 0, 2;
   print AUTH_FILE "$auth\n";
   flock AUTH_FILE, $UNLOCK;
  close(AUTH_FILE);
if ($admin_add eq ""){
   $message = "New User Added<br>You may now login with your new user name below.";
   &login($message);
   } else { 
   $title = "User Manager";
   $message = "User Added/Modified";
   &user_manager($message);
   }
}

################ Create Admin ###############

sub create_admin{
&html_header($title);
 print<<HTML;
<center><TABLE WIDTH=275>
<TR>
<TD>Please start out by setting the Administrator information below.  When logged in as the below user, you will be able to access additional options which are only available to the database administrator.</TD>
</TR><TR>
<TD><br><B>User Name:</B> $admin_user_name<br>This can be changed in the script configurations.</TD></TR>
<TR><TD><br><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>

<TR><TD ALIGN=MIDDLE><BR><INPUT TYPE="hidden" NAME="user" value="$admin_user_name">
<INPUT TYPE="hidden" NAME="search" value="yes">
<INPUT TYPE="hidden" NAME="add" value="yes">
<INPUT TYPE="hidden" NAME="modify" value="yes">
<INPUT TYPE="hidden" NAME="delete" value="yes">
<INPUT TYPE=button  onClick=" myForm.action.value='Add Administrator';this.form.submit();"  VALUE="Add Administrator" >
</TD>
</TR>
</TABLE></center>
HTML
$footer = "login";
&html_footer;
exit;
}

################ User Manager ###############

sub user_manager{
$message = $_[0];
&html_header($title,$message);
 print<<HTML;
<center>
<TABLE>
<TR>
<TD><select name="selected_user" size=8>
HTML
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    while (<USERFILE>) {
	chop($_);
	($password, $user, $u_search, $u_add, $u_modify, $u_delete) = split(/\|/, $_);
	print "<option value=\"$user\">$user</option>\n";
    } # End of While
    close (USERFILE);
  print<<HTML;
</select></TD>
<td valign=top>
<input TYPE=button onClick=" myForm.action.value='Create New User';this.form.submit();" value="Create New User"><p>
<input TYPE=button onClick=" myForm.action.value='Edit Selected User';this.form.submit();" value="Edit Selected User"><p>
<input TYPE=button onClick=" myForm.action.value='Remove Selected User';this.form.submit();" value="Remove Selected User">
</TR>
</TABLE>
</center>
HTML
&html_footer;
exit;
}

############### Add/Edit User ################

sub edit_user {
if ($perform eq "edit" && $selected_user eq "" ) {
	    $title = "User Manager - Edit Selected User";
	    $error_message = "You forgot to select a user record to edit!";
	    &access_problem($error_message);
	    exit;
}
if ($perform eq "edit") {
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    while (<USERFILE>) {
	chop($_);
	($password, $userfound, $u_search, $u_add, $u_modify, $u_delete, @other_user_fields) = split(/\|/, $_);
	if ($selected_user eq $userfound) {
	    @found_other_fields = @other_user_fields;
	    $edit_user = $userfound;
	    $edit_user_add = $u_add;
	    $edit_user_modify = $u_modify;
	    $edit_user_search = $u_search;
	    $edit_user_delete = $u_delete;
	    $old_password = $password;
	} # End of if username matches
    } # End of While
    close (USERFILE);
}
&html_header($title);
 print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30" value="$edit_user"></TD></TR>
HTML
if ($perform eq "edit") {
  print<<HTML;
<TR><TD><B>New Password</B><br>Leave blank if you aren't changing passwords.<BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
HTML
} else {
  print<<HTML;
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
HTML
}
if ($perform eq "edit") {
  print<<HTML;
<TR><TD><B>Re-Type New Password</B><br>Leave blank if you aren't changing passwords.<BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML
} else {
  print<<HTML;
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML
}


 print<<HTML;
<tr><td><br><b>User Permissions</b></td></tr>
HTML

if ($edit_user_search eq "no"){
  print<<HTML;
<tr><td>Search: <input type="radio" name="search" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="search" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Search: <input type="radio" name="search" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="search" value="no"> No</td></tr>
HTML
}
if ($edit_user_add eq "no"){
  print<<HTML;
<tr><td>Add: <input type="radio" name="add" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="add" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Add: <input type="radio" name="add" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="add" value="no"> No</td></tr>
HTML
}
if ($edit_user_modify eq "no"){
  print<<HTML;
<tr><td>Modify: <input type="radio" name="modify" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="modify" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Modify: <input type="radio" name="modify" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="modify" value="no"> No</td></tr>
HTML
}
if ($edit_user_delete eq "no"){
  print<<HTML;
<tr><td>Delete: <input type="radio" name="delete" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="delete" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Delete: <input type="radio" name="delete" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="delete" value="no"> No</td></tr>
HTML
}
  print<<HTML;
<TR><TD ALIGN=MIDDLE><BR><input type=hidden name="old_password" value="$old_password"><input type=hidden name="selected_user" value="$edit_user"><input type=hidden name="admin_add" value="yes">
<INPUT TYPE=button  onClick=" myForm.action.value='$button_text';this.form.submit();"  VALUE="$button_text" >
<INPUT TYPE=button  onClick=" myForm.action.value='User Manager';this.form.submit();"  VALUE="User Manager" >
</TD>
</TR>
</TABLE>
HTML
&html_footer;
}

################ Delete User ###############

sub delete_user{
if ($selected_user eq "" ) {
	    $title = "User Manager - Remove Selected User";
	    $error_message = "You forgot to select a user record to remove!";
	    &access_problem($error_message);
	    exit;
}
if ($selected_user eq "$admin_user_name" && $perform eq "delete") {
	    $title = "User Manager - Remove Selected User";
	    $error_message = "You are not allowed to remove the administrator!";
	    &access_problem($error_message);
	    exit;
}
  open (USERFILE, "$user_file") or die "Error opening file: $!\n";
  while (<USERFILE>)
    {
    $line = $_;
    chop $line;
    @dbfields = split (/\|/, $line);
    $deleted = "no";
    if ($dbfields[1] eq $selected_user) { $deleted = "yes"; }
    elsif ($deleted ne "yes") { $new_data .= "$line\n"; }
    } #end of while
  close (USERFILE);
    flock USERFILE, $EXCLUSIVE;
    open (USERFILE, ">$user_file") or die "Error opening file: $!\n";
    print USERFILE "$new_data";
    close (USERFILE);
}

################# Logout ###################

sub logout {
$cookie = cookie(-NAME=>'user',-VALUE=>"$user",-EXPIRES=>'-1d');
print header(-cookie=>[$cookie]);
$set_cookie = "yes";
$message = "User \"$user\" logged out";
&login($message);
 } # end of logout

############ Encrypt Password ###############

sub auth_encrypt {
    local ($field, $salt) = @_;
    $field = crypt ($field, $salt);
    $field;
 } # end of encrypt

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

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

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

sub get_date  {
  local ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst,$date);   
  local (@days, @months);
  @days = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  @months = ('January','February','March','April','May','June','July','August','September','October','November','December');
  ($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;
 $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">
HTML
}















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

sub form_footer {
if($footer eq "default") {
if ($authenticate  eq "yes") {print "<INPUT TYPE=button  onClick=\" myForm.action.value='new_card';this.form.submit();\"  VALUE=\"New card\" > "; }

print qq~
<INPUT type=button  onclick="doNew_x()" value="Upload csv batch file" name=storage> 
<INPUT TYPE=button  onClick=" myForm.action.value='populate';this.form.submit(  );"  VALUE="Import  cards" > 
~;

print qq~<INPUT TYPE=button onClick="myForm.action.value='Backup';this.form.submit();" VALUE="Backup" > ~;
print qq~<INPUT TYPE=button onClick="myForm.action.value='mailinglist';this.form.submit();" VALUE="Extract mailinglist" > ~;
print qq~<INPUT TYPE=button onClick="myForm.action.value='new_orders';this.form.submit();" VALUE="New orders" > ~;

if ($authenticate eq "yes") { print "<INPUT TYPE=button  onClick=\" myForm.action.value='Logout';this.form.submit();\"  VALUE=\"Logout\" >\n"; }
}
elsif($footer eq "login") { print "\&nbsp\;"; }
 else { 
 print "<INPUT TYPE=button  onClick=\" myForm.action.value='Main Menu';this.form.submit();\"  VALUE=\"Main Menu\" >";
 if ($authenticate eq "yes") { print "<INPUT TYPE=button  onClick=\"myForm.action.value='Logout';this.form.submit();\"  VALUE=\"Logout\" >";}
 }

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


print<<HTML;

<script type="text/javascript">
function ValueTransfer(f) {
	self.opener.document.myForm.ICONOGRAFIA_file_web.value = f;
	}


var myWind = ""

function doNew_x() {
// either open, or put on the top if it is already existing
	if (myWind == "" || myWind.closed || myWind.name == undefined) {

           pics = window.open("../$script_name?operation=upload_1x","subWindow","HEIGHT=200,WIDTH=620,status=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=yes").focus();

	} else{	myWind.focus();	}
}




</script>
HTML



}




















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

sub html_header{
print "Content-type: text/html; charset=utf8 \n\n";
if($use_external_html eq "yes") { 
%external_variables = (title=>$title, message=>$message,);
print html_template("$external_html_header", \%external_variables); 
&form_header;
} else {
 print<<HTML;
<HTML><HEAD>
 <meta http-equiv="content-type" content="text/html;  charset=utf8">
 <TITLE>$db_name - $_[0]</TITLE>
 </HEAD>
<BODY BGCOLOR="#FFFFFF">
  <link rel="stylesheet" href="$main_path/js/styles_ns.css">
  <script language="JavaScript" src="$main_path/js/global.js"></script>	
 <CENTER><B>
 $db_name
 </B><p><FONT SIZE=3 FACE="ARIAL" COLOR=RED><B>$_[1]</B></FONT></CENTER><P>
 <CENTER>
 <TABLE BORDER=1 WIDTH="$table_width" CELLSPACING="0" CELLPADDING="3">
 <TR> 
 <TD BGCOLOR="#e0e0e0" align="right"> 
 <CENTER>  <B>$_[0]</B>  </CENTER>
<a class="textblue" href="javascript:popWindowArticles('http://loyalty.hr/detempore/help_clients.pdf');"> 
<b>Help</a>
 </TD>
 </TR>
 <TR> 
 <TD align=middle><BR>

HTML
&form_header;
}
}















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

sub html_footer{
if($use_external_html eq "yes") { 
%external_variables = (title=>$title, message=>$message,);
&form_footer;
print html_template("$external_html_footer", \%external_variables); 
if ($user eq "$admin_user_name" && $footer eq "default" && $authenticate eq "yes") {
print "<center><INPUT TYPE=button  onClick=\"myForm.action.value='User Manager';this.form.submit();\"  VALUE=\"User Manager\" ></center><p>";
}
print "<center><p>Powered by <a href=\"http://www.1stmuse.com\">dbSpace</a><br>\&copy\; Spaceout<br><br></center>";
} else {
 print<<HTML;
    <BR></TD></TR>
  <TR> 
    <TD BGCOLOR="#e0e0e0"><CENTER> 
HTML
&form_footer;
 print<<HTML;
     </CENTER>
    </TD>
  </TR>
</TABLE><P>
HTML
if ($user eq "$admin_user_name" && $footer eq "default" && $authenticate eq "yes") {
print "<center><INPUT TYPE=button  onClick=\"myForm.action.value='User Manager';this.form.submit();\"  VALUE=\"User Manager\" ></center><p>";
}
  print<<HTML;




<script language="JavaScript">

<!-- function handler(e) {
    var key = e.which : e.keyCode;
    if (key == 13)     {myForm.action.value='search';this.form.submit();return false;}; 
    else return true;
}


//-->
</script>

</BODY></HTML>
HTML
	}
}

### To avoid usual situation like:
### After filling out the text field, you HAVE to click the specified button to 
### submit the form. If you press enter to submit the form it reloads the form.
### I have written small Javascript code in order to avoid previous behavior and to:
### Process the form by pressing the <ENTER> by putting the focus on the specified (default) button
### In the input field must be inserted the EVENT HANDLER
### like: <INPUT TYPE="text" NAME="search_for" SIZE="40" 
###       onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
###       {myForm.action.value='Logout';this.form.submit();return false;} else return true;" >






############ Print Next Page Buttons ###########################
sub next_page_buttons {

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

}




################ Back Screen ##################

sub print_back {

&html_header;
 print<<HTML;
<script language="JavaScript">
window.history.go(-3);
</script>
HTML
&html_footer;
} # End of print_default subroutine.




############# Results Screen ################
sub search_email_results{

$display = "columns"; 

# header
&html_header($title);
  $rows_left_to_view = $total_row_count - $new_hits_seen;
  $start_hit = $hits_seen + 1;
  $end_hit = $new_hits_seen;
  $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>Trovati: <B>1</B> record\n~; }
    #print "<br>nel campo: <b>$search_field_ </b> trova: <b> $find_ </b>";
$cerca = $search_for;
print "<br>";

if ($button_text ne "")
{ 
   if ($button_text eq "Modify Record") {
     print "<INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" >";
  };
}
$which_search = $choose;
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE=\"$bodovi\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE=\"\">\n";
# end of header


$display = "columns"; 
if($display =~/columns/i) {
 print<<HTML;
	<p><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
    <TR BGCOLOR="#e0e0e0">
HTML
  if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit();\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='nuovo';this.form.submit();\" VALUE=\"aggiungere card\" >
</TD></TR>\n";
  }

  foreach $field (@fields){
    print "<TD ALIGN=CENTER><B>\u$field</B></TD>\n";
  } # End of foreach


  print "</TR>";
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
    print "<TR BGCOLOR=\"#efefef\">\n";
    if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit();\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
</TD></TR>\n";
}
 # End of if $display =~columns
      for($x=0;$x<$field_count;$x++){
      $item = &check_item($field_vals[$x], $x);
      print "<TD>$item</TD>\n";
    }
     print "</TR> ";
  } # End of foreach loop.
  print<<HTML;
</TR></TABLE>
HTML
} 

else 
# do rows
{
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
### intervention
print<<HTML;
	<P><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
HTML

  $x=0;
  foreach $field (@fields){
  $item = &check_item($field_vals[$x], $x);


$background_color="#e0e0e0";
$line= "<TD BGCOLOR='#efefef' WIDTH=100%>$item</TD>";
if ($x > 9) {$background_color='#B6DB91'; $line= "<TD BGCOLOR='#D5FFD5' WIDTH=100%>$item</TD>" };



$campo = $field;

print<<HTML;
     <TR>
      <TD BGCOLOR=$background_color><B>\u$campo</B></TD>
      $line
     </TR>
HTML



   $x++;
 	 } # End of foreach field loop.
######## buttons on the end of record
  if($choose =~ /(modify|delete|search)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2> ";


    print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Edit_opera';this.form.submit();\"  VALUE=\"Edit card\" >
           <INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
           ";

};

######## end of buttons 
  print "</TABLE><P>";

  } # End of foreach record loop.

# end of rows display
} # End of if display loop

if ($button_text ne "")
{ 
  if ($button_text eq "Modify Record") {
     print " <INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" >";
  };
}

$which_search = $choose;
############### next page buttons 
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_field\" VALUE=\"$search_field\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE=\"$bodovi\">\n";
print "<p>";
$cerca_t=$cerca;
if ($cerca eq '.') {$cerca_t='tutto'};

&html_footer;
} # End of search_results subroutine.



























############### backup_detempore ################
sub backup_detempore{
# Author : John Jan Popovic
# Date : July, 2012
# Purpose: This procedure performs DBase adonis Backup



# Create %adonis_hash
 %DBADONIS_hash = ();
 @DB_line = ();
 $homedir = $root_ ;
  open (DB, "$database") || die "Error opening database. $! $database \n";
 @DB_line = <DB>;
 close (DB);

foreach $adonis_record (@DB_line){
   chomp $adonis_record;
   @altro =();
  ($key,$dbuser,$when_added,@altro) = split(/\|/, $adonis_record);
  $DBADONIS_hash{$key} = $adonis_record;
} ;
# end of creating of %adonis_hash

 $date_time = &get_date;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
# Format $dd,$mm numbers with up to 2 leading zeroes
$dd = sprintf("%02d", $dd);
$mm = sprintf("%02d", $mm);
 $day_time =~ s/[\:\.]/~/g;
 ($hour,$min,$sec) = split (/\~/,$day_time);
$hour = sprintf("%02d", $hour);
$min  = sprintf("%02d", $min);


 $backupdb = $root_ . "/detempore_backup/backup_clients" . $yy. "_". $mm ."_$dd" . ".txt";

  # save ADONIS records
  my @ADONIS_line = ();
  @ADONIS_line = values (%DBADONIS_hash);

 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$database") or die "Error opening file: $!\n";

  foreach $adonis_line (@ADONIS_line){ 
    chomp $adonis_line;
    print DATABASE "$adonis_line\n";
  }

  # backup ADONIS records
 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$backupdb") or die "Error opening file: $!\n";

  foreach $adonis_line (@ADONIS_line){ 
    chomp $adonis_line;
    print DATABASE "$adonis_line\n";
  }

  close (DATABASE);
  flock DATABASE, $UNLOCK;
  # end of backuping ADONIS records

  # save ADONIS records
  @ADONIS_line = ();
  @ADONIS_line = values (%DBADONIS_hash);

 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$database") or die "Error opening file: $!\n";

  foreach $adonis_line (@ADONIS_line){ 
    chomp $adonis_line;
    print DATABASE "$adonis_line\n";
  }

  close (DATABASE);
  flock DATABASE, $UNLOCK;
  # end of saving ADONIS db records



} # End of Backup_adonis subroutine.





































############### extract_mailinglist ################
sub extract_mailinglist{
# Author : John Jan Popovic
# Date : July, 2012
# Purpose: This procedure performs DBase adonis Backup



# Create %adonis_hash
 %DBADONIS_hash = ();
 @DB_line = ();
 $homedir = $root_ ;
  open (DB, "$database") || die "Error opening database. $! $database \n";
 @DB_line = <DB>;
 close (DB);

foreach $adonis_record (@DB_line){
   chomp $adonis_record;
   @altro =();
  ($key,$dbuser,$when_added,@altro) = split(/\|/, $adonis_record);
  $DBADONIS_hash{$key} = $adonis_record;
} ;
# end of creating of %adonis_hash




  # save MAILING LIST records
  my @ADONIS_line = ();
  @ADONIS_line = values (%DBADONIS_hash);
  $mailinglist = $root_ . "/detempore/detempore_mailinglist.txt";

 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$mailinglist") or die "Error opening file: $!\n";

  foreach $adonis_line (@ADONIS_line){ 
    chomp $adonis_line;
           ($key,$owner,$time_stamp,
            $CARD_Broj_kartice,$CARD_OIB,$CARD_Ime,$CARD_Prezime,
            $CARD_Datum_rodjenja,$CARD_Exp_date,$CARD_Bodovi,$CARD_Brand,$CARD_Email,$CARD_popup) = split (/\|/,$adonis_line);

    $mailing_line ="$CARD_Email|$key|$CARD_Ime $CARD_Prezime";
    print DATABASE "$mailing_line\n";
  }
  close (DATABASE);
  flock DATABASE, $UNLOCK;
  # end of saving MAILING LIST records





} # End of extract_mailinglist subroutine.






























































############# Email Billing  ################
sub mail_billing{
  my $search_for = $_[0]; 
  my $search_field = $_[1];
  my @results   =();
  my %shop_hash =();
  my $revenue=0;
  my $expenditure=0;

&html_header($title);

# build shop hash
  $database_shops    = "$ENV{'DOCUMENT_ROOT'}/detempore/detempore_shops.txt";	

  open (DB, "$database_shops") or die "Error opening database. $database_shops $!\n";
    while(<DB>){

   
           ($key,$owner,$time_stamp,
            $SHOP_Id, $SHOP_Pwd, $SHOP_salesPoint, $SHOP_address, $SHOP_telephone, $SHOP_email, $SHOP_GIS_coordinates, 
$SHOP_referral_person, $SHOP_contractNumber, $SHOP_activityStatus) = split(/\|/, $_);


          $SHOPId = $SHOP_Id;
          $SHOPId =~ s/\s//g;

          if ($SHOPId ne "") { 
             $shop_hash{$SHOP_Id} ="$SHOP_salesPoint - $SHOP_address";
          };


                
    } # End of while.
  close (DB);


 $date_time = &get_date;
 $datum =$date_time;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
# Format $dd,$mm numbers with up to 2 leading zeroes
$dd = sprintf("%02d", $dd);
$mm = sprintf("%02d", $mm);

    $billing_file = "$ENV{'DOCUMENT_ROOT'}/detempore_billing/billing" . $yy . "_". $mm .  ".txt";

 open (BILL, "$billing_file") or die "Error opening $billing_file  $!\n"; 
 @Billing_line = <BILL>;
 close (BILL);

  foreach $billing_record (@Billing_line){
    ($key,$LOGuser,$when_added,$detempore_Day,$detempore_TimeStamp,$detempore_TerminalId,$detempore_CardId,$detempore_Amount,$detempore_Reference) = split(/\|/, $billing_record);      
    if ($detempore_CardId =~ /$search_for/oi) { push @results,$billing_record};
  } # End of foreach

$count = @results;


  if ($count > 1) {
    $content = qq~<P>Total Found: <B>$count</B> billing records<BR>~;
  } 
  else { print qq~<P>Total Found: <B>1</B> billing record\n~; }
 


print "<br>";


$which_search = $choose;


    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE=\"$bodovi\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE=\"$email\">\n";

# end of Billing header
$content ="";

  foreach $record (@results){
    ($key,$LOGuser,$when_added,$julian_day,$timeStamp,$terminalId,$cardId,$amount,$reference) = split(/\|/, $record); 


     if ($amount > 0) {$revenue +=$amount}
     else {$expenditure +=$amount;}

$class="";


if ($amount < 0) {
  $class="class='textred'";
};

$content .=qq~
$red_font_on
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER $class >$timeStamp</TD>
   <TD width="20%" ALIGN="Right" $class>$terminalId</TD>
   <TD width="30%" ALIGN="Right" $class>$shop_hash{$SHOP_Id}</TD>
   <TD width="26%" ALIGN="Right" $class >$amount</TD>
   <TD width="26%" ALIGN="Right" $class >$reference</TD>
</TR>
$red_font_off
~;
     
  } # End of foreach loop.


$bodovi = sprintf("%.2f", $bodovi);

$revenue      = sprintf("%.2f", $revenue);
$expenditure  = sprintf("%.2f", $expenditure);

$billing_total = $revenue + $expenditure;
$billing_total = sprintf("%.2f", $billing_total);

$revenue       =~ s/\./\,/;
$expenditure   =~ s/\./\,/;
$billing_total =~ s/\./\,/;


$content .=qq~
$red_font_on
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER  >Ukupno sakupljeno bodova</b></TD>
<TD width="20%" ALIGN=CENTER></TD>
<TD width="30%" ALIGN=CENTER></TD>
   <TD width="26%" ALIGN="Right" >$revenue</TD>
</TR>
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER class="textred" >Ukupno potro&scaron;eno bodova</b></TD>
<TD width="20%" ALIGN=CENTER></TD>
<TD width="30%" ALIGN=CENTER></TD>
   <TD width="26%" ALIGN="Right" class="textred" >$expenditure</TD>
</TR>
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER  ><b>Grand Total</b></TD>
<TD width="20%" ALIGN=CENTER></TD>
<TD width="30%" ALIGN=CENTER></TD>
   <TD width="26%" ALIGN="Right" ><b>$billing_total</b></TD>
</TR>
$red_font_off
~;
   
$content .=qq~
</TR></TABLE>
~;




  if ($button_text eq "Modify Record") {
     print " <INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" > ";
  };




#  Billing header
$datum =~ s/at/ stanje u/;

$header = qq~
<br><br>
<p align="left">
<br>
Datum: $datum<br><br>
detempore korisnik: <B>$detempore_customer</B><br>
Broj_kartice: 	<B>$search_for</B><br><br>



Do danas ste skupili  <b>$bodovi </b> bodova.<br>

Dolje se nalazi ispis svih transakcija u $mm mjesecu. <br>
</p>
<br>
<br>
<TABLE BORDER=0 CELLSPACING=1 CELLPADDING=2 WIDTH=80%>
    <TR BGCOLOR="#e0e0e0">
<TD width="24%" ALIGN=CENTER><B>TimeStamp</B></TD>
<TD width="20%" ALIGN=CENTER><B>terminalId</B></TD>
<TD width="30%" ALIGN=CENTER><B>Sales point</B></TD>
<TD width="26%" ALIGN=CENTER><B>Amount</B></TD>
<TD width="26%" ALIGN=CENTER><B>Reference</B></TD>
</TR>

	
~;


print $header;
print $content;

$style =qq~
<head>
<style>  
.textorange{
	color: #D46300;
}
A.textorange:link {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:visited {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:active {
	color: #D46300;
	text-decoration: none;	
}


.textred{
	color: #ff0000;
}
A.textred:link {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:visited {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:active {
	color: #ff0000;
	text-decoration: none;	
}
</style>
<head>
~;

##########################################################################
#print " <br>SENDMAIL test";

$subject ="detempore billing report";

# sendmail setup
$SENDMAIL = "/usr/sbin/sendmail -t";
$FROM = "detempore testing <jjp\@testing.com>";
$TO = "$email";




open(MAIL, "|$SENDMAIL");


print MAIL <<EOM;
From: $FROM
To: $TO
Subject: $subject
Content-type: text/html; charset="iso-8859-1"
<html>
$style
<body>

$header
$content
<br>
$tx
<br>
Zahvaljujemo Vam na sudjelovanju u detempore programu vjernosti. 
</body>
</html>
EOM


close (MAIL);
##########################################################################

print "<p>";

&html_footer;
} # End of mail_billing subroutine.


















































########### Search Cards Database #############
sub search_cards{
  my $search_for   = $_[0];
  my $target_record ="";
  my @results =();
  my $cardId;

  $search_for =~ s/\s//g;
  $search_for =~ s/\D//g;

  
  open (DB, "$database") or die "Error opening database. $database $!\n";
    while(<DB>){

        ($key,$dbuser,$when_added,$CARD_Broj_kartice,
         $CARD_OIB,$CARD_Ime,$CARD_Prezime,$CARD_Datum_rodjenja,
         $CARD_Exp_date,$CARD_Bodovi,$CARD_Brand,$CARD_email,$CARD_popup) = split(/\|/, $_);

          $cardId = +$CARD_Broj_kartice;
          $cardId =~ s/\s//g;

          if ($cardId > 0) { 
             if ($cardId eq $search_for) { push @results, $_};
          };
           
    } # End of while.
  close (DB);

print "Content-type: text/html; charset=iso-8859-2\n\n";

my $count = @results;
if ($count < 1){ 
    $target_record =""; 
    $err_message="Error=100 Neregistrirana kartica $search_for"; 
}

if($count > 1){ 
    $target_record =""; 
    $err_message="Error=101 Too many results found for CardId $search_for"; 
}

if($count == 1){ 
    $target_record = @results[0];
    $err_message="";
};

# Print HTTP header for PLAIN TEXT
print "$CARD_Ime";

} # End of search_cards subroutine.
















########### Julian day #############
sub julian_day{
# The Julian day (jd) is computed from Gregorian date, month and year (d, m, y) as follows: http://en.wikipedia.org/wiki/Julian_day
# this code will stop working after 2100 , if you use format $dd/$mm/$yy
# but it will work correctly even after 2100 , if you use format $dd/$mm/$yyyy

use integer;
 my $datum = $_[0];
 my $jd;

 $datum =~ s/[\.\-]/\//g; # normalise: substitute dot and dash into slash
 ($dd,$mm,$yy) = split (/\//, $datum);

  if ($yy < 100) {$yy += 2000};
  $a1 =14 - $mm;
  $a = $a1/12.0;
  $y = $yy + 4800 - $a;
  $m = $mm +  12*$a - 3;  
  $j1 = 153*$m + 2;  
  $jd = $dd + $j1/5 + 365*$y + $y/4 - $y/100 + $y/400 - 32045;
  
  return $jd;

} # End of Julian day.












############# Results Screen ################
sub search_results{
&html_header($title);

  my $jd_today      =julian_day($date);

  $rows_left_to_view = $total_row_count - $new_hits_seen;
  $start_hit = $hits_seen + 1;
  $end_hit = $new_hits_seen;
  $hits_displayed = $end_hit - $start_hit + 1;
  if ($total_row_count > 1) {
    print qq~<P>Total Found: <B>$total_row_count</B> records<BR>~;
#    print qq~<P>restriction: <B>$expired_cards</B> <BR>~;
#    print qq~<P>restriction: <B>$soon_expiring</B> <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~; }
 
$cerca = $search_for;
print "<br>";


$which_search = $choose;

&next_page_buttons($rows_left_to_view);



    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"detempore_customer\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE='0'>\n";

if($display =~/columns/i) {
 print<<HTML;
	<p><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
    <TR BGCOLOR="#e0e0e0">
HTML
  if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit();\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='nuovo';this.form.submit();\" VALUE=\"aggiungere card\" >
</TD></TR>\n";

  }

  foreach $field (@fields){
    print "<TD ALIGN=CENTER><B>\u$field</B></TD>\n";
  } # End of foreach


  print "</TR>";
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 


    print "<TR BGCOLOR=\"#efefef\">\n";
    if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit();\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
</TD></TR>\n";
    } # End of if.
      for($x=0;$x<$field_count;$x++){
      $item = &check_item($field_vals[$x], $x);
      print "<TD>$item</TD>\n";
    }
     print "</TR> ";
  } # End of foreach loop.
  print<<HTML;
</TR></TABLE>
HTML
} else {
  foreach $record (@results){
   
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 

    my $expiery_date =$field_vals[5];
    my $jd_Exp_date =julian_day($expiery_date);
    my $delta = $jd_today - $jd_Exp_date;

# messages for expired or soon expires cards 
$expired_message ="";

$expired   ="no";
$ndays =-$delta;
if (($delta > - 40) && ($ndays >0)) {
  $expired_message ="expires within $ndays days";
  $expired   ="soon";
}



if ($delta > 0) {
  $expired_message ="already expired for $delta days";
  $expired   ="yes";
}

# end of messages for expired or soon expires cards 

$card = qq~<P><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>~;

   $x=0;
   foreach $field (@fields){
     ${$field} = $field_vals[$x];
     $x++;
   } 
  $x=0;
  foreach $field (@fields){
  $item = $field_vals[$x];

$background_color="#e0e0e0";
$line= "<TD BGCOLOR='#efefef' WIDTH=100%>$item</TD>";
if ($x > 9) {$background_color='#B6DB91'; $line= "<TD BGCOLOR='#D5FFD5' WIDTH=100%>$item</TD>" };

$campo = $field;

$card .=qq~
     <TR>
      <TD BGCOLOR=$background_color><B>\u$campo</B></TD>
      $line
     </TR>
~;
   $x++;
   } # End of foreach field loop.

    $detempore_customer ="$CARD_Ime $CARD_Prezime";


    chomp $CARD_Email;

$card .=qq|
<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
expired:$expired, $expired_message
           <INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Edit_opera';this.form.submit();\"  VALUE=\"Edit card\" >
           <INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Eliminate card\" >
           <INPUT TYPE=button  onClick=\"myForm.email.value='$CARD_Email';myForm.bodovi.value='$CARD_Bodovi';myForm.detempore_customer.value='$detempore_customer';myForm.search_for.value='$CARD_Broj_kartice';myForm.action.value='billing_report';this.form.submit();\" VALUE=\"Billing report\" > 
           <INPUT TYPE=button  onClick=\"myForm.email.value='$CARD_Email';myForm.bodovi.value='$CARD_Bodovi';myForm.detempore_customer.value='$detempore_customer';myForm.search_for.value='$CARD_Broj_kartice';myForm.action.value='email_billing';this.form.submit();\" VALUE=\"Email billing\" > 

</TABLE><P>
|;

if (($expired_cards  eq "expired_cards_only")  && ($expired eq "yes")){ print $card };
if (($soon_expiring eq "soon_expiring_only") && ($expired eq "soon")){ print $card };
if (($soon_expiring eq "") && ($expired_cards  eq "")){ print $card };


  } # End of foreach record loop.

} # End of if display loop

$which_search = $choose;

&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\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>";
$cerca_t=$cerca;
if ($cerca eq '.') {$cerca_t='tutto'};

&html_footer;
} # End of search_results subroutine.



























############### load_cards_screen ################
sub load_cards{

# Author : John Jan Popovic
# Date   : September MMXII 
# Purpose: This procedure performs UPDATES Cards DB from uploades CSV file


print "Content-type: text/html; charset=utf8 \n\n";

print<<HTML;


<HTML><HEAD>
 <meta http-equiv="content-type" content="text/html;  charset=utf8">
<title>$title</title>
   
  <link rel="stylesheet" href="$main_path/js/styles_ns.css">
  <style type="text/css">
<!--
.Stile1 {
	color: #FFFFFF;
	font-weight: bold;
}
-->
  </style>
</head>
load_cards ..<br>
HTML


# Create %Cards_hash
  %DBCards_hash = ();
  @Cards_line = ();
  $Cards_db   = $database;
  open (DBCards, "$Cards_db") || die "Error opening a input file $Cards_db  $!\n";
    @Cards_line = <DBCards>;
  close (DBCards);

foreach $site_record (@Cards_line){

   chomp $site_record;
   $site_record =~ s/"//g;
  ($key,$dbuser,$when_added,$CARD_Broj_kartice,$CARD_Tel,$CARD_Ime,$CARD_Prezime,$CARD_Datum_rodjenja,
   $CARD_Exp_date,$CARD_Bodovi,$CARD_Brand,$CARD_Email,$CARD_Popup_message,$CARD_Popup_autodelete,
   $CARD_Referral,$CARD_Limit,$CARD_Type,$CARD_Password ) = split(/\|/, $site_record);
  $CARD_Broj_kartice =~ s/http:\/\///;
  $DBCards_hash{$CARD_Broj_kartice} = $site_record;
} ;
# end of creating of %DBCards_hash


#Load_CSV csv file
  @db_csv =();
  $file_csv   = "$ENV{'DOCUMENT_ROOT'}/detempore/new_cards.csv"; 
  open (CSV, "$file_csv") || die "Error: The CSV file was not uploaded yet. Perform the UPLOAD, please. $file_csv  $!\n";
     @db_csv = <CSV>;
  close (CSV);

#Delete CSV file
  unlink $file_csv;
 
$RECORD_counter=0;

$key0 = time();
$dbuser="$admin_user_name";
$when_added = &get_date;
foreach $CSV_record (@db_csv){

  $key0++;
  if ($CSV_record =~ /\d/) {
    chomp $CSV_record;
    $CSV_record =~ s/\'//g;  # trim quotations
    $CSV_record =~ s/\"//g;    # trim quotations

  ($CARD_Broj_kartice,$CARD_Tel,$CARD_Ime,$CARD_Prezime,$CARD_Datum_rodjenja,
   $CARD_Exp_date,$CARD_Bodovi,$CARD_Brand,$CARD_Email,$CARD_Popup_message,$CARD_Popup_autodelete,
   $CARD_Referral,$CARD_Limit,$CARD_Type,$CARD_Password ) = split(/\;/, $CSV_record);

     print "$RECORD_counter Broj_kartice:$CARD_Broj_kartice ime: $CARD_Ime,$CARD_Prezime<br>\n";
     $card_record  ="$key0|$dbuser|$when_added|$CARD_Broj_kartice|$CARD_Tel|$CARD_Ime|$CARD_Prezime|";
     $card_record .="$CARD_Datum_rodjenja|$CARD_Exp_date|$CARD_Bodovi|$CARD_Brand|$CARD_Email|$CARD_Popup_message|";
     $card_record .="$CARD_Popup_autodelete|$CARD_Referral|$CARD_Limit|$CARD_Type|$CARD_Password|";

     if ($DBCards_hash{$CARD_Broj_kartice}  eq "") {
        $DBCards_hash{$CARD_Broj_kartice} =$card_record;
      }
      else {
        print "Error: Can not owerwrite existing record Broj_kartice:$CARD_Broj_kartice <br>\n";
      }

  }
  $RECORD_counter++;
} # terminate foreach
  

  # save updated Cards records
  @Cards_line = ();
  flock DBCards, $EXCLUSIVE;
  open (DBCards, ">$database") or die "Error opening file: $!\n";

  @Cards_line = values (%DBCards_hash);

  foreach $societa_line (@Cards_line){ 
    chomp $societa_line;
    print DBCards "$societa_line\n";
  }

  close (DBCards);
  flock DBCards, $UNLOCK;
  # end of saving Cards records

} # End of load_cards subroutine.






















############### UPLOAD Screen 1/2 ################
sub print_upload_1x_page{
$title="File Upload 1/2 ... Symphony";
$action="upload_2x";
if($set_cookie eq "") { print $q->header; }

 
 $path_ = "$root_/voltaire";
 $zy_name = "$path_/".$prefix ."a".$sufix."\.jpg"; 
 $zy_file = $prefix ."a".$sufix."\.jpg"; 
print<<BODY;
<HTML><HEAD>
 <TITLE>$db_name - $_[0]</TITLE>
 </HEAD><BODY BGCOLOR="#FFFFFF">
  <link rel="stylesheet" href="$main_path/js/styles_ns.css">
 <script language="javascript" src="$main_path/js/transfer_value.js"></script>
 <CENTER>
 $db_name
 <CENTER>
 <TABLE BORDER=1 WIDTH="$table_width" CELLSPACING="0" CELLPADDING="3">
 <TR> 
 <TD BGCOLOR="#e0e0e0"> 
 <CENTER> 
 <B>$title</B>
 </CENTER>
 </TD>
 </TR>
 <TR> 
 <TD align=middle><BR>

<FORM enctype="multipart/form-data" NAME="upload_1x" METHOD="post" ACTION="$upload_y_URL">

Server file:  $anno

<center>
<input type="file" name="myfile" accept="text/*" maxlength="2097152" size="60"><br>
<INPUT TYPE='submit' NAME='Submit' VALUE='UPLOAD file'>
</center>

 <BR></TD></TR>
 <TR> 
 <TD BGCOLOR="#e0e0e0"><CENTER> 
All rights reserved. 1stMuse Co
<input type=hidden name="user_search" value="">
<input type=hidden name="user_add" value="">
<input type=hidden name="user_modify" value="">
<input type=hidden name="user_delete" value="">
<INPUT TYPE="hidden" NAME="user" VALUE="">
<input type=hidden name="user_trans" value="">
<INPUT TYPE="hidden" NAME="authenticate" VALUE="yes">
<INPUT TYPE="hidden" NAME="message" VALUE=''>
<INPUT TYPE="hidden" NAME="file_name_convention" VALUE='Zy009876.jpg'>
 </CENTER>
 </TD>
 </TR>
</TABLE><P>
<center><p>All rights reserved. <a href="http://www.1stmuse.com">1stMuse</a><br>&copy; MMX 1stMuse &copy; MMX JJP<br><br></center>

</BODY></HTML>

BODY

}
############# end of UPLOAD Screen 1/2 ################


























############### ajax_addtocart ################
sub ajax_addToCart {

my $broj_kartice = $_[0];
my $product_key  = $_[1];
my $price        = $_[2];

my %adonis_hash = ();
my @adonis_records = ();
my @field_vals = ();
my $error;
my $card_number;

chomp $price;

print "Content-type: text/plain; charset=utf8\r\n\r\n";
############## Delete Record #################
# print "testing broj_kartice $broj_kartice  product_key $product_key  price $price end ";


# build %adonis_hash
 open (DATABASE, "$database") or die "Error opening file: $!\n";
 while (<DATABASE>)  {
   $line = $_;
   chop $line;
   @dbfields = ();
   ($key_,$dbuser,$when_added,$card_number,@resto) = split (/\|/, $line);
   if ($card_number ne "") { $adonis_hash{$card_number} = $line;}
 } #end of while
 close (DATABASE);
 
 $kljuc +=0;
 if ($broj_kartice ne "") {
 	
$key_record = $adonis_hash{$broj_kartice};
#  print "test $key_record";

($key,$dbuser,$when_added,
$CARD_Broj_kartice,
$CARD_Tel,
$CARD_Ime,
$CARD_Prezime,
$CARD_Datum_rodjenja,
$CARD_Exp_date,
$CARD_Bodovi,
$CARD_Brand,
$CARD_Email,
$CARD_Popup_message,
$CARD_Popup_autodelete,
$CARD_Referral,
$CARD_Limit,
$CARD_Type,
$CARD_Password, 
$CARD_Cart,
$CARD_Address,
$CARD_New_order,
$CARD_Spol
) = split(/\|/, $key_record); 

        $card_number  =$CARD_Broj_kartice;

   	$bodovi_na_kartici  = $CARD_Bodovi;
        $bodovi_na_kartici  =~ s/\,/\./g;
        $price              =~ s/\,/\./g;
        if ($bodovi_na_kartici >= $price) {
            $bodovi_na_kartici  = $bodovi_na_kartici - $price;
            $bodovi_na_kartici  = sprintf("%.2f", $bodovi_na_kartici);
        } 
        else {
            $error ="error";
        };
        $bodovi_na_kartici  =~ s/\./\,/g;
        $CARD_Bodovi = $bodovi_na_kartici;
        #print "testing CARD_Bodovi $CARD_Bodovi  end ";


   	$Cart_  =$CARD_Cart;
        chomp $Cart_;
        $Cart_  .= "1;$product_key;$price:";
        $Cart_ = compact_cart($Cart_);
        #print "testing Cart1 $Cart_  end ";


 $updated_record=$key;
 $updated_record .= "\|$user";
 $updated_record .= "\|$when_added";
 
 $updated_record .= "\|$CARD_Broj_kartice";
 $updated_record .= "\|$CARD_Tel";
 $updated_record .= "\|$CARD_Ime";
 $updated_record .= "\|$CARD_Prezime";
 $updated_record .= "\|$CARD_Datum_rodjenja";
 $updated_record .= "\|$CARD_Exp_date";
 $updated_record .= "\|$CARD_Bodovi";
 $updated_record .= "\|$CARD_Brand";
 $updated_record .= "\|$CARD_Email";
 $updated_record .= "\|$CARD_Popup_message";
 $updated_record .= "\|$CARD_Popup_autodelete";
 $updated_record .= "\|$CARD_Referral";
 $updated_record .= "\|$CARD_Limit";
 $updated_record .= "\|$CARD_Type";
 $updated_record .= "\|$CARD_Password"; 
 $updated_record .= "\|$Cart_";



$adonis_hash{$card_number} = $updated_record;
#$adonis_hash{$broj_kartice} = $updated_record;
}

 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$database") or die "Error opening file: $!\n";
 
   @adonis_records = values (%adonis_hash);

  # save adonis records
  foreach $line (@adonis_records){ 
    chomp $line;
    print DATABASE "$line\n";
  }

 close (DATABASE);
 flock DATABASE, $UNLOCK;
 
 if ($error eq "") {
   print "$bodovi_na_kartici~$Cart_";
 }
 else {
   print "NEDOVOLJNO $bodovi_na_kartici~$Cart_";
 }

}
############# end of ajax_addtocart ################





sub compact_cart{
my $cart_content = $_[0];
my %product_hash = ();
my %q_hash = ();
my @cart_items = ();
my $key;
my $item;

   @cart_items = split("\:", $cart_content);

#  built %product_hash
   foreach $item (@cart_items){
      ($quantity, $name, $price) = split("\;", $item);
       $key = $name . $price;
       $key =~ s/\s//g;
       $key =~ s/\.//g;
       $key =~ s/\,//g;
       $q_hash{$key} +=$quantity;
       $q = $q_hash{$key};
       $product_hash{$key} ="$q\;$name\;$price";
   }
   
   @cart_items = ();
   $compact_content ="";
   @cart_items   = values(%product_hash);
   foreach $item (@cart_items){     
       $compact_content .="$item:";
   }
       
   return $compact_content;
} # End of compact_cart





















############### ajax_confirmcart ################
sub ajax_confirmCart {

my $broj_kartice = $_[0];


my %adonis_hash = ();
my @adonis_records = ();
my @field_vals = ();
my $error;
my $card_number;


print "Content-type: text/plain; charset=utf8\r\n\r\n";
############## Delete Record #################
#print "testing confirmCart .. broj_kartice $broj_kartice   end ";

  
# build %adonis_hash
 open (DATABASE, "$database") or die "Error opening file: $!\n";
 while (<DATABASE>)  {
   $line = $_;
   chop $line;
   @dbfields = ();
   ($key_,$dbuser,$when_added,$card_number,@resto) = split (/\|/, $line);
   if ($card_number ne "") { $adonis_hash{$card_number} = $line;}
 } #end of while
 close (DATABASE);
 
 $kljuc +=0;
 if ($broj_kartice ne "") {
 	
$key_record = $adonis_hash{$broj_kartice};
#  print "test $key_record";

($key,$dbuser,$when_added,
$CARD_Broj_kartice,
$CARD_Tel,
$CARD_Ime,
$CARD_Prezime,
$CARD_Datum_rodjenja,
$CARD_Exp_date,
$CARD_Bodovi,
$CARD_Brand,
$CARD_Email,
$CARD_Popup_message,
$CARD_Popup_autodelete,
$CARD_Referral,
$CARD_Limit,
$CARD_Type,
$CARD_Password, 
$CARD_Cart,
$CARD_Address,
$CARD_New_order,
$CARD_Spol
) = split(/\|/, $key_record); 

        $card_number  =$CARD_Broj_kartice;

   	$bodovi_na_kartici  = $CARD_Bodovi;
        $CARD_Bodovi = $bodovi_na_kartici;

   	$Cart_x  =$CARD_Cart;
        $Cart_  =""; # reset the cart

 $updated_record=$key;
 $updated_record .= "\|$user";
 $updated_record .= "\|$when_added";
 $updated_record .= "\|$CARD_Broj_kartice";
 $updated_record .= "\|$CARD_Tel";
 $updated_record .= "\|$CARD_Ime";
 $updated_record .= "\|$CARD_Prezime";
 $updated_record .= "\|$CARD_Datum_rodjenja";
 $updated_record .= "\|$CARD_Exp_date";
 $updated_record .= "\|$CARD_Bodovi";
 $updated_record .= "\|$CARD_Brand";
 $updated_record .= "\|$CARD_Email";
 $updated_record .= "\|$CARD_Popup_message";
 $updated_record .= "\|$CARD_Popup_autodelete";
 $updated_record .= "\|$CARD_Referral";
 $updated_record .= "\|$CARD_Limit";
 $updated_record .= "\|$CARD_Type";
 $updated_record .= "\|$CARD_Password";
 $updated_record .= "\|$Cart_";
 $updated_record .= "\|$CARD_Address";
 $updated_record .= "\|$CARD_New_order";
 $updated_record .= "\|$CARD_Spol";

$adonis_hash{$broj_kartice} = $updated_record;

}

 $error ="";

 # save adonis records
 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$database") or die "Error opening file: $!\n";
 @adonis_records = values (%adonis_hash);
  foreach $line (@adonis_records){ 
    chomp $line;
    print DATABASE "$line\n";
  }
 close (DATABASE);
 flock DATABASE, $UNLOCK;
 # end of saving


########## Email mail_cart_order  ################

 $date_time = &get_date;
 $datum =$date_time;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
# Format $dd,$mm numbers with up to 2 leading zeroes
$dd = sprintf("%02d", $dd);
$mm = sprintf("%02d", $mm);

 
$content ="";

$class="";




#  print "testing CARD_Bodovi $CARD_Bodovi customer: $CARD_Email end";

my @myrow;
my @mycol;

$content ="";
  $cx0 ='Naručeni su slijedeći darovi: <table width="60%" border="0" cellpadding="4">  <tr>  <td>&nbsp;</td> <td>   </td>  <td>&nbsp;</td> <td>&nbsp;</td>  </tr> ';
  $cx0 .='<tr> <td>n</td>  <td>loyalty gift</td>  <td>points</td> <td>subtotal</td>  </tr> ';

  $tx =$cx0;
  @myrow = split(/:/,$Cart_x );
  $total = 0.0;
  foreach $rx (@myrow) {
     $tx .='<tr>';
     @mycol = split(/;/,$rx);
     $subtotal = $mycol[0] * $mycol[2]; 
     foreach $col (@mycol) {
        $tx .= '<td>' . $col .'</td>';
     }
     $tx .='<td>' . $subtotal .'</td>';
     $tx .='</tr>'; 
     $total +=$subtotal;
  }
  $tx .= '</table><br>';


#  CartOrder header
$datum =~ s/at/, /;
$detempore_customer = "$CARD_Ime $CARD_Prezime";

$header = qq~
<br><br>
<p align="left">
<br>
Datum: $datum<br><br>
Loyalty korisnik: <B>$detempore_customer</B><br>
Broj_kartice: 	<B>$CARD_Broj_kartice</B><br><br>
<br>
	
~;



$style =qq~
<head>
<style>  
.textorange{
	color: #D46300;
}
A.textorange:link {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:visited {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:active {
	color: #D46300;
	text-decoration: none;	
}


.textred{
	color: #ff0000;
}
A.textred:link {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:visited {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:active {
	color: #ff0000;
	text-decoration: none;	
}
</style>
<head>
~;
##########################################################################


$subject ="narudžba loyalty nagrada";

# sendmail setup
$SENDMAIL = "/usr/sbin/sendmail -t";
$FROM = "detempore testing2 <jjp\@testing.com>";
#$TO = "$loyalty_orders_email";
$TO = $CARD_Email;

open(MAIL, "|$SENDMAIL");


print MAIL <<EOM;
From: $FROM
To: $TO
Subject: $subject
Content-type: text/html; charset="utf8"
<html>
$style
<body>

$header
$content

<br>
$tx
<br>
Zahvaljujemo Vam na sudjelovanju u detempore programu vjernosti. 
</body>
</html>
EOM


close (MAIL);

########## End of mail_cart_order
$error ="";


 if ($error eq "") {
   print "$CARD_Bodovi~Zahvaljujemo Vam na sudjelovanju u detempore programu vjernosti";
 }


}
############# end of ajax_confirmcart ################



























############### ajax_cancelCart ################
sub ajax_cancelCart {

my $broj_kartice = $_[0];


my %adonis_hash = ();
my @adonis_records = ();
my @field_vals = ();
my $error;
my $card_number;


print "Content-type: text/plain; charset=utf8\r\n\r\n";
############## Delete Record #################
  
# build %adonis_hash
 open (DATABASE, "$database") or die "Error opening file: $!\n";
 while (<DATABASE>)  {
   $line = $_;
   chop $line;
   @dbfields = ();
   ($key_,$dbuser,$when_added,$card_number,@resto) = split (/\|/, $line);
   if ($card_number ne "") { $adonis_hash{$card_number} = $line;}
 } #end of while
 close (DATABASE);
 
 $kljuc +=0;
 if ($broj_kartice ne "") {
 	
$key_record = $adonis_hash{$broj_kartice};
#  print "test $key_record";

($key,$dbuser,$when_added,
$CARD_Broj_kartice,
$CARD_Tel,
$CARD_Ime,
$CARD_Prezime,
$CARD_Datum_rodjenja,
$CARD_Exp_date,
$CARD_Bodovi,
$CARD_Brand,
$CARD_Email,
$CARD_Popup_message,
$CARD_Popup_autodelete,
$CARD_Referral,
$CARD_Limit,
$CARD_Type,
$CARD_Password, 
$CARD_Cart,
$CARD_Address,
$CARD_New_order,
$CARD_Spol
) = split(/\|/, $key_record); 






my @myrow;
my @mycol;

$Cart_x  =$CARD_Cart;


  @myrow = split(/:/,$Cart_x );
  $total = 0.0;
  foreach $rx (@myrow) {
     @mycol = split(/;/,$rx);
     $subtotal = $mycol[0] * $mycol[2];
     $total +=$subtotal;
  }


        $card_number  =$CARD_Broj_kartice;

   	$bodovi_na_kartici  = $CARD_Bodovi;
        $bodovi_na_kartici  =~ s/\,/\./g;
        $CARD_Bodovi = $bodovi_na_kartici + $total;

 
        $Cart_  =""; # reset the cart

 $updated_record=$key;
 $updated_record .= "\|$user";
 $updated_record .= "\|$when_added";
 $updated_record .= "\|$CARD_Broj_kartice";
 $updated_record .= "\|$CARD_Tel";
 $updated_record .= "\|$CARD_Ime";
 $updated_record .= "\|$CARD_Prezime";
 $updated_record .= "\|$CARD_Datum_rodjenja";
 $updated_record .= "\|$CARD_Exp_date";
 $updated_record .= "\|$CARD_Bodovi";
 $updated_record .= "\|$CARD_Brand";
 $updated_record .= "\|$CARD_Email";
 $updated_record .= "\|$CARD_Popup_message";
 $updated_record .= "\|$CARD_Popup_autodelete";
 $updated_record .= "\|$CARD_Referral";
 $updated_record .= "\|$CARD_Limit";
 $updated_record .= "\|$CARD_Type";
 $updated_record .= "\|$CARD_Password"; 
 $updated_record .= "\|$Cart_";

$adonis_hash{$broj_kartice} = $updated_record;

}

 $error ="";

 # save adonis records
 flock DATABASE, $EXCLUSIVE;
 open (DATABASE, ">$database") or die "Error opening file: $!\n";
 @adonis_records = values (%adonis_hash);
  foreach $line (@adonis_records){ 
    chomp $line;
    print DATABASE "$line\n";
  }
 close (DATABASE);
 flock DATABASE, $UNLOCK;
 # end of saving



$error ="";


 if ($error eq "") {
   print "$CARD_Bodovi~Odustali ste od narudžbe. Povraćeni su vam bodovi. Zahvaljujemo Vam na sudjelovanju u detempore programu vjernosti.";
 }


}
############# end of ajax_cancelcart ################



















sub luhn_algorithm{
my $last_number = $_[0];

 print "current card number: $last_number<br>\n";

            my $sum = 0;
            my $alt = 1;
            my @digits =split(//, $last_number);
            $digits_length =@digits;

            for ($i = $digits_length - 1; $i >= 0; $i--) {
                $curDigit = @digits[$i];
                #print "curDigit: $curDigit .. \n";

                if ($alt == 1) {
                    $curDigit *= 2;
                    if ($curDigit > 9)  {
                        $curDigit -= 9;
                    };
                    $alt = 0;
                }
                else {
                    $alt = 1;
                };
                #print " $curDigit .. \n";
                $sum += $curDigit;
                #print ".. sum: $sum .. <br>\n";
            }

            if (($sum  % 10) == 0 )  {
                $luhn =  "0";
            }
            else {
            	$luhn = (10 - ($sum % 10));
            };

            print "Luhn checkdigit: $luhn .. \n";
            return $luhn;
        
   #return $last_number;
} # End of luhn_algorithm






############### Increment Counter ################
sub increment_nx_counter{
  open (COUNT_FILE, "+<$luhn_counter") || die "Error opening $luhn_counter  $!\n";
  while (<COUNT_FILE>) {
  chop($_);
  ($numero, @other_counter_fields) = split(/\|/, $_);
  }; # End of While
    seek (COUNT_FILE, 0, 0);
    $numero++;
    print COUNT_FILE ("$numero|");
    close (COUNT_FILE);
} #  End of Increment Counter 









################ new_orders
sub new_orders {
 html_header($title);
 
# Create %orders_hash
 my %orders_hash = ();
 my @DB_line = ();
 $homedir = $root_ ;
  open (DB, "$database") || die "Error opening database. $! $database \n";
  @DB_line = <DB>;
 close (DB);



# extract NEW ORDERS
foreach $adonis_record (@DB_line){
   chomp $adonis_record;
   @altro =();
   my ($key,$dbuser,$when_added, $broj_kartice, $CARD_Tel, $CARD_Ime, $CARD_Prezime, @altro) = split(/\|/, $adonis_record);
  # Broj kartice;Ime i prezime;Track1;Track2
  # 6048 65010 010821;Zdenka Lalić;6048 65010 010821;604865010010821     
   if ($adonis_record =~ /\|yes/) {
       pop(@altro);
       
       $left_substring    =substr($broj_kartice, 0, 4);
       $central_substring =substr($broj_kartice, 4, 5);
       $right_substring   =substr($broj_kartice, 9, 6);
       $space_delimited_number ="$left_substring $central_substring $right_substring";
       $csv_record =  "$space_delimited_number\;$CARD_Ime $CARD_Prezime\;$space_delimited_number\;$broj_kartice\;";
       $orders_hash{$key} = $csv_record; 
   };
};
 

 $date_time = &get_date;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
 # Format $dd,$mm numbers with up to 2 leading zeroes
 $dd = sprintf("%02d", $dd);
 $mm = sprintf("%02d", $mm);

 $day_time =~ s/[\:\.]/~/g;
 ($hour,$min,$sec) = split (/\~/,$day_time);
$hour = sprintf("%02d", $hour);
$min  = sprintf("%02d", $min);

 $new_order_csv = "$root_/detempore_new_orders/cards_new_order_" . $yy. "_". $mm . "_$dd" . ".csv";
 $new_order_url = "$main_path/detempore_new_orders/cards_new_order_" . $yy. "_". $mm . "_$dd" .  ".csv";

  my @ADONIS_line = ();
  @ADONIS_line = values (%orders_hash);

  print  qq~<p align="left">\n~;
  $csv_header =qq~Broj kartice;Ime i prezime;Track1;Track2~;
  unshift  @ADONIS_line, "$csv_header";
 

  open (my $fh, ">", $new_order_csv)   or die "Can't write file $new_order_csv $!";
  foreach $adonis_line (@ADONIS_line){ 
      print  "$adonis_line<br><br>\n";
      print  $fh "$adonis_line\n";
  }
  close $fh;

  $n_cards =@ADONIS_line;
  $n_cards--;

  print qq~<INPUT TYPE=button onClick="myForm.action.value='confirm_new';this.form.submit();" VALUE="Confirm new orders" > <br>~;

  print "<br>total new cards: $n_cards <br><br>\n";
  print qq~<a class="LeftNavLink" href="$new_order_url">New cards order - excel file</a></td>~;
 
 html_footer;

}










################ confirm_new 
sub confirm_new{
# 1. send the csv file via email
# 2. resave  the database where in all new orders is removed "yes"

 &html_header($title);
 

# send the csv file link via email 
 $date_time = &get_date;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
 # Format $dd,$mm numbers with up to 2 leading zeroes
 $dd = sprintf("%02d", $dd);
 $mm = sprintf("%02d", $mm);

  $day_time =~ s/[\:\.]/~/g;
 ($hour,$min,$sec) = split (/\~/,$day_time);
$hour = sprintf("%02d", $hour);
$min  = sprintf("%02d", $min);


 $new_order_csv = "$root_/detempore_new_orders/cards_new_order_" . $yy. "_". $mm ."_$dd" .  ".csv";
 $new_order_url = "$main_path/detempore_new_orders/cards_new_order_" . $yy. "_". $mm ."_$dd" . ".csv";

 $content = qq~<a class="LeftNavLink" href="$new_order_url">New order - excel file</a></td>~;
  

##########################################################################



$style =qq~
<head>
<style>  
.textorange{
	color: #D46300;
}
A.textorange:link {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:visited {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:active {
	color: #D46300;
	text-decoration: none;	
}


.textred{
	color: #ff0000;
}
A.textred:link {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:visited {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:active {
	color: #ff0000;
	text-decoration: none;	
}
</style>
<head>
~;

$header = qq~
<br><br>
<p align="left">
<br>
Datum: $datum<br><br>
detempore korisnik: <B>$detempore_customer</B><br>
Broj_kartice: 	<B>$search_for</B><br><br>



Do danas ste skupili  <b>$bodovi </b> bodova.<br>

Dolje se nalazi ispis svih transakcija u $mm mjesecu. <br>
</p>
<br>
<br>
<TABLE BORDER=0 CELLSPACING=1 CELLPADDING=2 WIDTH=80%>
    <TR BGCOLOR="#e0e0e0">
<TD width="24%" ALIGN=CENTER><B>TimeStamp</B></TD>
<TD width="20%" ALIGN=CENTER><B>terminalId</B></TD>
<TD width="30%" ALIGN=CENTER><B>Sales point</B></TD>
<TD width="26%" ALIGN=CENTER><B>Amount</B></TD>
<TD width="26%" ALIGN=CENTER><B>Reference</B></TD>
</TR>

	
~;





# end of send the email 


# sendmail setup


# lista sa naručenim karticama dolazi na :
# denis.prugovecki@etranet.hr;  tomislav.kulis@detempore.hr;tomislav.jezic@etranet.hr;john.jan.popovic@etranet.hr

$subject ="Maras new orders - new cards";

$SENDMAIL = "/usr/sbin/sendmail -t";
$FROM = "Etranet Loyalty <noreply\@etranet.hr>";
$TO   = "denis\.prugovecki\@etranet.hr,tomislav\.jezic\@etranet.hr,tomislav\.kulis\@detempore.hr,john\.jan\.popovic\@etranet.hr";
print "<br>Maras new card orders was sent to $TO ";

open(MAIL, "|$SENDMAIL");


print MAIL <<EOM;
From: $FROM
To: $TO
Subject: $subject
Content-type: text/html; charset="utf8"
<html>
$style
<body>
 
$content
<br>
 
 Kliknuti na link i preuzeti file s novo naručenim karticama. <br>
 File se mora importirati u Excel kao text UTF8 csv file.
</body>
</html>
EOM


close (MAIL);
##########################################################################



# re-save  the database where all new orders are reseted
 my %adonis_hash = ();
 my @DB_line = ();
  open (DB, "$database") || die "Error opening database. $! $database \n";
 @DB_line = <DB>;
 close (DB);


foreach $adonis_record (@DB_line){
   chomp $adonis_record;
   if ($adonis_record =~ /\|yes/) {
       $adonis_record =~ s/\|yes//i;
   };
   my ($key, @altro) = split(/\|/, $adonis_record);
   $adonis_hash{$key} = $adonis_record; 
};


  my @ADONIS_line = ();
  @ADONIS_line = values (%adonis_hash);
  open (my $fh, ">", $database)   or die "Can't write file $database $!";
  foreach $adonis_line (@ADONIS_line) { 
  	  #print  "<br>$adonis_line<br>\n";
      print  $fh "$adonis_line\n";
  }
  close $fh;
 # end of resaving the database


 &html_footer;

} # end of confirm_new











############### Modify Screen ################
sub print_modify_page{
  ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $results[0]); 
$title="Modify Record";
&html_header($title);
print<<HTML;

   <INPUT TYPE=HIDDEN NAME=key value="$key">
    <TABLE BORDER=0 CELLSPACING=0>
HTML
my  $x=0;
  foreach $field (@fields){

   $input_txt="<INPUT TYPE=TEXT NAME=\"$field\" VALUE=\"$field_vals[$x]\" SIZE=40  onkeydown=\"return tabOnEnter (this, event);\" >";
 
   $input_html=$input_txt;

    if ($field eq "CARD_New_order") {
      $input_txt="<INPUT TYPE=\"hidden\" NAME=\"CARD_New_order\" VALUE=\"$field_vals[$x]\"    >";
      $field="";
    };


      if ($field eq "CARD_Spol") {
      	
       my $selected_sex    = $field_vals[$x];
       chomp $selected_sex;
       
       my $selected_male   = "";
       my $selected_female = "";

        if ($selected_sex  eq "M") {
        	$selected_male ="SELECTED";
        }
        else {
        	$selected_female ="SELECTED";
        };
   

$input_html =qq~ <select name="CARD_Spol">
<option value="Ž" $selected_female >Ženski</option>
<option value="M" $selected_male >Muški</option>
</select>~;

    }; 
  

       print<<HTML;
        <TR>
         <TD><B>\u$field</B></TD>
         <TD>$input_html</TD>
         </TR>
HTML

    $x++;
  } # End of foreach.


print<<HTML;
       	</TABLE>
	<BR>
<INPUT TYPE=button  onClick=" myForm.action.value='Modify This Record';this.form.submit();"  VALUE="Save" >

   <P>

<SCRIPT LANGUAGE="JavaScript">

<!-- This script locksout <CR> i.e. Enter Key and requires the SUBMIT button to be clicked to send form -->
<!-- Begin

function tabOnEnter (field, evt) {
      var keyCode = document.layers ? evt.which : document.all ? 
     evt.keyCode : evt.keyCode;
      if (keyCode != 13)
        return true;
      else {
        getNextElement(field).focus();
        return false;
      }
}


function getNextElement (field) {
    var frm = field.form;
    var bIs = false;
    for (var e=0;e<frm.length;e++)  {
      if(frm[e].type!="hidden" && bIs) return frm.elements[e];
      if (field==frm[e]) bIs=true;
    }
}

//  End -->
</script>
HTML


&html_footer;
}






















############# Billing Results Screen ################
sub billing_results{
  my $search_for = $_[0]; 
  my $search_field = $_[1];
  my @results   =();
  my %shop_hash =();
  my %terminal_shopId =();
  my $revenue=0;
  my $expenditure=0;

&html_header($title);

# build shop hash
  $database_shops    = "$ENV{'DOCUMENT_ROOT'}/detempore/detempore_shops.txt";	

  open (DB, "$database_shops") or die "Error opening database. $database_shops $!\n";
    while(<DB>){


           ($key,$owner,$time_stamp,
            $SHOP_Id, $SHOP_Pwd, $SHOP_salesPoint, $SHOP_address, $SHOP_telephone, 
            $SHOP_email, $SHOP_GIS_coordinates, $SHOP_referral_person, 
            $SHOP_contractNumber, $SHOP_activityStatus) = split(/\|/, $_);


          $SHOPId = $SHOP_Id;
          $SHOPId =~ s/\s//g;

          if ($SHOPId ne "") { 
             $shop_hash{$SHOP_Id} ="$SHOP_salesPoint - $SHOP_address";
             #print "$SHOP_Id -> $SHOP_salesPoint - $SHOP_address\n<br>";
          };

                
    } # End of while.
  close (DB);






# build terminal hash
#print "<br>terminal hash\n<br>";
  $database_terminals    = "$ENV{'DOCUMENT_ROOT'}/detempore/detempore_terminals.txt";	

  open (DB, "$database_terminals") or die "Error opening database. $database_terminals $!\n";
    while(<DB>){
   
($key,$owner,$time_stamp,
$TERMINAL_Id, 	
$TERMINAL_Pwd,	
$TERMINAL_ShopId, 	
$TERMINAL_referral_person, 	
$TERMINAL_email,	
$TERMINAL_contractNumber,	
$TERMINAL_activityStatus
            ) = split(/\|/, $_);


          $TERMINALId = $TERMINAL_Id;
          $TERMINALId =~ s/\s//g;

          if ($TERMINALId ne "") { 
             $terminal_shopId{$TERMINALId} = $TERMINAL_ShopId;
              # print "$TERMINALId -> $TERMINAL_ShopId\n<br>";
          };

    } # End of while.
  close (DB);


 $date_time = &get_date;
 $datum =$date_time;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($dd,$mm,$yy) = split (/\~/,$date);
# Format $dd,$mm numbers with up to 2 leading zeroes
$dd = sprintf("%02d", $dd);
$mm = sprintf("%02d", $mm);

    $billing_file = "$ENV{'DOCUMENT_ROOT'}/detempore_billing/billing" . $yy . "_". $mm .  ".txt";

 open (BILL, "$billing_file") or die "Error opening $billing_file  $!\n"; 
 @Billing_line = <BILL>;
 close (BILL);

  foreach $billing_record (@Billing_line){
    ($key,$LOGuser,$when_added,$detempore_Day,$detempore_TimeStamp,$detempore_TerminalId,$detempore_CardId,
     $detempore_Amount,$detempore_Reference) = split(/\|/, $billing_record);      
    if ($detempore_CardId =~ /$search_for/oi) { push @results,$billing_record};
  } # End of foreach

$count = @results;


  if ($count > 1) {
    $content = qq~<P>Total Found: <B>$count</B> billing records<BR>~;
  } 
  else { print qq~<P>Total Found: <B>1</B> billing record\n~; }
 


print "<br>";


$which_search = $choose;


    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"bodovi\" VALUE=\"$bodovi\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE=\"$email\">\n";

# end of Billing header
$content ="";

  foreach $record (@results){
    ($key,$LOGuser,$when_added,$julian_day,$timeStamp,
     $terminalId, $cardId, $amount, $reference) = split(/\|/, $record); 


     if ($amount > 0) {$revenue +=$amount}
     else {$expenditure +=$amount;}

$class="";

$shopID = $terminal_shopId{$terminalId};

if ($amount < 0) {
  $class="class='textred'";
};

$amount      = sprintf("%.2f", $amount);
$amount      =~ s/\./\,/g;

$content .=qq~
$red_font_on
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER $class >$timeStamp</TD>
   <TD width="20%" ALIGN="Right" $class>$terminalId</TD>
   <TD width="30%" ALIGN="Right" $class> $shopID </TD>
   <TD width="30%" ALIGN="Right" $class>$shop_hash{$shopID}</TD>
   <TD width="26%" ALIGN="Right" $class >$amount</TD>
   <TD width="26%" ALIGN="Right" $class >$reference</TD>
</TR>
$red_font_off
~;
     
  } # End of foreach loop.


$bodovi = sprintf("%.2f", $bodovi);

$revenue      = sprintf("%.2f", $revenue);
$expenditure  = sprintf("%.2f", $expenditure);

$billing_total = $revenue + $expenditure;
$billing_total = sprintf("%.2f", $billing_total);

$revenue      =~ s/\./\,/g;
$expenditure  =~ s/\./\,/g;
$billing_total=~ s/\./\,/g;

$content .=qq~
$red_font_on
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER  >Ukupno sakupljeno bodova</b></TD>
<TD ALIGN=CENTER></TD>
<TD ALIGN=CENTER></TD>
<TD ALIGN=CENTER></TD>
   <TD width="26%" ALIGN="Right" >$revenue</TD>
</TR>
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER class="textred" >Ukupno potro&scaron;eno bodova</b></TD>
<TD ALIGN=CENTER></TD>
<TD ALIGN=CENTER></TD>
<TD ALIGN=CENTER></TD>
   <TD width="26%" ALIGN="Right" class="textred" >$expenditure</TD>
</TR>
<TR BGCOLOR="#e0e0e0">
   <TD width="24%" ALIGN=CENTER  ><b>Grand Total</b></TD>
<TD ALIGN=CENTER></TD>
<TD ALIGN=CENTER></TD>
<TD ALIGN=CENTER></TD>
   <TD width="26%" ALIGN="Right" ><b>$billing_total</b></TD>
</TR>
$red_font_off
~;
   
$content .=qq~
</TR></TABLE>
~;



#$content .=qq~ revenue=$revenue expenditure=$expenditure~;

  if ($button_text eq "Modify Record") {
     print " <INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" > ";
  };




#  Billing header
$datum =~ s/at/ stanje u/;

$header = qq~
<br><br>
<p align="left">
<br>
Datum: $datum<br><br>
detempore korisnik: <B>$detempore_customer</B><br>
Broj_kartice: 	<B>$search_for</B><br><br>



Do danas ste skupili  <b>$bodovi </b> bodova.<br>

Dolje se nalazi ispis svih transakcija u $mm mjesecu. <br>
</p>
<br>
<br>
<TABLE BORDER=0 CELLSPACING=1 CELLPADDING=2 WIDTH=80%>
    <TR BGCOLOR="#e0e0e0">
<TD width="24%" ALIGN=CENTER><B>TimeStamp</B></TD>
<TD width="10%" ALIGN=CENTER><B>terminalId</B></TD>
<TD width="10%" ALIGN=CENTER><B>shopId</B></TD>
<TD width="30%" ALIGN=CENTER><B>Sales point</B></TD>
<TD width="26%" ALIGN=CENTER><B>Amount</B></TD>
<TD width="26%" ALIGN=CENTER><B>Reference</B></TD>
</TR>

	
~;


print $header;
print $content;

$style =qq~
<HEAD>
 <meta http-equiv="content-type" content="text/html;  charset=utf8">
<style>  
.textorange{
	color: #D46300;
}
A.textorange:link {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:visited {
	color: #D46300;
	text-decoration: none;	
}

A.textorange:active {
	color: #D46300;
	text-decoration: none;	
}


.textred{
	color: #ff0000;
}
A.textred:link {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:visited {
	color: #ff0000;
	text-decoration: none;	
}

A.textred:active {
	color: #ff0000;
	text-decoration: none;	
}
</style>
<head>
~;

print "<p>";

&html_footer;
} # End of billing_results subroutine.




