#!/usr/bin/perl

###############################################
###                                                                                  
###     (c) 2012 John Jan Popovic, http://1stmuse.com   for Etranet                                    
###                                                                                 
###                                    
###                                                                             
###############################################

BEGIN {
    my $b__dir = (-d '/home/loyaltyh/perl'?'/home/loyaltyh/perl':( getpwuid($>) )[7].'/perl');
    unshift @INC,$b__dir.'5/lib/perl5',$b__dir.'5/lib/perl5/x86_64-linux-thread-multi',map { $b__dir . $_ } @INC;
}

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

use Encode;
use utf8;

###############################################
###                  Set Configurations Below
###############################################
### Specify LOG fields in the array below
# 1339496095|jjp|6/12/2012 at 05:14:55|213.147.121.164|62777|http://1stmuse.com/fido/pos_form.html|Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5|stat=2&cardId=62778409803000&posTerminalId=123456&amount=100&submit=Send


@fields = 
( 
"Scheme_Owner",
"Scheme_Title",
"Scheme_Periodicity",
"Scheme_ExpDate",
"Scheme_Cases_PopUp",
"Scheme_Cases_Point_upgrade",
"Scheme_Cases_Brand",
"Scheme_Point_Reset",
"Scheme_Additional_Rule"
);


### 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'};
### Specify the required fields below. This may be left empty 
@required = ();

### Specify the filtered words below.  This may be left empty 
@filter = ("word1","word2");



 $date_time = &get_date;
 $date_time =~ s/at/~/g;
 ($date,$day_time) = split (/\~/,$date_time);
 $date =~ s/[\s]//g;
 $date =~ s/[\/]/~/g;
 ($mm,$dd,$yy) = split (/\~/,$date);

$database   = "$ENV{'DOCUMENT_ROOT'}/fido/fido_schemas.txt";

$user_file   = "$ENV{'DOCUMENT_ROOT'}/fido/users.txt";			   # User file name and path

	   # This script name
$DB_name = "Fido Loyalty Schemas";	   # 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 = "120";	  	   # 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
@extra_user_fields = ("Email");	   	   # Additional info needed when registering users
$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";
$image_path = 'http://1stmuse.com/opere';

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


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

$q = new CGI;
$field_count = @fields;
$colspan = $field_count+1;
$EXCLUSIVE = 2;
$UNLOCK    = 8;
$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);
$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);
$scheme       = $q->param(scheme);
$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'};
########



########
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($action =~ /new_card/i){ &print_add_screen;} 
	elsif($action =~ /conferma opera/i){ &add_record; $message="Record Added"; $title="Main Menu"; &print_default($title, $message);}
	elsif($action =~ /modifica_opera/i){ $title="Modification Error"; $error_message="You forgot to select a record to modify!"; &access_problem if($key < 1); &search_log($key);  &print_modify_page;}
	elsif($action =~ /modify this record/i){ $title="Modify"; &delete_records; $key=$keys[0]; &add_record; &print_back;}
	elsif($action =~ /conferma_modifica/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_log($search_for); $title="Modify Which Record?"; $button_text="Modify Record"; $choose="modify"; &search_results;}
	elsif($action =~ /delete/i){ &search_log($search_for); $title="Delete Which Record?"; $button_text="Elimina card"; $choose="delete"; &search_results;}
	elsif($action =~ /search/i){ &search_log($search_for); $title="Search Results"; $button_text = "";  $choose="search"; $what="search"; &search_results;}

	elsif($action =~ /update_scheme_messages/i){ $title="Schemas Message Trigger";$message="Popup poruke o nagradama su pohranjene"; &apply_schema_on_cards; &print_default($title, $message);}
	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;}
	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();

  $residum = $key % 43200;
  $dan = ($key - $residum) / 43200;

  $record=$key;
  $record  .= "\|$user";
  $record  .= "\|$when_added";

  foreach $field (@fields){ ${$field}  = $q->param($field); ${$field}  = filter(${$field}); $record  .= "\|${$field}"; }
   unless (-e $database){ open (LOG, ">$database") || die "Error creating database.  $!\n"; }
   else { open (LOG, ">>$database") || die "Error opening database.  $!\n"; }
   flock LOG, $EXCLUSIVE;
   seek LOG, 0, 2;
   print LOG "$record\n";
   flock LOG, $UNLOCK;
  close(LOG);
} # End of add_record subroutine.




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

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

&html_header($title);
  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;
$input_provenienza="<SELECT NAME=\"$field\"  onkeydown=\"return tabOnEnter (this, event);\"  >
<OPTION VALUE='già opera'>già opera<OPTION VALUE='Fiera'>Fiera<OPTION VALUE='per conoscenza'>per conoscenza
<OPTION VALUE='pagine gialle'>pagine gialle<OPTION VALUE='Internet'>Internet</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="Conferma card" >

         </CENTER>
        </TD>
       </TR>
      </TABLE>
     <P>
    </FONT>
<SCRIPT LANGUAGE="JavaScript" >
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// ===================================================================

//-------------------------------------------------------------------
// getElementIndex(input_object)
//   Pass an input object, returns index in form.elements[] for the object
//   Returns -1 if error
//-------------------------------------------------------------------
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;
	}

// -------------------------------------------------------------------
// tabNext(input_object)
//   Pass an form input object. Will focus() the next field in the form
//   after the passed element.
//   a) Will not focus to hidden or disabled fields
//   b) If end of form is reached, it will loop to beginning
//   c) If it loops through and reaches the original field again without
//      finding a valid field to focus, it stops
// -------------------------------------------------------------------
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;
    @LOGfields = split (/\|/, $line);
    $deleted = "no";
    if ($LOGfields[0] eq $q->param(key)) { $deleted = "yes"; if ($user eq $LOGfields[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accesso 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>
        
        </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_log{
  my $search_for = $_[0];
   unless (-e $database){ open (LOG, ">$database") || die "Error creating database.  $!\n"; }
   else { open (LOG, "$database") || die "Error opening database.  $!\n"; }
    while(<LOG>){
      if($search_field =~ /all/i) {

          if (/$search_for/oi){ push @results, $_};

      } else {
        ($key,$LOGuser,$when_added,@field_vals) = split(/\|/, $_);
        
          if ($field_vals[$search_field] =~ /$search_for/oi) { push @results, $_};

      } # End of else.
    } # End of while.
  close (LOG);
  foreach $curr (@results){
    ($key,$LOGuser,$when_added,@rest) = split(/\|/, $curr);
     $max = @fields;
     $code='$record{$key} = { key => "$key", ';
     $code .='LOGuser => "$LOGuser", ';
     $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->{LOGuser}";
    $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_log 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);
}



################### 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, @extra_user_fields) = 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
  foreach $extra (@extra_user_fields){
    print "<TR><TD><B>\u$extra</B><BR><INPUT TYPE=\"text\" NAME=\"$extra\" SIZE=\"30\"></TD></TR>";
  }
 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', @extra_user_fields);
    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>
HTML
  foreach $extra (@extra_user_fields){
    print "<TR><TD><B>\u$extra</B><BR><INPUT TYPE=\"text\" NAME=\"$extra\" SIZE=\"30\"></TD></TR>";
  }
 print<<HTML;
<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, @extra_user_fields) = 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
}
$extra_fields_count = @found_other_fields;
      for($x=0;$x<$extra_fields_count;$x++){
print "<TR><TD><B>\u$extra_user_fields[$x]</B><BR><INPUT TYPE=\"text\" NAME=\"$extra_user_fields[$x]\" SIZE=\"30\" value=\"$found_other_fields[$x]\"></TD></TR>";
    }
if ($perform eq "add") {
  foreach $extra (@extra_user_fields){
    print "<TR><TD><B>\u$extra</B><BR><INPUT TYPE=\"text\" NAME=\"$extra\" SIZE=\"30\"></TD></TR>";
  }
}
 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;
    @LOGfields = split (/\|/, $line);
    $deleted = "no";
    if ($LOGfields[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 = "$mon/$mday/$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\" > "; }
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";
}


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

sub html_header{
if($set_cookie eq "") { print $q->header; }
$set_cookie = "";
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>
   <TITLE>$DB_name - $_[0]</TITLE>
  </HEAD><BODY BGCOLOR="#FFFFFF">
  	<script language="javascript" src="$image_path/js/global.js"></script>	
	<script language="javascript" src="$image_path/js/style.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"> 
     <CENTER> 
          <B>$_[0]</B>
     </CENTER>
    </TD>
   </TR>
    <TR> 
     <TD align=middle><BR>
<script language=JavaScript>

</SCRIPT>
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\">LOGSpace</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;


<form name="myForm2">
<input type="hidden" value="Write"   onClick=document.myForm.elements[0].focus(); "> 
</form>

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







############ 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.











############### Modify Screen ################

sub print_modify_page{
  ($key,$LOGuser,$when_added,@field_vals) = split(/\|/, $results[0]); 
$title="Modify Record";
&html_header($title);
  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>


   <INPUT TYPE=HIDDEN NAME=key value="$key">
    <TABLE BORDER=0 CELLSPACING=0>
HTML
  $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;


       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>
HTML
&html_footer;
}








########### Capture amount #############
sub capture_amount{
   my $stranica = $_[0];
   if ($stranica =~ /amount\=\&/) {
     return "0";
   }
   else {
     $stranica =~ s/amount\=(.+?)\&//;  
     my $bodovi = $1;
     $bodovi =~ s/\s//g;
     $bodovi =~ s/\,/\./g;
     return $bodovi;
   }
}







############# Results Screen ################
sub search_results{
&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>Total Found: <B>1</B> record\n~; }
   # print "<br>in <b>$search_field_ </b> find<b> $find_ </b>";



$cerca = $search_for;
print "<br>";

   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 TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"scheme\" VALUE=''>\n";

############### end PRINT BUTTON which_search #######

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=\"Elimina 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,$LOGuser,$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=\"Elimina card\" >
</TD></TR>\n";
    } # End of if.
      for($x=0;$x<$field_count;$x++){
      $item = $field_vals[$x];



      print qq~<TD align="right">$item </TD>\n~;
    }
     print "</TR> ";
  } # End of foreach loop.
  print<<HTML;
</TR></TABLE>
HTML
} else {


  foreach $record (@results){
    ($key,$LOGuser,$when_added,@field_vals) = split(/\|/, $record); 

print<<HTML;
	<P><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
HTML

$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='#B6LOG91'; $line= "<TD BGCOLOR='#D5FFD5' WIDTH=100%>$item</TD>" };
if ($x > 20) {$background_color='#dcb691'; $line= "<TD BGCOLOR='#ffd5D5' 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.


$Scheme_Cases0 =$field_vals[4];
chomp $Scheme_Cases0;

$Scheme_Cases1 =$field_vals[5];
chomp $Scheme_Cases1;

$Scheme_Cases2 =$field_vals[6];
chomp $Scheme_Cases2;

$Scheme_Cases3 =$field_vals[7];
chomp $Scheme_Cases3;

$scheme_additional_rule =$field_vals[8];
chomp $scheme_additional_rule;

######## 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='modifica_opera';this.form.submit();\"  VALUE=\"Edit\" >
           <INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit();\"  VALUE=\"Delete\" >
           <INPUT TYPE=button  onClick=\"myForm.scheme.value='$Scheme_Cases0~$Scheme_Cases1~$Scheme_Cases2~$Scheme_Cases3~$scheme_additional_rule';myForm.search_field.value='all'; myForm.action.value='update_scheme_messages';this.form.submit();\"  VALUE=\"Update scheme messages\" >
          ";

};

 
  print "</TABLE><P>";

  }; # End of foreach record loop.

} # End of if display loop


  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=\"search_field\" VALUE=\"$search_field\">\n";
print "<p>";
$cerca_t=$cerca;
if ($cerca eq '.') {$cerca_t='tutto'};

&html_footer;
} # End of search_results subroutine.















########### Set Schema  #############
sub apply_schema_on_cards{
my %db_hash   = ();
my @CARD_line = ();

#$message = $scheme;

$database_cards    = "$ENV{'DOCUMENT_ROOT'}/fido/fido_clients.txt";	

 
  open (DB, "$database_cards") or die "Error opening database. $database_cards $!\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, $CARD_Popup_autodelete, $CARD_Referral , $CARD_Type ,$CARD_Password) = split(/\|/, $_);

          ($Scheme_Cases_PopUp,$Scheme_Cases_Point_upgrade,$Scheme_Cases_Brand,$Scheme_Point_Reset,$Scheme_Additional_Rule) =split(/\~/,$scheme);

          if ($key > 0)  {
            $updated_record  ="$key|$owner|$time_stamp|$CARD_Broj_kartice|$CARD_OIB|$CARD_Ime|$CARD_Prezime|$CARD_Datum_rodjenja|";
            $updated_record .="$CARD_Exp_date|$CARD_Bodovi|$CARD_Brand|$CARD_Email|$CARD_popup|$CARD_Popup_autodelete|$CARD_Referral|$CARD_Type|$CARD_Password";
            $db_hash{$key}  = $updated_record;
          };

# gleda se sakupljeni broj bodova na kartici i onda se još dodaju dodatni nagradni bodovi, prema pravilima definiranim u $Scheme_Cases_Point_upgrade
          $bonus_Bodovi = set_point_upgrade($CARD_Bodovi, $Scheme_Cases_Point_upgrade);
          $CARD_Bodovi += $bonus_Bodovi;

# gleda se sakupljeni broj bodova na kartici i onda se updatira record, odnosno setira se odgovarajuća PopUp poruka
          $CARD_popup  = set_popup_message($CARD_Bodovi, $Scheme_Cases_PopUp);

# gleda se sakupljeni broj bodova na kartici i onda se updatira record, odnosno setira se odgovarajuća BRAND poruka
          $CARD_Brand_previous =$CARD_Brand;
          $CARD_Brand = set_brand_message($CARD_Bodovi, $Scheme_Cases_Brand);

          if (($CARD_Brand_previous ne $CARD_Brand) && ($Scheme_Point_Reset =~ /yes/i)) {
              $CARD_Bodovi=0; # reset bodovi only if the brand was changed/upgraded and if $Scheme_Point_Reset ="yes"
          };

         
          $update_flag ="yes";
         # $update_flag = set_brand_message($CARD_Datum_rodjenja, $CARD_Brand,  $Scheme_Additional_Rule);
          if (($key >0) && ($update_flag eq "yes")) {
            $updated_record  ="$key|$owner|$time_stamp|$CARD_Broj_kartice|$CARD_OIB|$CARD_Ime|$CARD_Prezime|$CARD_Datum_rodjenja|";
            $updated_record .="$CARD_Exp_date|$CARD_Bodovi|$CARD_Brand|$CARD_Email|$CARD_popup|$CARD_Popup_autodelete|$CARD_Referral|$CARD_Type|$CARD_Password";
            $db_hash{$key}  = $updated_record;
          };
                
    } # End of while.
  close (DB);




                   # save DB records
                   @CARD_line = values (%db_hash);
                   flock DATABASE, $EXCLUSIVE;
                   open (DATABASE, ">$database_cards") or die "Error opening database: $database_cards $!\n";
                   foreach $adonis_line (@CARD_line){ 
                     chomp $adonis_line;
                     print DATABASE "$adonis_line\n";
                   }
                   flock DATABASE, $UNLOCK;             





} # End of apply_schema_on_cards subroutine.




























sub set_popup_message{
# returned PopUp message depends on number of points
# 100=Osvojili ste kapu!; 200=Osvojili ste kiobran!; 500=Ostvarujete popust 10% na slijede&#263;oj kupovini!
# 100=Osvojili ste kapu!
# 200=Osvojili ste kiobran!
# 500=Ostvarujete popust 10% na slijedećoj kupovini!

my $points = $_[0];
my $schema_ = $_[1];
my @case =();
my $message;
my $bodovi;
my $prix;


@case =split(/\//,$schema_);
$n =@case;

foreach $bod_prix (@case){
  ($bod, $prix)=split(/\=/,$bod_prix);
  if ($points >= $bod) {$message =$prix};
};

#if ($points >= 100) {$message ="Osvojili ste kapu!"};
#if ($points >= 200) {$message ="Osvojili ste kiobran!"};
#if ($points >= 500) {$message ="Ostvarujete popust 10% na slijede&#263;oj kupovini!"};

return $message;
}























sub set_brand_message{
# returned Brand message depends on number of points


my $points = $_[0];
my $schema_ = $_[1];
my @case =();
my $message;
my $bodovi;
my $prix;


@case =split(/\//,$schema_);
$n =@case;

$message ="";

foreach $bod_prix (@case){
  ($bod, $prix)=split(/\=/,$bod_prix);
  if ($points >= $bod) {$message =$prix};
};

#if ($points >= 100) {$message ="Silver"};
#if ($points >= 200) {$message ="Vip"};
#if ($points >= 500) {$message ="Platinum"};

return $message;
}







sub set_point_upgrade{
# additional bonus POINTS depend on number of points and reward roules: $schema_


my $points  = $_[0];
my $schema_ = $_[1];
my @case =();
my $add_points;
my $bodovi;
my $prix;


@case =split(/\//,$schema_);
$n =@case;

$add_points ="";

foreach $bod_prix (@case){
  ($bod, $prix)=split(/\=/,$bod_prix);
  if ($points >= $bod) {$add_points =$prix};
};

#if ($points >= 500)  {$add_points =50};
#if ($points >= 1000) {$message =150};


return $message;
}



