#! c:\perl\bin\perl
###########################################################################                              
###########################################################################
# Custimization portion - All Options are set in smart.cfg !!
###########################################################################

use Encode;
use LWP::Simple qw(get);

# Measure CPU time usage;
$start = (times)[0];
# Unbuffer the output;
$| = 1;

# Read in user prefs
require 'd:\xvrt\asturalba.com\html\smart.cfg';

##############################################################################
# Done. Make no changes below this line, unless you know what you are doing.##
##############################################################################
use vars qw($tmpdir $storename %shipping2 %shipping3 $trackurl $useverify $usertime $orderdir $usercurr $trackdb);
my($incoming, @pairs, %FORM);
$incoming = $ENV{'QUERY_STRING'};
#$incoming = $ENV{'PATH_INFO'};
@pairs = split(/&/, $incoming);
#@pairs = split(/\//, $incoming);
foreach $pair (@pairs) {
  my($name, $value) = split(/=/, $pair);
#  my($name, $value) = split(/\./, $pair);

  $value =~ tr/+/ /;
  $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  $FORM{$name} = $value;
}

# Get command variables
$command = $FORM{'command'};
$pos = $FORM{'pos'};
$type = $FORM{'type'};
$cmdlinegroup = $FORM{'group'};

# Parse form input
&parse_form;

# Get the date
&get_date;

# Get their hostname
#if ($usecookie eq '1') {
#require 'cookie.lib';
#&get_cookie;
#}
#else {

&get_host;

#}

# See if they have a cart already, if not, make one
&check_file;

# See what they want to do.

# Add an item to the cart.
if ($command eq 'add') {
&add_item;
}
# Change a quantity of an item in the cart, if at zero, delete it
elsif ($command eq 'change') {
&change_items;
}
# Show the order form. Get their name, phone number, CC info, etc..
elsif ($command eq 'buy1') {
&buy_items1;
}
# Process the order form info, mail out receipt, and order
elsif ($command eq 'buy2') {
&buy_items2;
}


# Show current cart
elsif ($command eq 'review') {
&review_items;
}
# List items, based on database call
elsif ($command eq 'listitems') {
&gen_page;
}
# Show a databae frontend. 
elsif ($command eq 'showstore') {
&show_store;
}
# Delete a whole cart
elsif ($command eq 'delete') {
&delete_cart;
}
else { &show_store; }
# Subroutines:

# Generate page, based on database search
sub gen_page {
my($SIZE,$i);
&print_header;
# Table header, change this for table options!
print "<center><table border=0 cellpadding=2>\n";
print "<tr>\n";

open (FILE,"$basepath$delim$resourcedb") || die "Content-type: text/html\n\nCan't Open $resourcedb(r): $!\n";
my(@LINES)=<FILE>;
close(FILE);
$SIZE=@LINES;

if ($type eq 'all') {
	my($max) = $pos + $numtolist;
	if ($max > $SIZE) {
	$max = $SIZE;
	}
	for ($i=$pos;$i<$max;$i++) {
   		$_=$LINES[$i];
		($itemid, $name, $price, $descrip, $image, $weight, $itemurl, $group) = split(/\|/,$_);
		&print_item;
		}
	print "</table>\n";
	if ($max < $SIZE) {
		print "<center><a href=\"$cgiurl\?command=listitems\&pos=$max&type=all\">Next $numtolist items</a></center>\n";
		}
	}

elsif ($type eq 'search') {
	my($matches) = 0;
	my($i) = $pos;
	while (($matches < $numtolist) && ($i < $SIZE)) {
		$_=$LINES[$i];
		if (index(lc $LINES[$i],lc $FORM{'search'}) >= 0) { 
			$matches++;
			($itemid, $name, $price, $descrip, $image, $weight, $itemurl, $group) = split(/\|/,$_);
			&print_item;
			}
		$i++;
		}
	print "</table>\n";
	if ($i < $SIZE) {
		print "<form method=post action=\"$cgiurl\?command=listitems\&pos=$i\&type=search\">\n";
		print "<input type=hidden name=itemid value=\"$itemid\">\n";
		print "<input type=hidden name=search value=\"$FORM{'search'}\">\n";
		print "<center><input type=submit value=\"Continue Search\"></form>\n";
		}
	}

elsif ($type eq 'group') {
	my($matches) = 0;
	my($i) = $pos;
	while (($matches < $numtolist) && ($i < $SIZE)) {
		$_=$LINES[$i];
		($itemid, $name, $price, $descrip, $image, $weight, $itemurl, $group) = split(/\|/,$_);
		my(@groups) = split(/,/,$group);
		undef %is_group;
		for (@groups) { $is_group{$_} = 1 }
		if ($is_group{$FORM{'group'}}) { 
			$matches++;
			&print_item;
			}
		$i++;
		}
	print "</table>\n";
	if ($i < $SIZE) {
			print "<a href=\"$cgiurl\?command=listitems\&pos=$i\&type=group\&group=$FORM{'group'}\">Continue Search</a>\n";
			}
	}

&print_footer;

# This is where you want to customize your generated pages!!
# Basically the top part will write out the header, then the table header
# Change the table header for options like spacing, borders, etc...

sub print_item {

print "<form method=post action=\"$cgiurl\?command=add\">\n";
# Hide the weight for later use
print "<input type=hidden name=weight value=\"$weight\">\n";
print "<input type=hidden name=itemid value=\"$itemid\">\n";

# For showing product images
if ($image) {
	print "<td bgcolor=#E1E1FF rowspan=2><img src=\"$imageurl/$image\" $imageopt></td>\n";
	}
	else {
		print "<td bgcolor=#E1E1FF rowspan=2></td>\n";
		}

# If the item has a URL, make it a link
if ($itemurl) {
	print "<td bgcolor=#E1E1FF><a href=\"$itemurl\">$name</a><input type=hidden name=itemname value=\"$name\"></td>\n";
	}
	else {
		print "<td bgcolor=#E1E1FF>$name<input type=hidden name=itemname value=\"$name\"></td>\n";
		}
		
# Print other info

#Price
print "<td bgcolor=#E1E1FF>$price €<input type=hidden name=itemprice value=\"$price\"></td>\n";

#Quantity
print "<td bgcolor=#E1E1FF><input type=text size=2 name=itemquant value=1></td>\n";

#Add button
print "<td rowspan=2 bgcolor=#E1E1FF><input type=submit value=\"Buy Me!\"></td>\n";

#Description
print "</tr><tr><td colspan=3 bgcolor=#E1E1FF>$descrip</td>\n";

# Close
print "</form></tr><tr>\n";
	
}
## END print_item

}
## END gen_page


# Show front end of database store.
sub show_store {
&print_header;
print "<center>\n";
print "<table width=80%><td bgcolor=#E1E1FF>\n";
print "<a href=\"$cgiurl\?command=listitems\&type=all\&pos=0\">List all items available</a><br>\n
<Br>\n
<table>
<td bgcolor=#E1E1FF>Search for a particular item(s):</td>
<td bgcolor=#E1E1FF>
<form method=post action=\"$cgiurl\?command=listitems\&pos=0\&type=search\">
<input type=text name=search size=30></td>
<td bgcolor=#E1E1FF><input type=submit value=Search></form></tD>
</table>\n";
print "<table>
<td bgcolor=#E1E1FF>List all:</td>
<td bgcolor=#E1E1FF>
<form method=post action=\"$cgiurl\?command=listitems\&pos=0\&type=group\">
<select name=group><option selected>Select a Group</option>\n";

foreach $group (keys %groups){
	print "<OPTION value=\"$group\"> $groups{$group} </option>\n";
    }

print "</select></td><td bgcolor=#E1E1FF>\n";

print "<center><input type=submit value=\"List\"</form></td>\n</table>\n<br>";

if ($usetrack eq 1) {
	print "<br><a href=\"$trackurl\">Track an Order</a><br>\n";
	}

print "</td></table>\n";
&print_footer;
}
## END show_store

# Print the HTML header
sub print_header {
print "Content-type: text/html\n\n";
open (HEADER,"$basepath$delim$header") || print "Could not open $basepath$delim$header $! \n";
while (<HEADER>) {
print $_;
	}
close(HEADER);	
}
## END print_header;

#Print the HTML footer
sub print_footer {
open (FOOTER,"$basepath$delim$footer") || print "Could not open $basepath$delim$footer $! \n";
while (<FOOTER>) {
print $_;
	}
close(FOOTER);	
}
## END print_footer

##########  LISTA ARTICULOS DEL CARRO EN LA PANTALLA Y FORMULARIO DE COMPRA #########
sub list_items {
my($totalprice,$totalquant,$totalweight) = 0;
open (REFFILE,"$reffile") || die "Content-type: text/html\n\nCan't Open $reffile(r): $!\n";
my(@LINES)=<REFFILE>;
close(REFFILE);
$SIZE=@LINES;

print "<form name=select1 method=POST action=\"$cgiurl?command=change\">\n";
#print "<table border=0 align=center cellpadding=2><tr>\n";

if ($useimage eq '1') {
	print "<th></th>";
	}
	
if ($useid eq '1') {
	print "<th>Item ID</th>";
	}

#print "<th bgcolor=#000080><font color=#FFFFFF>Artículo</font></th><th bgcolor=#000080><font color=#FFFFFF>Precio</font></th><th bgcolor=#000080><font color=#FFFFFF>Cantidad</font></th><th bgcolor=#000080><font color=#FFFFFF>Total</font></th></tr>";


print "<div class='cabecera'><div class='nombre'>Artículo</div><div class='borrar'><span class='extradesc'>Eliminar</span></div><div class='unitario'>Precio</div>";
print "<div class='cantidad'>Unidades</div><div class='actualizar'><span class='extradesc'>Actualizar</span></div><div class='total'>Total</div></div>";




	$_=$LINES[0];
	($udate, $uhost, $uagente, $unose, $gastosenvio) = split(/\|/,$_);

for ($i=1;$i<$SIZE;$i++) {
	$_=$LINES[$i];
	($itemname, $itemprice, $itemquant, $weight, $itemid) = split(/\|/,$_);
	$tmpprice = ($itemprice*$itemquant);
	$tmpprice = int($tmpprice * (10 ** 2) + .5) / (10 ** 2);
####	$itemptas = $tmpprice * 166.386;
####	$itemptas = int($itemptas * (10 ** 0) + .5) / (10 ** 0);
	$totalprice += $tmpprice;
	$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
####	$totalptas = $totalprice * 166.386;
####	$totalptas = int($totalptas * (10 ** 0) + .5) / (10 ** 0);
####	$totalquant += $itemquant;
####	$totalweight = ($weight*$itemquant) + $totalweight;
	#####print "<tr>";

if ($useimage eq '1') {
	if ($FORM{'image'}) {
		print "<td bgcolor=#E1E1FF><img src=\"$imageurl/$image\"></td>\n";
		}
	else {
		print "<td bgcolor=#E1E1FF></td>";
		}
	}
	
if ($useid eq '1') {
	print "<td bgcolor=#E1E1FF>$itemid <input type=hidden name=itemid value=\"$itemid\"></td>\n";
	}

# print "<td bgcolor=#E1E1FF><font face=Arial size=2>$itemname</font></td><td bgcolor=#E1E1FF align=right><font face=Arial size=2>$itemprice&nbsp;€</font></td><td bgcolor=#E1E1FF align=center><input type=number size=5 value=\"$itemquant\" name=item$i></td><td bgcolor=#E1E1FF align=right><font face=Arial size=2>$tmpprice&nbsp;€</font></tr>\n";
print "<div class='articulo'><div class='nombre'>$itemname</div><div class='unitario'>$itemprice&nbsp;€</div><div class='borrar'><img src='$iconoborrar' alt='Borrar' onclick=\"borrart('item$i')\"></div><div class='cantidad'><input value=\"$itemquant\" min=\"0\" id=\"item$i\" name=item$i type=\"number\"></div><div class='actualizar'><input type='image' src='$iconoactualizar' alt='Actualizar'></div><div class=\"precio\">$tmpprice€</div></div>\n";
}
#####print "<tr><td bgcolor=#E1E1FF><b>Subtotal:</b></td>";
#if ($useimage eq '1') {
#	print "<td bgcolor=#E1E1FF></td>";
#	}
#if ($useid eq '1') {
#	print "<td bgcolor=#E1E1FF></td>";
#	}
	
#####print "<td bgcolor=#E1E1FF></td><td bgcolor=#E1E1FF></td><td bgcolor=#E1E1FF align=right><b>$totalprice&nbsp;€</b></td></tr>\n";
#print "<div class='botonordenador'><button class='continue'>Continuar comprando</button><br></div>";

print "<div class='impuesto'><div class='iva'><div class='izq'>Subtotal</div><div class='dch'>$totalprice€</div></div></div>";

print "<div class='envio'><div class='peq'>¿Dónde tenemos que enviar el pedido?<br>Escoge la zona de envío:</div><br>";

print "<div class='forma'>";


#################################################################
######################## GASTOS DE ENVIO ########################
#################################################################
if ($shipping eq '2') {

#$portes = 6.90;
#$portesptas = $portes * 166.386;
#$portesptas = int($portesptas * (10 ** 0) + .5) / (10 ** 0);

&precioportes;

###$totalprice += $taxtotal;
#####print "<tr><td bgcolor=#E1E1FF><b>Gastos de envio:</b><select onchange='this.form.submit()' size='1' name='gastosenvio'>";
if ($gastosenvio eq 'Peninsula' || $gastosenvio eq '')
  {
  #####print "<option selected value='Peninsula'>España peninsula</option>
  #####<option value='Asturias'>Asturias</option>
  #####<option value='Canarias'>Canarias, Ceuta o Melilla</option>
  #####<option value='Baleares'>Baleares o Portugal</option>";
    print "<label><input id='envio-asturias' class='selenvio' type='radio' name='gastosenvio' value='Asturias' onclick='this.form.submit()'> Asturias <span class='iva'>3.90€</span></label><br>
         <label><input id='envio-peninsula' class='selenvio' type='radio' name='gastosenvio' value='Peninsula' onclick='this.form.submit()' checked = true> España península <span class='iva'>6.90€</span></label><br>
         <label><input id='envio-baleares' class='selenvio' type='radio' name='gastosenvio' value='Baleares' onclick='this.form.submit()'> Baleares o Portugal <span class='iva'>18.00€</span></label><br>
         <input id='envio-otros' class='selenvio' type='radio' name='gastosenvio' disabled='' value='Otros'> Otros <span class='iva'><strong><a href='http://www.asturalba.com/contactar.htm' target='_blank'>Consultar</a></strong></span>";       
  }
if ($gastosenvio eq 'Asturias')
  {
  #####print "<option value='Peninsula'>España peninsula</option>
  #####<option selected value='Asturias'>Asturias</option>
  #####<option value='Canarias'>Canarias, Ceuta o Melilla</option>
  #####<option value='Baleares'>Baleares o Portugal</option>";
 print "<label><input id='envio-asturias' class='selenvio' type='radio' name='gastosenvio' value='Asturias' onclick='this.form.submit()' checked = true> Asturias <span class='iva'>3.90€</span></label><br>
         <label><input id='envio-peninsula' class='selenvio' type='radio' name='gastosenvio' value='Peninsula' onclick='this.form.submit()'> España península <span class='iva'>6.90€</span></label><br>
         <label><input id='envio-baleares' class='selenvio' type='radio' name='gastosenvio' value='Baleares' onclick='this.form.submit()'> Baleares o Portugal <span class='iva'>18.00€</span></label><br>
         <input id='envio-otros' class='selenvio' type='radio' name='gastosenvio' disabled='' value='Otros'> Otros <span class='iva'><strong><a href='http://www.asturalba.com/contactar.htm' target='_blank'>Consultar</a></strong></span>";       
  }
if ($gastosenvio eq 'Baleares')
  {
  #####print "<option  value='Peninsula'>España peninsula</option>
  #####<option value='Asturias'>Asturias</option>
  #####<option value='Canarias'>Canarias, Ceuta o Melilla</option>
  #####<option selected value='Baleares'>Baleares o Portugal</option>";
 print "<label><input id='envio-asturias' class='selenvio' type='radio' name='gastosenvio' value='Asturias' onclick='this.form.submit()'> Asturias <span class='iva'>3.90€</span></label><br>
         <label><input id='envio-peninsula' class='selenvio' type='radio' name='gastosenvio' value='Peninsula' onclick='this.form.submit()'> España península <span class='iva'>6.90€</span></label><br>
         <label><input id='envio-baleares' class='selenvio' type='radio' name='gastosenvio' value='Baleares' onclick='this.form.submit()' checked = true> Baleares o Portugal <span class='iva'>18.00€</span></label><br>
         <input id='envio-otros' class='selenvio' type='radio' name='gastosenvio' disabled='' value='Otros'> Otros <span class='iva'><strong><a href='http://www.asturalba.com/contactar.htm' target='_blank'>Consultar</a></strong></span>";       
  }
if ($gastosenvio eq 'Canarias')
  {
  #####print "<option  value='Peninsula'>España peninsula</option>
  #####<option value='Asturias'>Asturias</option>
  #####<option selected value='Canarias'>Canarias, Ceuta o Melilla</option>
  #####<option value='Baleares'>Baleares o Portugal</option>";
 print "<label><input id='envio-asturias' class='selenvio' type='radio' name='gastosenvio' value='Asturias' onclick='this.form.submit()'> Asturias <span class='iva'>3.90€</span></label><br>
         <label><input id='envio-peninsula' class='selenvio' type='radio' name='gastosenvio' value='Peninsula' onclick='this.form.submit()'> España península <span class='iva'>6.90€</span></label><br>
         <label><input id='envio-baleares' class='selenvio' type='radio' name='gastosenvio' value='Baleares' onclick='this.form.submit()'> Baleares o Portugal <span class='iva'>18.00€</span></label><br>
         <input id='envio-otros' class='selenvio' type='radio' name='gastosenvio' disabled='' value='Otros'> Otros <span class='iva'><strong><a href='http://www.asturalba.com/contactar.htm' target='_blank'>Consultar</a></strong></span>";       
  }


#####print "</select></td>";

#####print "<td bgcolor=#E1E1FF></td><td bgcolor=#E1E1FF></td><td bgcolor=#E1E1FF align=right><b>$portes €</center></b></td></tr>\n";
        print "</div>
         <hr class='separador'>
         <div class='iva'><div class='izq'>Gastos de envío</div>
         <div class='dch'>$portes €</div><br></div>
         <br>
	</div>";




}
########################### IMPUESTOS ##########################
if ($tax eq '0') {
# print nothing
}
elsif ($tax eq '1') {
print "<tr><td bgcolor=#E1E1FF><b>I.V.A.:</b></td>";
if ($useimage eq '1') {
	print "<td bgcolor=#E1E1FF></td>";
	}
if ($useid eq '1') {
	print "<td bgcolor=#E1E1FF></td>";
	}
print "<td bgcolor=#E1E1FF align=center colspan=2>";
print "<select name=taxopt><option value=NULL>None</option>";
foreach $tax (keys %taxes) {
	print "<option ";
	if ($usertax eq $tax) { print "selected "; $totaltax=($totalprice*$taxes{$tax});$totalprice+=$totaltax;}
	print "value=$tax>$tax \+" . $taxes{$tax}*100 . "\% </option>";
	}
	print "</select></td>\n";

print "</td><td bgcolor=#E1E1FF align=right><b>$totaltax€</b></td></tr>\n";
}

elsif ($tax eq '2') {
$totalprice += $portes;
$taxtotal = $totalprice * $taxamt;
$taxtotal = int($taxtotal * (10 ** 2) + .5) / (10 ** 2);
#### $taxptas = $taxtotal * 166.386;
#### $taxptas = int($taxptas * (10 ** 0) + .5) / (10 ** 0);

$totalprice += $taxtotal;
#####print "<tr><td bgcolor=#E1E1FF><b>I.V.A. 21%</b></td>";
#if ($useimage eq '1') {
#	print "<td bgcolor=#E1E1FF></td>";
#	}
#if ($useid eq '1') {
#	print "<td bgcolor=#E1E1FF></td>";
#	}

#####print "<td bgcolor=#E1E1FF></td><td bgcolor=#E1E1FF></td><td bgcolor=#E1E1FF align=right><b>$taxtotal €</center></b></td></tr>\n";
print "<div class='impuesto'>
<div class='iva'><div class='izq'>IVA 21%</div><div class='dch'>$taxtotal €</div></div></div>";

}
$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
#### $totalptas = $totalprice * 166.386;
#### $totalptas = int($totalptas * (10 ** 0) + .5) / (10 ** 0);

#############################################################################
############## FIN DEL CALCULO DEL PRECIO TOTAL DE LA COMPRA  ###############
#############################################################################



   print "<div class='final'>
    <span class='izq'>Total</span><div class='dch'>$totalprice&nbsp;€</div>
    </div>"; 
    #<span class='movil'>
         #<button class='continue'>Continuar comprando</button></span>";




#####print "<tr><td bgcolor=#E1E1FF><b>Total:</b></td>";
#if ($useimage eq '1') {
#	print "<td bgcolor=#E1E1FF></td>";
#	}
#if ($useid eq '1') {
#	print "<td bgcolor=#E1E1FF></td>";
#	}
#####print "<td bgcolor=#E1E1FF></td><td bgcolor=#E1E1FF></td><td bgcolor=#E1E1FF align=right><b>$totalprice&nbsp;€</b></td></tr>\n";


if ($multicurr eq 1) {
print "<tr><td bgcolor=#E1E1FF><b>Total price in<br>selected currency:</b></td>";
	if ($useimage eq '1') {
		print "<td bgcolor=#E1E1FF></td>";
	}
	if ($useid eq '1') {
		print "<td bgcolor=#E1E1FF></td>";
	}

my($path) = $basepath . $delim . $currdb;
open (CURRDB, "$path");
my(@CURR) = <CURRDB>;
close(CURRDB);
print "<td bgcolor=#E1E1FF colspan=2 align=center><select name=curropt>";
foreach $curr (@CURR) {
	my(@currs)=split(/\|/,$curr);
	print "<option ";
	if ($usercurr eq $currs[0]) { print "selected "; $usercurr=$currs[2] }
	print "value=$currs[0]>$currs[1] x$currs[2] </option>";
	}
	print "</select></td>\n";

	$totalprice *= $usercurr;
	$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
	print "<td bgcolor=#E1E1FF align=right><b>$totalprice&nbsp;€</b></td></tr>\n"; 
	}
	
#####print "</table><br>\n";

}

sub precioportes {
$portes = 6.90;

	if ($gastosenvio eq 'Peninsula') {
	$portes = 6.90;
	}

	if ($gastosenvio eq 'Asturias') {
	$portes = 3.90;
	}

	if ($gastosenvio eq 'Baleares') {
	$portes = 18.00;
	}

	if ($gastosenvio eq 'Canarias') {
	$portes = 22.00;
	}
}

# Review all items in cart. SE PUEDEN MODIFICAR LAS CANTIDADES.
sub review_items {
&print_header;
&list_items;
if ($SIZE > 1){
#print "<font face=Arial size=2>Si no desea un articulo ponga 0 en \"Cantidad\" y pulse \"Actualizar\"</font><center><input type=submit value=\"Actualizar\"><br></form>
# <form method=post action=http://www.asturalba.com/cgi-bin/s-mart.pl?command=buy2\n";
open (ORDER,"$basepath$delim$order") || print "Could not open $basepath$delim$order $! \n";
while (<ORDER>) {
	print $_;
	}
close(ORDER);
#&print_footer;
}
&print_footer;
}

# Add a item to the cart, show review page, unless they included a redirect variable.
sub add_item {

open (REFFILE,">>$reffile") || print "Content-type: text/html\n\n Can't Open $reffile(r): $!\n";
print REFFILE join "\|", $FORM{'itemname'},$FORM{'itemprice'},$FORM{'itemquant'},$FORM{'weight'},$FORM{'itemid'},"\|\n";
close(REFFILE);
if ($useredirect eq '1') {
&review_items;
	}
elsif ($FORM{'redirect'}) {
		print "Location: $FORM{'redirect'} \n\n";
		}
else {
	&review_items;
	}
}

# Cambiar la cantidad de los articulos, se borra con cantidad cero.######################
sub change_items {
open (REFFILE,"$reffile") || print "Content-type: text/html\n\n Can't Open $reffile(r): $!\n";
my(@LINES)=<REFFILE>;
close(REFFILE);
$SIZE=@LINES;

open (REFFILE,">$reffile") || print "Content-type: text/html\n\n Can't Open $reffile(r): $!\n";
print REFFILE "$date\| $ENV{'REMOTE_HOST'}\| $ENV{'HTTP_USER_AGENT'}\|$FORM{'curropt'}\|$FORM{'gastosenvio'}\|$FORM{'taxopt'}\|\n";
for ($i=1;$i<$SIZE;$i++) {
	local($itemq) = "item$i";
   	$_=$LINES[$i];
	my($itemname, $itemprice, $itemquant, $weight, $itemid) = split(/\|/,$_);
	if ($FORM{$itemq} > 0) {
		print REFFILE join "\|", $itemname,$itemprice,$FORM{$itemq},$weight,$itemid,"\|\n";
		}
	}
close(REFFILE);
print "Location: $cgiurl\?command=review\n\n";
}


# MOSTRAR EL FORMULARIO DE COMPRA
sub buy_items1 {
&print_header;
&list_items;
#####print "<font face=Arial size=2>Si no desea un articulo ponga 0 en \"Cantidad\" y pulse \"Actualizar\"</font><center><input type=submit value=\"Actualizar\"><br></form>
 ##### <form method=post action=http://www.asturalba.com/cgi-bin/s-mart.pl?command=buy2\n";
open (ORDER,"$basepath$delim$order") || print "Could not open $basepath$delim$order $! \n";
while (<ORDER>) {
	print $_;
	}
close(ORDER);	
&print_footer;
}

sub numpedido {
$pat = "$basepath$delim" . "Data" . "$delim" . "carro" . $delim . "numped.txt";
open(numped, "$pat");
$numpedi = <numped>;            
close(numped);                
$numpedi++; 
open(numped2, ">$pat");  
print numped2 $numpedi;         
close(numped2); 
}

##### PROCESAR O ENVIAR EL FORMULARIO DE COMPRA  &check_required#####
sub buy_items2 {

#&print_header;
if ($SIZE > 1){
&numpedido;
&grabapedi;

if ($FORM{'forpago'} eq 'Paypal'){
&send_order;
&send_verify;

$totalpaypal = $totalpedido * 1.03;
$totalpaypal = int($totalpaypal * (10 ** 2) + .5) / (10 ** 2);
#print "Location: https://www.paypal.com/cgi-bin/webscr?cmd=_cart& upload=1& currency_code=EUR& business=palmirafc\@yahoo.es& item_name_1=Pedido www.asturalba.com&amount_1=$totalpaypal\n\n";
$headerfinal = "html\\headerfinal.html";
print "Content-type: text/html\n\n";
#open (HEADER,"$basepath$delim$headerfinal ") || print "Could not open $basepath$delim$headerfinal $! \n";
#while (<HEADER>) {
#print $_;
#	}



print "<html lang=\"es\">

<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"shortcut icon\" href=\"http://www.asturalba.com/iconoasturalba2.ico\">
<title>Asturalba.com - Paypal</title>
<link href=\"http://www.asturalba.com/css/movil/boilerplate.css\" rel=\"stylesheet\" type=\"text/css\">
<link href=\"http://www.asturalba.com/css/responsive-carro.css\" rel=\"stylesheet\" type=\"text/css\">
<meta name=\"google-translate-customization\" content=\"bb7393bb84452501-b1d193a7e63d6ce8-g9cc9dc94550a0633-11\"></meta>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
 
  ga('create', 'UA-50593875-1', 'asturalba.com');
  ga('send', 'pageview');
 
</script>
<!--[if lt IE 9]>
    <script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"></script>
    <script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script>
<![endif]-->
</head>
<body>
<header id=\"header\" style=\"background: #fff;\">
  <div id=\"superior\">
  <a id=\"arriba\"></a>
  <div id=\"logo\">
<a href=\"http://www.asturalba.com\"><img src=\"http://www.asturalba.com/images/asturalba-azul.png\" alt=\"logo Asturalba\" longdesc=\"http://www.asturalba.com/\"></a>
</div>
<div id=\"slogan\"></div>
  <div id=\"lateral\">
  </div>
  </div>
</header>
<div align=\"center\" style=\"line-height: 20px; font-size: 16px;\">

<div class=\"peq\">
</div>
<div class=\"redirect\">
<div style=\"height: 90px;\">
<img align=\"left\" src=\"http://www.asturalba.com/images/icons/pago/paypal-pago.png\" alt=\"Paypal\"><br>
</div>
<div class=\"blanco\">
<div class=\"peq\">El importe total de tu pedido es de $totalpaypal&euro;.<br>
  <br>
  Pulsa continuar para ser redirigido a Paypal y completar tu compra de forma segura:</div>
  <form method='POST' action='https://www.paypal.com/cgi-bin/webscr'>
  <input type='hidden' name='cmd' value='_cart'>
  <input type='hidden' name='currency_code' value='EUR'>
  <input type='hidden' name='business' value='palmirafc\@yahoo.es'>
  <input type='hidden' name='item_name_1' value='Pedido www.asturalba.com'>
  <input type='hidden' name='amount_1' value='$totalpaypal'>
  <input type='hidden' name='upload' value='1'>
<button align=\"center\" type=\"submit\" class=\"continue\" id=\"confirmar\" value='Continuar' name='B1'>Continuar</button>
  </form>
</div>
<img src=\"http://www.asturalba.com/images/icons/pago/pago-paypal.png\" alt=\"Pago seguro con Paypal\">
</div>
<br>
</div>

</body>
</html>";










=pod
print "<br><br>Su pedido ha sido cursado correctamente,<br>\n";
print "<br>ha elegido pago con paypal,<br>\n";
print "<br>el importe de su pedido es de $totalpaypal Euros<br>\n";
print "<br><br>pulse el botón 'continuar' para acceder la página de pago de paypal,<br><br>\n";
print "<form method='POST' action='https://www.paypal.com/cgi-bin/webscr'>";
print "<input type='hidden' name='cmd' value='_cart'>";
print "<input type='hidden' name='currency_code' value='EUR'>";
print "<input type='hidden' name='business' value='palmirafc\@yahoo.es'>";
print "<input type='hidden' name='item_name_1' value='Pedido www.asturalba.com'>";
print "<input type='hidden' name='amount_1' value='$totalpaypal'>";
print "<input type='hidden' name='upload' value='1'><p>";
print "<input type='submit' value='Continuar' name='B1'></p>";
print "</form>";
print "<br><br>\n";
=cut
#close(HEADER);
}
else
{
print "Content-type: text/html\n\n";
=pod
$headerfinal = "html\\headerfinal.html";
open (HEADER,"$basepath$delim$headerfinal ") || print "Could not open $basepath$delim$headerfinal $! \n";
while (<HEADER>) {
print $_;
	}
close(HEADER);
=cut


if ($useverify eq '1' && ($cardtype eq 'visa' || $cardtype eq 'mastercard' || $cardtype eq 'novus' || $cardtype eq 'amex')) {
	&CC_Verify;
	}
if ($usetrack eq 1) {
	&track_order;
	}

#### if size mayor que uno verifica que hay algun articulo en el carro
##aquiivaelifsizemayorqueuno
&send_order;
&send_verify;
######esto si se hace la compra con tarjeta #############

if ($FORM{'forpago'} eq 'Tarjeta') {
print "<html lang=\"es\">

<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"shortcut icon\" href=\"http://www.asturalba.com/iconoasturalba2.ico\">
<title>Asturalba.com - Tarjeta de crédito</title>
<link href=\"http://www.asturalba.com/css/movil/boilerplate.css\" rel=\"stylesheet\" type=\"text/css\">
<link href=\"http://www.asturalba.com/css/responsive-carro.css\" rel=\"stylesheet\" type=\"text/css\">
<meta name=\"google-translate-customization\" content=\"bb7393bb84452501-b1d193a7e63d6ce8-g9cc9dc94550a0633-11\"></meta>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
 
  ga('create', 'UA-50593875-1', 'asturalba.com');
  ga('send', 'pageview');
 
</script>
<!--[if lt IE 9]>
    <script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"></script>
    <script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script>
<![endif]-->
</head>
<body>
<header id=\"header\" style=\"background: #fff;\">
  <div id=\"superior\">
  <a id=\"arriba\"></a>
  <div id=\"logo\">
<a href=\"http://www.asturalba.com\"><img src=\"http://www.asturalba.com/images/asturalba-azul.png\" alt=\"logo Asturalba\" longdesc=\"http://www.asturalba.com/\"></a>
</div>
<div id=\"slogan\"></div>
  <div id=\"lateral\">
  </div>
  </div>
</header>
<div align=\"center\" style=\"line-height: 20px; font-size: 16px;\">

<div class=\"peq\">
</div>
<div class=\"redirect\">
<div style=\"height: 90px;\">
<img align=\"left\" style=\"max-width :50%;\" src=\"http://www.asturalba.com/images/icons/pago/popular-payments.png\" alt=\"Popular Payments\"><img style=\"max-width :25%; vertical-align: bottom;\" align=\"right\" src=\"http://www.asturalba.com/images/icons/pago/pago-seguro-ssl.png\" alt=\"Pago seguro SSL\"><br>
</div>
<div class=\"blanco\">
<div class=\"peq\">Todas las transacciones son seguras y están encriptadas. Nunca se almacena la información de la tarjeta.<br><br>
  Pulsa continuar para ser redirigido a Popular Payments y completar tu compra de forma segura:</div>
  <form method='POST' action='http://www.asturalba.com/pgotarjeta/API_PHP/redsysHMAC256_API_PHP_5.2.0/generapet.php?nume=$numpedi&tott=$totalprince'>
<button align=\"center\" type=\"submit\" class=\"continue\" id=\"confirmar\" value='Continuar' name='B1'>Continuar</button>
  </form>
</div>
<img class=\"tarjeta\" src=\"http://www.asturalba.com/images/icons/pago/tarjeta-credito-visa.png\" alt=\"Tarjeta de crédito Visa\">
<img class=\"tarjeta\" src=\"http://www.asturalba.com/images/icons/pago/tarjeta-credito-mastercard.png\" alt=\"Tarjeta de crédito MasterCard\">
<img class=\"tarjeta\" src=\"http://www.asturalba.com/images/icons/pago/tarjeta-credito-maestro.png\" alt=\"Tarjeta de crédito Maestro\">
<img class=\"tarjeta\" src=\"http://www.asturalba.com/images/icons/pago/tarjeta-credito-american-express.png\" alt=\"Tarjeta de crédito American Express\">
</div>
<br>
<br>
</div>

</body>
</html>";


=pod
print "<br><br>Su pedido ha sido cursado correctamente,<br>\n";
print "<br>ha elegido pago con tarjeta,<br>\n";
print "<br><br>pulse el botón 'continuar' para acceder a una página de pago segura https,<br><br>\n";
print "<form method='POST' action='https://tpv.4b.es/tpvv/teargral.exe'>";
print "<input type='hidden' name='order' value='$storename-$host-$orderid'>";
print "<input type='hidden' name='store' value='PI00021136'><p>";
print "<input type='submit' value='Continuar' name='B1'></p>";
print "</form>";
print "<br><br>\n";}
=cut

}
elsif ($FORM{'forpago'} eq 'Transferencia'){
print "<html lang=\"es\">
<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"shortcut icon\" href=\"http://www.asturalba.com/iconoasturalba2.ico\">
<title>Asturalba.com - Transferencia bancaria</title>
<link href=\"http://www.asturalba.com/css/movil/boilerplate.css\" rel=\"stylesheet\" type=\"text/css\">
<link href=\"http://www.asturalba.com/css/responsive-carro.css\" rel=\"stylesheet\" type=\"text/css\">
<meta name=\"google-translate-customization\" content=\"bb7393bb84452501-b1d193a7e63d6ce8-g9cc9dc94550a0633-11\"></meta>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
 
  ga('create', 'UA-50593875-1', 'asturalba.com');
  ga('send', 'pageview');
 
</script>
<!--[if lt IE 9]>
    <script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"></script>
    <script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script>
<![endif]-->
</head>
<body>
<header id=\"header\" style=\"background: #fff;\">
  <div id=\"superior\">
  <a id=\"arriba\"></a>
  <div id=\"logo\">
<a href=\"http://www.asturalba.com\"><img src=\"http://www.asturalba.com/images/asturalba-azul.png\" alt=\"logo Asturalba\" longdesc=\"http://www.asturalba.com/\"></a>
</div>
<div id=\"slogan\"></div>
  <div id=\"lateral\">
  </div>
  </div>
</header>
<div align=\"center\" style=\"line-height: 20px; font-size: 16px;\">

<div class=\"peq\">
</div>
<div class=\"redirect\">

<div class=\"blanco\">
<div class=\"peq\">El pedido se ha realizado con éxito.<br>
  <img src=\"http://www.asturalba.com/images/icons/pago/correo.png\" alt=\"Tienes 1 email\"><br>
  Te hemos enviado un correo con las instrucciones para el pago mediante transferencia bancaria.</div>
<a href=\"http://www.asturalba.com/\" title=\"www.asturalba.com\">
<button align=\"center\" class=\"continue\" id=\"confirmar\">Finalizar</button>
</a></div>
</div>
<br>
<h2>¡Gracias por tu compra!</h2>

</body>
</html>";
}
else {


print "<html lang=\"es\">

<head>
<meta charset=\"utf-8\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"shortcut icon\" href=\"http://www.asturalba.com/iconoasturalba2.ico\">
<title>Asturalba.com - Contra reembolso</title>
<link href=\"http://www.asturalba.com/css/movil/boilerplate.css\" rel=\"stylesheet\" type=\"text/css\">
<link href=\"http://www.asturalba.com/css/responsive-carro.css\" rel=\"stylesheet\" type=\"text/css\">
<meta name=\"google-translate-customization\" content=\"bb7393bb84452501-b1d193a7e63d6ce8-g9cc9dc94550a0633-11\"></meta>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
 
  ga('create', 'UA-50593875-1', 'asturalba.com');
  ga('send', 'pageview');
 
</script>
<!--[if lt IE 9]>
    <script src=\"https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js\"></script>
    <script src=\"https://oss.maxcdn.com/respond/1.4.2/respond.min.js\"></script>
<![endif]-->
</head>
<body>
<header id=\"header\" style=\"background: #fff;\">
  <div id=\"superior\">
  <a id=\"arriba\"></a>
  <div id=\"logo\">
<a href=\"http://www.asturalba.com\"><img src=\"http://www.asturalba.com/images/asturalba-azul.png\" alt=\"logo Asturalba\" longdesc=\"http://www.asturalba.com/\"></a>
</div>
<div id=\"slogan\"></div>
  <div id=\"lateral\">
  </div>
  </div>
</header>
<div align=\"center\" style=\"line-height: 20px; font-size: 16px;\">

<div class=\"peq\">
</div>
<div class=\"redirect\">

<div class=\"blanco\">
<div class=\"peq\">El pedido se ha realizado con éxito, el importe total es de <strong>$totalreembolso&euro;</strong>.<br>
  <img src=\"http://www.asturalba.com/images/icons/pago/contra-reembolso.jpg\" alt=\"Pago contra reembolso\"><br>
  Por favor, ten preparado el importe exacto para realizar el pago al transportista.</div>
<a href=\"http://www.asturalba.com/\" title=\"www.asturalba.com\">
<button align=\"center\" class=\"continue\" id=\"confirmar\">Finalizar</button>
</a></div>
</div>
<br>
<h2>¡Gracias por tu compra!</h2>

</body>
</html>";

=pod
print "<br><br>Su pedido ha sido cursado correctamente,<br><br>\n";
print "en breve nos pondremos en contacto con usted.<br><br>\n";
print "Gracias por realizar sus compras en <b>www.asturalba.com</b><br><br>\n";
=cut
#print "  $storename";
#print "  $orderid";
######&list_items;#######
#print "<br><br>\n";
}#fin else
}
}
else
{
$headerfinal = "html\\headerfinal.html";
print "Content-type: text/html\n\n";
open (HEADER,"$basepath$delim$headerfinal ") || print "Could not open $basepath$delim$headerfinal $! \n";
while (<HEADER>) {
print $_;
	}
close(HEADER);
}

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

if ($usetrack eq 1) {
	my($sys) = "mv $reffile $basepath/$orderdir/$storename-$orderid";
	system($sys);
	}
unlink($reffile);

#####&print_footer;###no hace falta imprimir el pie
}

# parse form input
sub parse_form {
my(@pairs);
   if ($ENV{'REQUEST_METHOD'} eq 'POST') {
      # Get the input
      read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
 
      # Split the name-value pairs
      @pairs = split(/&/, $buffer);
   }

   foreach $pair (@pairs) {
      my($name, $value) = split(/=/, $pair);
 
      $name =~ tr/+/ /;
      $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

      $value =~ tr/+/ /;
      $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

      # If they try to include server side includes, erase them, so they
      # arent a security risk if the html gets returned.  Another 
      # security hole plugged up.

      $value =~ s/<!--(.|\n)*-->//g;

      # Create two associative arrays here.  One is a configuration array
      # which includes all fields that this form recognizes.  The other
      # is for fields which the form does not recognize and will report 
      # back to the user in the html return page and the e-mail message.
      # Also determine required fields.

      if ($name eq 'bgcolor' ||
	  $name eq 'background' ||
	  $name eq 'link_color' ||
	  $name eq 'vlink_color' ||
      $name eq 'text_color' ||
   	  $name eq 'alink_color' ||
	  $name eq 'title' ||
	  $name eq 'sort' ||
	  $name eq 'print_config' ||
	  $name eq 'return_link_title' ||
	  $name eq 'return_link_url' && ($value)) {
         
	 $CONFIG{$name} = $value;
      }
      elsif ($name eq 'required') {
         @required = split(/,/,$value);
      }
      elsif ($name eq 'exclude') {
      	@exclude = split(/,/,$value);
      	}
      else {
         if ($FORM{$name} && ($value)) {
	    $FORM{$name} = "$FORM{$name}, $value";
	 }
         elsif ($value) {
            $FORM{$name} = $value;
         }
      }
   }
}

# Send the order
$SERVER_OS="WIN";

sub send_order {
open (REFFILE,"$reffile") || print "Content-type: text/html\n\n Can't Open $reffile(r): $!\n";

$SERVER_OS="WIN";

my(@LINES)=<REFFILE>;
close(REFFILE);
$SIZE=@LINES;

my($totalquant,$totalprice,$totalweight) = 0;
######################AQUI ARRIBA A INTRODUCIDO LAS LINEAS AL REFFILE###########
# abre el programa de mail

    if ($SERVER_OS eq "WIN") {
        open(MAIL, ">$reffile");
        # BLAT NECESITA to: and from: on command line
        local($BLAT_ARGS);
    }


   print MAIL "Subject: $FORM{'subject'}";
   if ($usetrack eq 1) { print MAIL "\#$orderid"; }
   print MAIL "\n\n";
   print MAIL "Este pedido ha sido ";
   print MAIL "enviado por $FORM{'realname'} ($FORM{'email'})  ";
   print MAIL "$date\n";
   print MAIL "-----------------------------------\n";


    # Check ESTO ES LO QUE SE MANDA POR EMAIL LO QUE SE ESCRIBE EN EL PROGRAMA ######


   print MAIL "Remote Host: $userhost\n";
   print MAIL "Explorador: $useragent\n";
   print MAIL "\n\n";
   print MAIL "PEDIDO:\n\n";


   
print MAIL sprintf "%-57.57s", "Articulo";
print MAIL sprintf "%8.8s", "Cantidad";
print MAIL sprintf "%10.10s", "Precio";
print MAIL sprintf "%11.11s", "Total";
print MAIL "\n";
print MAIL "--------------------------------------------------------------------------------------\n";

	$_=$LINES[0];
	($udate, $uhost, $uagente, $unose, $gastosenvio) = split(/\|/,$_);

	$lineasreales = 0;
=pod
for ($i=1;$i<$SIZE;$i++) {
	$_=$LINES[$i];
	my($itemname, $itemprice, $itemquant, $weight,$itemid) = split(/\|/,$_);
	$tmpprice = $itemprice*$itemquant;
	$tmpprice = int($tmpprice * (10 ** 2) + .5) / (10 ** 2);
	$totalprice=$totalprice + $tmpprice;
	$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
	$totalquant=$totalquant + $itemquant;
	$totalweight = $totalweight + $weight;
	print MAIL sprintf "%-18.18s", $itemid;
	print MAIL sprintf "%-58.58s", $itemname;
	print MAIL sprintf "%7.7s", $itemquant;
	print MAIL sprintf "%10.10s", "$itemprice";
	print MAIL sprintf "%11.11s", "$tmpprice";
	print MAIL "\n";
##### verifica que se han introducido lineas
	if ($itemname eq '' || $totalprice < 1){
	}
	else
	{
	$lineasreales = 1;
	}
	}

print MAIL "--------------------------------------------------------------------------------------\n";
print MAIL "Subtotal:";
print MAIL sprintf "%78.78s", "$totalprice\ Euros\n";



&precioportes;

$totalprice += $portes;
$portes = int($portes * (10 ** 2) + .5) / (10 ** 2);
$_ = $portes;

print MAIL "Portes:  ";
print MAIL sprintf "%78.78s", "$portes\ Euros\n";

### Taxes
if ($tax eq '0') {
	# Do nothing
	}
## Always tax

elsif ($tax eq '2') {
	$taxtotal = $totalprice * $taxamt;
	$taxtotal = int($taxtotal * (10 ** 2) + .5) / (10 ** 2);
	$totalprice = $totalprice + $taxtotal;
}



## Format and print the tax
$taxtotal = int($taxtotal * (10 ** 2) + .5) / (10 ** 2);


print MAIL "I.V.A.:  ";
print MAIL sprintf "%78.78s", "$taxtotal\ Euros\n";

## Format and print the totalprice
$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
$_ = $totalprice;

print MAIL "Total:";
print MAIL sprintf "%83.83s" , "$totalprice\ Euros\n";

if ($FORM{'forpago'} eq 'Contrareembolso') {
if ($totalprice < 100){
$totalreembolso = $totalprice + 5;
}
else{
$totalreembolso = $totalprice * 1.05;
}
$totalreembolso = int($totalreembolso * (10 ** 2) + .5) / (10 ** 2);
print MAIL "Total Reembolso:";
print MAIL sprintf "%73.73s" , "$totalreembolso\ Euros\n";

}
=cut
print MAIL "\n\n";



## Print all the variables on the order form
undef %is_exclude;
for (@exclude) { $is_exclude{$_} = 1 }
   if ($CONFIG{'sort'} eq 'alphabetic') {
      foreach $key (sort keys %FORM) {
         # Print the name and value pairs in FORM array to mail.
         print MAIL "$key: $FORM{$key}\n\n" unless $is_exclude{$key};
      }
   }
   elsif ($CONFIG{'sort'} =~ /^order:.*,.*/) {
	  $CONFIG{'sort'} =~ s/order://;
      @sorted_fields = split(/,/, $CONFIG{'sort'});
      foreach $sorted_field (@sorted_fields) {
         # Print the name and value pairs in FORM array to mail.
         if ($FORM{$sorted_field}) {
            print MAIL "$sorted_field: $FORM{$sorted_field}\n\n" unless $is_exclude{$sorted_field};
         }
      }
   }
   else {

=pod
   print MAIL "Nombre Comprador: $FORM{'realname'} $FORM{'Apellidos'}\n";
#####   print MAIL "Nombre Comercial: $FORM{'nombre_comercial'}\n";
   print MAIL "Razon social: $FORM{'razon_social'}\n";
   print MAIL "Dni: $FORM{'dni'}\n\n";

   print MAIL "Direccion: $FORM{'Direccion'}\n";
   print MAIL "C.P.: $FORM{'Codigo_Postal'}  Ciudad: $FORM{'Ciudad'}\n";
   print MAIL "Provincia: $FORM{'Provincia'}\n\n";

   print MAIL "Tel_Comprador: $FORM{'Tel_comprador'}\n";
   print MAIL "Telefono: $FORM{'Telefono'}\n";
   print MAIL "Fax: $FORM{'Fax'}\n";
   print MAIL "E-mail: $FORM{'email'}\n\n";
   print MAIL "forma de pago $FORM{'forpago'}\n\n";
    #if ($FORM{'forpago'} eq 'Tarjeta') {
        	#$orderid = time() . "-" . $$;
   		#print MAIL "referencia pago tarjeta: $storename-$host-$orderid\n"; 
         #}
   print MAIL "en lista de correo: $FORM{'newsletters'}\n\n";
   print MAIL "forma de pago $FORM{'forpago'}\n\n";
   print MAIL "Comentario:\n$FORM{'Comentario'}\n";

=cut

#### VERSION XML ######

#$direcc = encode("iso-8859-1", decode("utf8",$FORM{'Direccion'}));

print MAIL "<pedido>\n";
print MAIL "<cliente>\n";
print MAIL "<codcli>00002</codcli>\n";
print MAIL "<nomcli>" . encode("iso-8859-1", decode("utf8",$FORM{'realname'})) . encode("iso-8859-1", decode("utf8",$FORM{'Apellidos'})) . "</nomcli>\n";
print MAIL "<Rsocial>" . encode("iso-8859-1", decode("utf8",$FORM{'razon_social'})) . "</Rsocial>\n";
print MAIL "<Pcontacto>" . encode("iso-8859-1", decode("utf8",$FORM{'nombre_comercial'})) . "</Pcontacto>\n";
print MAIL "<nif>$FORM{'dni'}</nif>\n";
print MAIL "<direccion>" . encode("iso-8859-1", decode("utf8",$FORM{'Direccion'})) . "</direccion>\n";
print MAIL "<cpostal>$FORM{'Codigo_Postal'}</cpostal>\n";
print MAIL "<ciudad>" . encode("iso-8859-1", decode("utf8",$FORM{'Ciudad'})) . "</ciudad>\n";
print MAIL "<provincia>" . encode("iso-8859-1", decode("utf8",$FORM{'Provincia'})) . "</provincia>\n";
print MAIL "<telefono>$FORM{'Tel_comprador'}</telefono>\n";
print MAIL "<telefono2>$FORM{'Telefono'}</telefono2>\n";
print MAIL "<fax>$FORM{'Fax'}</fax>\n";
print MAIL "<email>" . encode("iso-8859-1", decode("utf8",$FORM{'email'})) . "</email>\n";
print MAIL "<observaciones>" . encode("iso-8859-1", decode("utf8",$FORM{'Comentario'})) . "</observaciones>\n";
print MAIL "<fecha>$date2</fecha>\n";
print MAIL "<numped>$numpedi</numped>\n";
print MAIL "<formapago>" . encode("iso-8859-1", decode("utf8",$FORM{'forpago'})) . "</formapago>\n";
print MAIL "<representante>INTERNET ASTURALBA</representante>\n";
print MAIL "</cliente>\n";
print MAIL "<lineas>\n";


$_=$LINES[0];
	($udate, $uhost, $uagente, $unose, $gastosenvio) = split(/\|/,$_);

	$lineasreales = 0;

for ($i=1;$i<$SIZE;$i++) {
	$_=$LINES[$i];
	my($itemname, $itemprice, $itemquant, $weight,$itemid) = split(/\|/,$_);
	$tmpprice = $itemprice*$itemquant;
	$tmpprice = int($tmpprice * (10 ** 2) + .5) / (10 ** 2);
	$totalprice=$totalprice + $tmpprice;
	$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
	$totalquant=$totalquant + $itemquant;
	$totalweight = $totalweight + $weight;
	print MAIL "<articulo>\n";
	print MAIL "<Codigo>$itemid</Codigo>\n";
	print MAIL "<Descrip>" . encode("iso-8859-1", decode("utf8",$itemname)) . "</Descrip>\n";
	print MAIL "<unidades>$itemquant</unidades>\n";
	print MAIL "<Precio>$itemprice</Precio>\n";
	print MAIL "<totlinea>$tmpprice</totlinea>\n";
	print MAIL "<dto>$tmpprice</dto>\n";
	print MAIL "<Observaciones></Observaciones>\n";
	print MAIL "<Urge>0</Urge>\n";
	print MAIL "</articulo>\n";
##### verifica que se han introducido lineas
	if ($itemname eq '' || $totalprice < 1){
	}
	else
	{
	$lineasreales = 1;
	}
	}


print MAIL "</lineas>\n";

print MAIL "<total>\n";
print MAIL "<subtotal>$totalprice</subtotal>\n";

&precioportes;

$totalprice += $portes;
$portes = int($portes * (10 ** 2) + .5) / (10 ** 2);
$_ = $portes;

print MAIL "<porte>$portes</porte>\n";

### Taxes
if ($tax eq '0') {
	# Do nothing
	}
## Always tax
elsif ($tax eq '2') {
	$taxtotal = $totalprice * $taxamt;
	$taxtotal = int($taxtotal * (10 ** 2) + .5) / (10 ** 2);
	$totalprice = $totalprice + $taxtotal;

}
## Format and print the tax
$taxtotal = int($taxtotal * (10 ** 2) + .5) / (10 ** 2);

#print MAIL "I.V.A.:  ";
#print MAIL sprintf "%78.78s", "$taxtotal\ Euros\n";
print MAIL "<iva>$taxtotal</iva>\n";

## Format and print the totalprice
$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
$_ = $totalprice;

#print MAIL "Total:";
#print MAIL sprintf "%83.83s" , "$totalprice\ Euros\n";

print MAIL "<totalpedido>$totalprice</totalpedido>\n";

if ($FORM{'forpago'} eq 'Contrareembolso') {
if ($totalprice < 100){
$totalreembolso = $totalprice + 5;
}
else{
$totalreembolso = $totalprice * 1.05;
}
$totalreembolso = int($totalreembolso * (10 ** 2) + .5) / (10 ** 2);
#print MAIL "Total Reembolso:";
#print MAIL sprintf "%73.73s" , "$totalreembolso\ Euros\n";

print MAIL "<totalreembolso>$totalreembolso</totalreembolso>\n";
}


print MAIL "</total>\n";
print MAIL "</pedido>\n";



      #comentado# foreach $key (keys %FORM) {
         # Print the name and value pairs in FORM array to html.
         #comentado# print MAIL "$key: $FORM{$key}\n\n" unless $is_exclude{$key};
      #comentado# }
   }


#manda el xml
#$resultado = get("http://www.asturalba.com/email1.php?cuerpo=$reffile&corre=serv.tecnico\@asturalba.com");

$totalprice = 0;
close (MAIL);
############# P R O G R A M A   Q U E   M A N D A   E - M A I L #############







$mailcli = $FORM{'email'};

    # BEGIN: Win32 mods - darrin@gorski.net
    # If we're running under Windows, we actually send mail here...
#verifica que hay lineas lo de lineasreales
if ($lineasreales == 1){   
 if ($SERVER_OS eq "WIN") {

	$BLAT_ARGS = "$reffile -t serv.tecnico\@asturalba.com ";#quite#$CONFIG{'recipient'}#
        ##$BLAT_ARGS = "http://www.asturalba.com/email2.html -t asturalba\@asturalba.com ";#quite#$CONFIG{'recipient'}#
	$BLAT_ARGS .= "-f asturalba\@asturalba.com ";
        $BLAT_ARGS .= "-s \"Pedido de www.asturalba.com\" ";
        $BLAT_ARGS .= "-i $FORM{'email'} " if defined($FORM{'email'});
        $BLAT_ARGS .= "-q";
        system ("$mailprog $BLAT_ARGS");
        #unlink $WIN_TEMPFILE;
    	}
    }
}

###############################################################################
#############    ESTE DE ABAJO ES EL MAIL PARA EL CLIENTE     #################
###############################################################################

# Send to receipt
sub send_verify {
my($totalquant,$totalprice,$taxtotal) = 0;

# abre el programa de mail

    if ($SERVER_OS eq "WIN") {
        open(MAIL, ">$reffile");
        # BLAT NECESITA to: and from: on command line
        local($BLAT_ARGS);
    }

   #print MAIL "Subject: $FORM{'subject'}";
   if ($usetrack eq 1) { print MAIL "\#$orderid"; }

=pod
   print MAIL "\n";
   print MAIL "-------------------------------------------- \n";
   print MAIL "             WWW.ASTURALBA.COM  \n";
   print MAIL "-------------------------------------------- \n\n";


   print MAIL "Estimado/a $FORM{'realname'} . \n\n";

   print MAIL "Este email ha sido generado automaticamente para confirmación de los productos y detalles de su pedido. \n\n
   A fin de evitar errores o malentendidos, rogamos compruebe los artículos en cuanto a su exactitud y cantidad, informándonos en caso de que estos fueran erroneos. \n\n
   Muchas gracias por su pedido
    y su confianza en nuestros productos y servicios. \n\n";


   #print MAIL "Este pedido ha sido ";
   #print MAIL "enviado por $FORM{'realname'} ($FORM{'email'}) \n";
   #print MAIL "$date\n\n\n";
   
   
print MAIL "Artículo                                                    Cantidad    Precio   Total";
print MAIL "\n";
print MAIL "--------------------------------------------------------------------------------------\n";
=cut

$parte1 = "<!doctype html>
<html>
<head>
<meta charset=\"utf-8\">
<title>Gracias por confiar en Asturalba</title>
<style type=\"text/css\">
img {
	max-width: 100%;
}
a img {
	border: none;
}
\@media print {
.noprint {
    display:none;
    }
</style>
</head>

<body style=\"font-family: Arial; font-size: 13px; background-color: #FFF; margin: 10px; margin: 3%; padding: 0; color: #000;\">
<table width=\"99%\">
<tr>
<td width=\"80%\"><a href=\"http://www.asturalba.com/\"><img src=\"http://www.asturalba.com/images/asturalba-mail.png\" alt=\"www.asturalba.com\"></a></td>
  </tr>
  </table>
  
<table width=\"99%\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\">
<tr>
<th width=\"60%\" style=\"width: 40%; padding: 8px; padding-left: 16px; padding-right: 16px; margin: 6px; font-size: 16px; font-weight: normal; text-align: left; background-color: #ededf9; border: solid #000080; border-width: 1px; border-left-style: solid; border-right-style: none; border-right-width: medium; border-top-style: solid;border-bottom-style:solid; bordercolor:#000080\"><strong> PEDIDO: $numpedi
</strong>
</th>
<th width=\"40%\" align=\"right\" style=\"width: 40%; padding: 8px; padding-left: 16px; padding-right: 16px; margin: 6px; font-size: 16px; font-weight: normal; text-align: left; background-color: #ededf9; border: thin solid #000080; border-width: 1px; border-right-style: solid; border-top-style: solid;  border-bottom-style: solid; padding-right: 4px; padding-top: 1px; padding-bottom: 1px; border-left-style:none; border-left-width:medium\">
<div align=\"right\" style=\"padding-right: 16px\">$date2</div></th></tr>
</table>
<br>
<table width=\"99%\" align=\"center\" cellpadding=\"4\" class=\"producto\" style=\"border: thin hidden white; border-collapse: collapse; border-bottom: thin solid #ededf9\">
  <tr style=\"border: thin solid #000080\">
<th width=\"50%\" align=\"left\">
Descripción
</th>
<th width=\"20%\" align=\"right\">
Precio
</th>
<th width=\"10%\">
Und.
</th>
<th width=\"20%\" align=\"right\" style=\"padding-right: 1%\">
Total
</th>
</tr>";

#$parte1 = decode( 'utf-8', $parte1 );
#$parte1 = encode( 'iso-8859-1', $parte1 );


#$octets = encode("iso-8859-1", $parte1);
#  from_to($parte1, "utf8", "iso-8859-1");
$parte1 = encode("iso-8859-1", decode("utf8",$parte1));
print MAIL $parte1;


	$_=$LINES[0];
	($udate, $uhost, $uagente, $unose, $gastosenvio) = split(/\|/,$_);

$lineasreales = 0;

$articulosmail = "";

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

	$_=$LINES[$i];
	my($itemname, $itemprice, $itemquant, $weight,$itemid) = split(/\|/,$_);
	$tmpprice = $itemprice*$itemquant;
	$tmpprice = int($tmpprice * (10 ** 2) + .5) / (10 ** 2);
	$totalprice=$totalprice + $tmpprice;
	$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
	$totalquant=$totalquant + $itemquant;
	$totalweight = $totalweight + $weight;
	$subtotal = $totalprice;
=pod
###	print MAIL sprintf "%-6.6s", $itemid;
	print MAIL sprintf "%-58.58s", $itemname;
	print MAIL sprintf "%7.7s", $itemquant;
	print MAIL sprintf "%10.10s", "$itemprice";
	print MAIL sprintf "%11.11s", "$tmpprice";
	print MAIL "\n";
=cut

$articulosmail .= "<tr class=\"producto\" style=\"border: thin solid #ededf9\">
<td width=\"50%\" align=\"left\">
$itemname
</td>
<td width=\"20%\" align=\"right\">
$itemprice&euro;
</td>
<td width=\"10%\" align=\"center\">
$itemquant
</td>
<td width=\"20%\" align=\"right\">
$tmpprice&euro;
</td>
</tr>";

##### verifica que se han introducido lineas
	if ($itemname eq '' || $totalprice < 1){
	}
	else
	{
	$lineasreales = 1;
	}
	}

$articulosmail = encode("iso-8859-1", decode("utf8",$articulosmail));
print MAIL $articulosmail;



=pod
print MAIL "--------------------------------------------------------------------------------------\n";
print MAIL "Subtotal:";
print MAIL sprintf "%78.78s", "$totalprice\ Euros\n";
=cut

&precioportes;

$totalprice += $portes;
$portes = int($portes * (10 ** 2) + .5) / (10 ** 2);
$_ = $portes;

=pod
print MAIL "Portes:  ";
print MAIL sprintf "%78.78s", "$portes\ Euros\n";
=cut

### Taxes
if ($tax eq '0') {
	# Do nothing
	}
## Always tax
elsif ($tax eq '2') {
	$taxtotal = $totalprice * $taxamt;
	$taxtotal = int($taxtotal * (10 ** 2) + .5) / (10 ** 2);
	$totalprice = $totalprice + $taxtotal;

}
## Format and print the tax
$taxtotal = int($taxtotal * (10 ** 2) + .5) / (10 ** 2);

=pod
print MAIL "I.V.A.:  ";
print MAIL sprintf "%78.78s", "$taxtotal\ Euros\n";
=cut

## Format and print the totalprice
$totalprice = int($totalprice * (10 ** 2) + .5) / (10 ** 2);
$totalpedido = $totalprice;
$_ = $totalprice;

=pod
print MAIL "Total:";
print MAIL sprintf "%81.81s" , "$totalprice\ Euros\n";
=cut

=pod
if ($FORM{'forpago'} eq 'Contrareembolso') {
if ($totalprice < 100){
$totalreembolso = $totalprice + 5;
}
else{
$totalreembolso = $totalprice * 1.05;
}
$totalreembolso = int($totalreembolso * (10 ** 2) + .5) / (10 ** 2);
print MAIL "Total Reembolso:";
print MAIL sprintf "%73.73s" , "$totalreembolso\ Euros\n";
}
=cut
print MAIL "\n\n";


## Print all the variables on the order form
undef %is_exclude;
for (@exclude) { $is_exclude{$_} = 1 }
   if ($CONFIG{'sort'} eq 'alphabetic') {
      foreach $key (sort keys %FORM) {
         # Print the name and value pairs in FORM array to mail.
         print MAIL "$key: $FORM{$key}\n\n" unless $is_exclude{$key};
      }
   }
   elsif ($CONFIG{'sort'} =~ /^order:.*,.*/) {
	  $CONFIG{'sort'} =~ s/order://;
      @sorted_fields = split(/,/, $CONFIG{'sort'});
      foreach $sorted_field (@sorted_fields) {
         # Print the name and value pairs in FORM array to mail.
         if ($FORM{$sorted_field}) {
            print MAIL "$sorted_field: $FORM{$sorted_field}\n\n" unless $is_exclude{$sorted_field};
         }
      }
   }
   else {

=pod
   print MAIL "$FORM{'realname'} $FORM{'Apellidos'}\n";
   print MAIL "Nombre Comercial: $FORM{'nombre_comercial'}\n";
   print MAIL "Razon social: $FORM{'razon_social'}\n";
   print MAIL "Dni: $FORM{'dni'}\n\n";

   print MAIL "Direccion: $FORM{'Direccion'}\n";
   print MAIL "C.P.: $FORM{'Codigo_Postal'} Ciudad: $FORM{'Ciudad'}\n";
   print MAIL "Provincia: $FORM{'Provincia'}\n\n";

   print MAIL "Tel_Comprador: $FORM{'Tel_comprador'}\n";
   print MAIL "Telefono: $FORM{'Telefono'}\n";
   print MAIL "Fax: $FORM{'Fax'}\n";
   print MAIL "E-mail: $FORM{'email'}\n\n";

   print MAIL "Comentario:\n$FORM{'Comentario'}\n";
   print MAIL "----------------------------------------\n";

   print MAIL "\n\nEste mensaje ha sido generado automáticamente al realizar su pedido, \n";
#   print MAIL "en breve le enviaremos la factura proforma con la forma de pago.\n\n";

   print MAIL "\nAsturalba\nPol. Ind. de Maqua, Sector C, Nave 10\n33418 Gozón - Asturias\nTel. 985 514 025 - Fax 985 515 846\nEmail: asturalba\@asturalba.com\n";
=cut





$partetotalmail = "</table>
<br>
<table width=\"99%\" align=\"center\" cellpadding=\"4\" class=\"producto\" style=\"border-collapse: collapse\">
<tr id=\"subtotal\" style=\"color:#666\">
<td width=\"50%\">&nbsp;
</td>
<td width=\"30%\" align=\"left\">
  Subtotal
</td>
<td width=\"25%\" align=\"right\">
  $subtotal&euro;
</td>
</tr>
<tr id=\"gastos\" style=\"color:#666\">
<td width=\"50%\">&nbsp;
</td>
<td width=\"30%\" align=\"left\">
  Gastos de envío
</td>
<td width=\"25%\" align=\"right\">
  $portes&euro;
</td>
</tr>
<tr id=\"iva\" style=\"color:#666\">
<td width=\"50%\">&nbsp;
</td>
<td width=\"30%\" align=\"left\">
  IVA
</td>
<td width=\"25%\" align=\"right\">
  $taxtotal&euro;
</td>
</tr>";

if ($FORM{'forpago'} eq 'Contrareembolso') {

if ($totalprice < 100){
$totalreembolso = $totalprice + 5;
$gastosreembolso = 5;
}
else{
$totalreembolso = $totalprice * 1.05;
$gastosreembolso = int(($totalreembolso - $totalprice) * (10 ** 2) + .5) / (10 ** 2);

}
$totalprice =  int($totalreembolso * (10 ** 2) + .5) / (10 ** 2);

$partetotalmail .= "<tr style=\"color:#666\">
  <td>&nbsp;</td>
  <td align=\"left\">Gastos de reembolso</td>
  <td align=\"right\">$gastosreembolso&euro;</td>
</tr>";

}
elsif($FORM{'forpago'} eq 'Paypal') {

$totalpaypal = $totalprice * 1.03;
$gastospaypal = int(($totalpaypal - $totalprice) * (10 ** 2) + .5) / (10 ** 2);

$totalprice =  int($totalpaypal * (10 ** 2) + .5) / (10 ** 2);
$partetotalmail .= "<tr style=\"color:#666\">
  <td>&nbsp;</td>
  <td align=\"left\">Gastos Paypal</td>
  <td align=\"right\">$gastospaypal&euro;</td>
</tr>";

}


$partetotalmail .= "<tr id=\"total\" style=\"font-weight:bold\">
<td width=\"50%\">&nbsp;
</td>
<td width=\"30%\" align=\"left\" style=\" border-width: 1px; border-left-style: solid; border-right-style: none; border-right-width: medium; border-top-style: solid;border-bottom-style:solid; bordercolor:#000080\">
  Total
</td>
<td width=\"25%\" align=\"right\" style=\"border-width: 1px; border-right-style: solid; border-top-style: solid;  border-bottom-style: solid; padding-right: 4px; padding-top: 1px; padding-bottom: 1px; border-left-style:none; border-left-width:medium; bordercolor:#000080\">
  $totalprice&euro;
  </div>
</td>
</tr>
</table>";

$partetotalmail = encode("iso-8859-1", decode("utf8",$partetotalmail));
print MAIL $partetotalmail;

$partepagomail = "<br>
<table width=\"99%\" align=\"center\" cellpadding=\"2\">
<tr>
<th style=\"padding: 8px; padding-left: 16px; padding-right: 16px; margin: 6px; font-size: 16px; font-weight: normal; text-align: left; background-color: #ededf9; border: thin solid #000080\"><strong>
Forma de pago</strong></th>
<tr>
<td style=\"padding-top: 10px\">";

#<td>Referencia pago tarjeta: $storename-$host-$orderid</td>
if ($FORM{'forpago'} eq 'Tarjeta') {
$partepagomail .= "
<strong>Tarjeta de crédito</strong></td>
</tr>
<tr>
<td></td>
</tr>
</table>";}
elsif ($FORM{'forpago'} eq 'Transferencia') {
$partepagomail .= "
<strong>Transferencia bancaria</strong></td>
</tr>
<tr>
  <td>Puedes realizar el pago en los siguientes números de cuenta:</td>
</tr>
<tr>
  <td style=\"color: #000080; font-weight: bold;\">BANCO SABADELL ES64 0081 5716 4300 0109 0615</td>
</tr>
<tr>
<td>Por favor, indícanos como concepto en la transferencia el número de pedido: <strong>$numpedi</strong><br> 
Para agilizar el envío puedes enviar el justificante de pago a nuestro correo <a href=\"mailto:asturalba\@asturalba.com\">asturalba\@asturalba.com</a>.</td>
</tr>
</table>";}
elsif ($FORM{'forpago'} eq 'Paypal') {
$partepagomail .= "
<strong>Paypal</strong></td>
</tr>
<tr>
<td></td>
</tr>
</table>";}
elsif ($FORM{'forpago'} eq 'Contrareembolso') {
$partepagomail .= "<strong>Contrareembolso</strong></td>
</tr>
<tr>
<td>Por favor, tenga el importe de $totalprice&euro; preparado para cuando el transportista pase a entregar el pedido.</td>
</tr>
</table>";
}
else{
$partepagomail .= "
</td>
</tr>
<tr>
<td></td>
</tr>
</table>"
}


$partepagomail = encode("iso-8859-1", decode("utf8",$partepagomail));
print MAIL $partepagomail;


$partefinmail = "<br>
<table width=\"99%\" align=\"center\" cellpadding=\"2\">
<tr>
<th style=\"width: 40%; padding: 8px; padding-left: 16px; padding-right: 16px; margin: 6px; font-size: 16px; font-weight: normal; text-align: left; background-color: #ededf9; border: thin solid #000080\"><strong>
Datos de envío y facturación</strong></th>
<tr>
<td style=\"padding-top: 10px\">
Nombre o empresa: $FORM{'realname'}</td>
</tr>
<tr>
<td>
E-mail: $FORM{'email'}</td></tr>
<tr>
<td>
Teléfono: $FORM{'Tel_comprador'}</td></tr>";

if ($FORM{'Direccion'} eq '' && $FORM{'Codigo_Postal'} eq '' && $FORM{'Ciudad'} eq '' && $FORM{'Provincia'} eq '' && $FORM{'nombre_comercial'} eq '' && $FORM{'dni'} eq '' && $FORM{'Comentario'} eq ''){

}
else{
$partefinmail .= "
<tr>
<td>
Dirección: $FORM{'Direccion'}</td>
</tr>
<tr>
<td>
Código Postal: $FORM{'Codigo_Postal'}</td></tr>
<tr>
<td>
Población: $FORM{'Ciudad'}</td></tr>
<tr>
<td>
Provincia: $FORM{'Provincia'}</td></tr>
<tr>
<td>
Persona de contacto: $FORM{'nombre_comercial'}</td></tr>
<tr>
<td>
DNI/NIF: $FORM{'dni'}</td></tr>
<tr>
<td>
Observaciones: $FORM{'Comentario'}</td></tr>"
}

$partefinmail .= "
</table>
<br>
<div class=\"noprint\">
<hr color=\"#ededf9\" noshade 1px>

<table width=\"99%\">
<tr>
  <td align=\"center\">
    <img src=\"http://www.asturalba.com/images/calidad-servicio-slogan.png\" alt=\"Calidad y servicio desde 1989\" longdesc=\"http://www.asturalba.com/\"></td>
</tr>
</table>
<table width=\"90%\" align=\"center\">
<tr>
  <td style=\"font-size: 10px; color: #000080\" align=\"left\">
  Asturalba Iberia, SL<br>
  B74409178<br>
  Pol. Ind. Maqua, Sector C, Nave 10<br>
  33418 - Gozón - Asturias - España
  </td>
  <td width=\"5px\">&nbsp;</td>
  <td style=\"font-size: 10px; color: #000080\" align=\"right\">
  Tel. 985 514 025<br>
  Fax 985 515 346<br>
  <a href=\"mailto:asturalba\@asturalba.com\">asturalba\@asturalba.com</a><br>
  <a href=\"http://www.asturalba.com/\" title=\"www.asturalba.com\">www.asturalba.com</a></td>
</tr>
</table>
<table width=\"99%\">
<tr>
  <td style=\"font-size: 14px;color: #000080; vertical-align: top\" align=\"center\">&nbsp;</td>
</tr>
<tr>
  <td width=\"50%\" style=\"font-size: 14px;color: #000080; vertical-align: top\" align=\"center\">
  Gracias por confiar en nosotros.<br>
  Síguenos en:<br><br>
  <div style=\"vertical-align: bottom\"><a href=\"https://es-es.facebook.com/asturalba\" target=\"_blank\"><img src=\"http://www.asturalba.com/images/icons/facebook.gif\" alt=\"facebook\" width=\"30\" height=\"30\" longdesc=\"https://es-es.facebook.com/asturalba\"></a>&nbsp;&nbsp;&nbsp;<a href=\"https://twitter.com/asturalba\" target=\"_blank\"><img src=\"http://www.asturalba.com/images/icons/twitter.gif\" alt=\"twitter\" longdesc=\"https://twitter.com/asturalba\"></a>&nbsp;&nbsp;&nbsp;<a href=\"https://www.youtube.com/user/asturalba\" target=\"_blank\"><img src=\"http://www.asturalba.com/images/icons/youtube.gif\" alt=\"Youtube\" longdesc=\"http://www.youtube.com/user/asturalba\"></a>&nbsp;&nbsp;&nbsp;<a href=\"https://plus.google.com/+asturalba/posts\" target=\"_blank\"><img src=\"http://www.asturalba.com/images/icons/google.gif\" alt=\"Google+\" longdesc=\"https://plus.google.com/+asturalba/posts\"></a>&nbsp;&nbsp;&nbsp;<a href=\"https://es.pinterest.com/asturalba/\" target=\"_blank\"><img src=\"http://www.asturalba.com/images/icons/pinterest.gif\" alt=\"Pinterest\" longdesc=\"https://es.pinterest.com/asturalba/\"></a></div>
  </td>
  </tr>
  </table>
</div>
</body>
</html>";




$partefinmail = encode("iso-8859-1", decode("utf8",$partefinmail));

print MAIL $partefinmail;





#### si forma de pago tarjeta entonces ####

if ($FORM{'forpago'} eq 'Tarjeta') {
$totalprince = int($totalprice * 100);
open(REQUETE,">$reffile-$orderid");

print REQUETE "\PREM978$totalprince\r\n1\r\nC5698\r\nArticulos diversos\r\n1\r\n$totalprince\n";
   print REQUETE "$FORM{'realname'} $FORM{'Apellidos'}\n";
   print REQUETE "Nombre Comercial: $FORM{'nombre_comercial'}\n";
   print REQUETE "Razon social: $FORM{'razon_social'}\n";
   print REQUETE "Dni: $FORM{'dni'}\n\n";

   print REQUETE "Direccion: $FORM{'Direccion'}\n";
   print REQUETE "C.P.: $FORM{'Codigo_Postal'} Ciudad: $FORM{'Ciudad'}\n";
   print REQUETE "Provincia: $FORM{'Provincia'}\n\n";

   print REQUETE "Tel_Comprador: $FORM{'Tel_comprador'}\n";
   print REQUETE "Telefono: $FORM{'Telefono'}\n";
   print REQUETE "Fax: $FORM{'Fax'}\n";
   print REQUETE "E-mail: $FORM{'email'}\n\n";

   print REQUETE "Comentario:\n$FORM{'Comentario'}\n";
for ($i=1;$i<$SIZE;$i++) {
	$_=$LINES[$i];
	my($itemname, $itemprice, $itemquant, $weight,$itemid) = split(/\|/,$_);
	$tmpprice = $itemprice*$itemquant;
	$tmpprice = int($tmpprice * (10 ** 2) + .5) / (10 ** 2);
	$totalquant=$totalquant + $itemquant;
###	print MAIL sprintf "%-6.6s", $itemid;
	print REQUETE sprintf "%-58.58s", $itemname;
	print REQUETE sprintf "%7.7s", "$itemprice";
	print REQUETE sprintf "%10.10s", $itemquant;
	print REQUETE sprintf "%11.11s", "$tmpprice";
	print REQUETE "\n";
	}
}######fin if de la forma de pago#######

      #comentado# foreach $key (keys %FORM) {
         # Print the name and value pairs in FORM array to html.
         #comentado# print MAIL "$key: $FORM{$key}\n\n" unless $is_exclude{$key};
      #comentado# }
   }


$totalprice = 0;   

close (MAIL);
    # BEGIN: Win32 mods
    # If we're running under Windows, we actually send mail here...
	



if ($lineasreales == 1){

    if ($SERVER_OS eq "WIN") {

   #### $resultado = get("http://www.asturalba.com/email1.php?cuerpo=$reffile");
       #$BLAT_ARGS = "$reffile -t $mailcli ";#quite#$CONFIG{'recipient'}#
        #$BLAT_ARGS = "$reffile -t $mailcli ";

        #$BLAT_ARGS = "\"email2.html\" -to hector\@asturalba.com ";#quite#$CONFIG{'recipient'}#
	#$BLAT_ARGS = " -to hector\@asturalba.com ";#quite#$CONFIG{'recipient'}#
 	$BLAT_ARGS = "$reffile -to $FORM{'email'} -bcc serv.tecnico\@asturalba.com ";#quite#$CONFIG{'recipient'}#

        $BLAT_ARGS .= "-f asturalba\@asturalba.com ";
        $BLAT_ARGS .= "-s \"Tu pedido de Asturalba - $numpedi\" ";
       #$BLAT_ARGS .= "-i $FORM{'email'} " if defined($FORM{'email'});
	$BLAT_ARGS .= "-i asturalba\@asturalba.com ";
        $BLAT_ARGS .= "-q ";
	$BLAT_ARGS .= "-html";
	#$BLAT_ARGS .= " -body 'this is the mesage body'";
        system ("$mailprog $BLAT_ARGS");

	#### EMAIL PARA NOSOTROS ######
#$resultado = get("http://www.asturalba.com/email1.php?cuerpo=$reffile&");
$resultado = get("http://www.asturalba.com/email1.php?cuerpo=$reffile&corre=$FORM{'email'}&numpe=$numpedi");		
	$BLAT_ARGS = "$reffile -to asturalba\@asturalba.com -bcc isaac\@asturalba.com ";#quite#$CONFIG{'recipient'}#
        $BLAT_ARGS .= "-f asturalba\@asturalba.com ";
        $BLAT_ARGS .= "-s \"$numpedi - Tu pedido de Asturalba\" ";
       #$BLAT_ARGS .= "-i $FORM{'email'} " if defined($FORM{'email'});
	$BLAT_ARGS .= "-i asturalba\@asturalba.com ";
        $BLAT_ARGS .= "-q ";
	$BLAT_ARGS .= "-html";
	#$BLAT_ARGS .= " -body 'this is the mesage body'";
        system ("$mailprog $BLAT_ARGS");

	
	






        #unlink $WIN_TEMPFILE;


	#system("$mailprog $reffile -f asturalba\@asturalba.com -t hector\@asturalba.com -s \"asunto\" -q -html");
    }
}

    
}
######################### AQUI SE ACABA EL MAIL PARA EL CLIENTE #####################
# Get the hostname, for file reference


sub grabapedi {

$pat1 = "$basepath$delim" . "Data" . "$delim" . "pedidosweb" . $delim . "$host-$numpedi";
open(REQUETER,">$pat1");

   print REQUETER "$FORM{'realname'} $FORM{'Apellidos'}\n";
   print REQUETER "Nombre Comercial: $FORM{'nombre_comercial'}\n";
   print REQUETER "Razon social: $FORM{'razon_social'}\n";
   print REQUETER "Dni: $FORM{'dni'}\n\n";

   print REQUETER "Direccion: $FORM{'Direccion'}\n";
   print REQUETER "C.P.: $FORM{'Codigo_Postal'} Ciudad: $FORM{'Ciudad'}\n";
   print REQUETER "Provincia: $FORM{'Provincia'}\n\n";

   print REQUETER "Tel_Comprador: $FORM{'Tel_comprador'}\n";
   print REQUETER "Telefono: $FORM{'Telefono'}\n";
   print REQUETER "Fax: $FORM{'Fax'}\n";
   print REQUETER "Forma de pago: $FORM{'forpago'}\n";
   print REQUETER "E-mail: $FORM{'email'}\n\n";

   print REQUETER "Comentario:\n$FORM{'Comentario'}\n";
for ($i=1;$i<$SIZE;$i++) {
	$_=$LINES[$i];
	my($itemnameR, $itempriceR, $itemquantR, $weightR,$itemidR) = split(/\|/,$_);
	$tmppriceR = $itempriceR*$itemquantR;
	$tmppriceR = int($tmppriceR * (10 ** 2) + .5) / (10 ** 2);
	$totalquantR=$totalquantR + $itemquantR;
###	print MAIL sprintf "%-6.6s", $itemid;
	print REQUETER sprintf "%-58.58s", $itemnameR;
	print REQUETER sprintf "%7.7s", "$itempriceR";
	print REQUETER sprintf "%10.10s", $itemquantR;
	print REQUETER sprintf "%11.11s", "$tmppriceR";
	print REQUETER "\n";
	}

close (REQUETER);

#### manda grabado $resultado = get("http://www.asturalba.com/email1.php?cuerpo=$pat1");

}



sub get_host {
$host = $ENV{'REMOTE_HOST'};
$reffile = "$tmpdir$delim$storename-$host";
}

sub check_file {
$exists = '1' if -e "$reffile";
if ($exists eq '1') {
	&parse_file;
	}
	else {
	&make_file;
	}
}

# Parse the cart
sub parse_file {
open (REFFILE,"$reffile") || die "Can't Open $reffile(r): $!\n";
@LINES=<REFFILE>;
close(REFFILE);
$SIZE=@LINES;
$_=$LINES[0];
($usertime, $userhost, $useragent, $usercurr, $usership, $usertax) = split(/\|/,$_);
}

# If they don't have a cart, make them one.
sub make_file {
open(REFFILE,">$reffile");
print REFFILE "$date\| $ENV{'REMOTE_HOST'}\| $ENV{'HTTP_USER_AGENT'}\|";
if ($multicurr eq 1) { print REFFILE "NULL\|"; } else { print REFFILE "1\|"; }
open (SHIPDB, "$basepath$delim$shipdb");
my(@SHIP) = <SHIPDB>;
close(SHIPDB);
my(@ships)=split(/\|/,$SHIP[0]);
print REFFILE "$ships[0]\|\n";
close(REFFILE);
}

#Delete a cart
sub delete_cart {
unlink($reffile);
}

# Delete an item from the cart
sub delete_item {
open (REFFILE,"$reffile") || print "Content-type: text/html\n\n Can't Open $reffile(r): $!\n";
@LINES=<REFFILE>;
close(REFFILE);
$SIZE=@LINES;

open (REFFILE,">$reffile") || print "Content-type: text/html\n\n Can't Open $reffile(r): $!\n";
print REFFILE "$date\| $ENV{'REMOTE_HOST'}\| $ENV{'HTTP_USER_AGENT'}\|NULL\|NULL\|\n";
for ($i=1;$i<$SIZE;$i++) {
   	$_=$LINES[$i];
	my($itemname, $itemprice, $itemquant, $weight, $itemid) = split(/\|/,$_);
	if ($FORM{$itemname} eq $itemname) {
		# Do nothing
		}
		else { print REFFILE $_; }
	}
close(REFFILE);
&review_items;
}

# Get the date.
sub get_date {
   @days =
('Domingo','Lunes','Martes','Miercoles','Jueves','Viernes','Sabado');
   @months = ('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio',
              'Agosto','Septiembre','Octubre','Noviembre','Diciembre');

   ($sec,$min,$hour,$mday,$mon,$year,$wday) =
localtime(time);
   if ($hour < 10) { $hour = "0$hour"; }
   if ($min < 10) { $min = "0$min"; }
   if ($sec < 10) { $sec = "0$sec"; }

   $date = "$days[$wday], $months[$mon] $mday, 2$year - $hour\:$min\:$sec";
   $anio = $year - 100;
   #$date2 = " $days[$wday], $mday de $months[$mon] de 20$anio";
	$date2 = " $mday/". ($mon + 1) . "/20$anio";
	
	
}

# Did they fill out all necesary info?
sub check_required {

   foreach $require (@required) {
      if ($require eq 'bgcolor' ||
          $require eq 'background' ||
          $require eq 'link_color' ||
          $require eq 'vlink_color' ||
          $require eq 'alink_color' ||
          $require eq 'text_color' ||
	  	  $require eq 'sort' ||
          $require eq 'title' ||
          $require eq 'print_config' ||
          $require eq 'return_link_title' ||
          $require eq 'return_link_url') {

         if (!($CONFIG{$require}) || $CONFIG{$require} eq ' ') {
            push(@ERROR,$require);
         }
      }
      elsif (!($FORM{$require}) || $FORM{$require} eq ' ') {
         push(@ERROR,$require);
      }
   }

   if (@ERROR) {
      &error('missing_fields', @ERROR);
   }

}

# Warning Warning.
sub error {
&print_header;
   ($error,@error_fields) = @_;

if ($error eq 'missing_fields') {


      print "   <h1>Error: Blank Fields</h1>\n\n";
      print "The following fields were left blank in your submission form:<p>\n";

      # Print Out Missing Fields in a List.
      print "<ul>\n";
      foreach $missing_field (@error_fields) {
         print "<li>$missing_field\n";
      }
      print "</ul>\n";

      # Provide Explanation for Error and Offer Link Back to Form.
      print "<p><hr size=7 width=75\%><p>\n";
      print "These fields must be filled out before you can successfully submit\n";
      print "the form.  Please return to the <a href=\"$ENV{'HTTP_REFERER'}\">Fill Out Form</a> and try again.\n";
   }
 elsif ($error eq 'noship') { 
 print "<h2>Error: Shipping not Set!</h2><br> Please go back and calcualte shipping!\n";
 }
&print_footer;
   exit;
}


sub track_order {
## First make a tracking id. A combo of the current time, and the PID.
$orderid = time() . "-" . $$;

# Write the order to the tracking DB.
open (TRACK, ">>$trackdb");
print TRACK $orderid . "\|";
foreach $key (%FORM) {
	print TRACK "$key\=$FORM{$key}\&";
	}
print TRACK "\|pending\|NONE\|\n";
close(TRACK);
}

sub number { $a <=> $b }

# END s-mart.pl
