#!/usr/bin/perl
#
# Install (a modified version of) this program in your webserver's cgi-bin directory.
# 
# This demo program prints the order into /tmp/yahoo-order; you will probably want
# to do something more interesting with it. Replace the function handle_order
# It also puts the raw key-value fields into /tmp/yahoo-order.raw
#
# Order fields are:
#
# ID
#   A unique order identifier including the Y! Store account name, such as acme-451
#   
# Date
#   Standard date format, in GMT
# 
# {Ship,Bill}-Name, -Firstname, -Lastname
#   These fields are always defined. If your store is configured to have separate first and last
#   name fields on the order page, then -Name will be the concatenation of them. If it is configured to have
#   a single entry field, then the split into Firstname and Lastname will be a guess.
#
#   If you have custom fields, they will appear here too. The field names look like "Ship-Pack in dry ice"
#   for an extra shipping field, and similarily for a billing field.
#
# {Ship,Bill}-Address1, -Address2, -City, -State, -Zip, -Country, -Phone, -Email
#   The shipping and billing address. Both will be filled in, and will be the same if the
#   user only gave one address
#
# Card-Name, -Number, -Expiry
#   Credit card info
#
# Item-Id-N, -Code-N, -Quantity-N, -Unit-Price-N, -Description-N, -Url-N,
#   For values of N from 1 to Item-Count, the relevant attributes of each item are given.
#   This script contains code to separate these into an @items array.
#   Code is from the "Code" field when editing the item, typically an SKU or ISBN
#   Unit-Price takes any quantity pricing into account
#
# Tax-Charge, Shipping-Charge, Total
#   Extra charges, and the order total
# 

require 5.001;
use strict;

#$ENV{'USER'}='encrypt'; #for gpg
#$ENV{'HOME'}='/home/cust1/encrypt'; #for gpg

if ($ENV{'REQUEST_METHOD'} ne "POST") {
    die("Expecting a POST, bailing");
}

my $o;
read(STDIN,$o,$ENV{'CONTENT_LENGTH'});

my %o;
for (split(/&/,$o)) {
    $_ =~ s/\+/ /g;
    my($key,$val) = split(/=/,$_,2);
    for ($key,$val) {
        $_ =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/ge;
    }
    $o{$key} = $val;
}

my @items;
my $i;
for ($i=1; $i<=$o{'Item-Count'}; $i++) {
    push(@items,{map {($_,$o{"Item-$_-$i"})} qw(Id Code Quantity Unit-Price Description Url)});
}

#open(RAW,">/tmp/yahoo-order.raw") or die("Can't open raw");
#for (sort keys %o) {
#    print RAW "$_ = $o{$_}\n";
#}
#close(RAW);
print "Status: 200 OK\n";
print "\n";
print "b4\n";
&handle_order(\%o,@items);

# A successful delivery is indicated by a good HTTP result code.
print "Status: 200 OK\n";
print "\n";
exit(0);


######################################################################
# Replace this function with something that does what you want
#   $info gets a hash ref of all the order fields, like Ship-Name.
#   @items gets an array of hash refs, one for each item.

sub handle_order {
	my($info,@items)=@_;

	my($store,$order_no)=($info->{'ID'}=~/([a-zA-Z]+)-([0-9]+)$/);
	my $tmpfile="/home/cust1/interch/catalogs/yahoo_$store/orders/delete.txt";
	
	my %shipcodes=('UPS Ground Residential'=>'4',
				   'Ground'=>'4',
				   '2nd Day Air'=>'2',
				   'Next Day Air'=>'1');
				   
	my %prefixcodes=('bobsclub'=>'B',
				   'digiexpo'=>'E');
				   
	my %salesmancodes=('bobsclub'=>'BC',
				   'digiexpo'=>'DE');
				   
	$info->{'Bill-Phone'}=~s/\D//g;
	$info->{'Ship-Phone'}=~s/\D//g;
	
	$info->{'Bill-Phone'}=~s/(\d{3,3})(\d{3,3})(.+)/$1-$2-$3/;
        $info->{'Ship-Phone'}=~s/(\d{3,3})(\d{3,3})(.+)/$1-$2-$3/;
	
	$info->{'Card-Number'}=~s/\D//g;
	$info->{'Card-Number'}=Encrypt($info->{'Card-Number'},$tmpfile);

	my ($ExpiryMonth,$ExpiryYear)=($info->{'Card-Expiry'}=~/([0-9]{1,2})\/[0-9][0-9]([0-9][0-9])/);
	
	if(length($ExpiryMonth)==1)
	{
		$ExpiryMonth='0'.$ExpiryMonth;
	}
	my ($b_fname,$b_lname)=($info->{'Bill-Name'}=~/^(.+)\s(\w+)$/);
	my @BillInfo= (
		'BILLING',
		$info->{'Bill-Phone'},
		$b_fname,
		$b_lname,
		'',#company
		$info->{'Bill-Address1'},
		$info->{'Bill-Address2'},
		$info->{'Bill-City'},
		$info->{'Bill-State'},
		$info->{'Bill-Zip'},
		$info->{'Card-Number'},
		"$ExpiryMonth$ExpiryYear"
		);
	
	my ($fname,$lname)=($info->{'Ship-Name'}=~/^(.+)\s(\w+)$/);	
	my @ShipInfo=(
		'SHIPPING',
		$info->{'Bill-Phone'},
	 	$fname,
                $lname,
                '',#company
                $info->{'Ship-Address1'},
		$info->{'Ship-Address2'},
		$info->{'Ship-City'},
		$info->{'Ship-State'},
		$info->{'Ship-Zip'},
		$info->{'Bill-Email'}
		);
	
	my $item;
	my @ItemLines;
	for $item (@items) {
		
		push(
			@ItemLines,
			[
				"ORDER",
				$info->{'Bill-Phone'},	
				$item->{'Code'},
				&ZeroPadded(&Digits($item->{'Quantity'}),6),
				&ZeroPadded(&Digits($item->{'Unit-Price'}),8)
			]
		);
	}
	
	my @misc=( 
		'MISC',
		$info->{'Bill-Phone'},
		$shipcodes{$info->{'Shipping'}},
		&ZeroPadded(&Digits($info->{'Shipping-Charge'}),6),
		"",
		$salesmancodes{$store}.$order_no,
		$prefixcodes{$store},
		$salesmancodes{$store},
		$info->{'Ship-Phone'},
		&FormatDate($info->{'Date'})
		);
	my @comment_lines;			
	
	#take care of comments
	my @comments=&Delineate($info->{'Comments'},69);
	for(@comments){
		push(
			@comment_lines,
			[
				'NOTE',
				$info->{'Bill-Phone'},
				$_
			]
		);
	}
	
	if(uc($info->{'Ship-includeinv'}) eq 'YES')
	{
		push(
			@comment_lines,
			[
				'NOTE',
				$info->{'Bill-Phone'},
				'I M P O R T A N T: DO NOT ENCLOSE INVOICE WITH ORDER!'
			]
		);
	}
	
	if (exists $info->{'Warning'})
	{
		push(
			@comment_lines,
			[
				'Note',
				$info->{'Bill-Phone'},
				"W A R N I N G: $info->{'Warning'}"
			]
		);
	}
	
	my $orderfile=$salesmancodes{$store};
	open(OUT,">/home/filmart/catalogs/yahoo_$store/orders/$orderfile$order_no.txt") or print('Cant open order output file, '.$!);
		PrintItem(\@BillInfo);
		PrintItem(\@ShipInfo);
		for(@ItemLines){
			PrintItem($_);
		}
		PrintItem(\@misc);
		for(@comment_lines){
			PrintItem($_);
		}
	close(OUT);
	
}

sub Digits
{
	my ($thenum)=@_;
	$thenum=~s/[^0-9]//g;
	return $thenum;
}

#---------------------------------------------------------------------------------------------------------------------------
sub ZeroPadded
{
	my($thenum, $howmany)=@_;
	my $zeros;
	for(1..$howmany)
	{	
		$zeros.='0'; 
	}
	my $padded=substr($zeros.$thenum,-$howmany,$howmany);
	return $padded;
}

#---------------------------------------------------------------------------------------------------------------------------
sub FormatDate
{
	my($date)=@_;
	$date=~tr/a-z/A-Z/;
	my ($mon,$day,$year)=($date=~/[A-Z]{3,3}\s+([A-Z]{3,3})\s+([0-9]{1,2})\s+[0-9]{2,2}.[0-9]{2,2}.[0-9]{2,2}\s+[0-9]{2,2}([0-9]{2,2})/);
	#Wed Jan 31 00:37:23 2001 GMT
	my %months=(
			'JAN'=>'01',
			'FEB'=>'02',
			'MAR'=>'03',
			'APR'=>'04',
			'MAY'=>'05',
			'JUN'=>'06',
			'JUL'=>'07',
			'AUG'=>'08',
			'SEP'=>'09',
			'OCT'=>'10',
			'NOV'=>'11',
			'DEC'=>'12'
			);
			
	$day=&ZeroPadded($day,2);
	return "$months{$mon}$day$year";
			
}

#---------------------------------------------------------------------------------------------------------------------------
sub PrintItem
{	
	my ($arref)=@_;
	print OUT join('|',@{$arref})."\n";
}


#---------------------------------------------------------------------------------------------------------------------------
sub Encrypt
{
	my ($value,$tmpfile)=@_;
	local($/)=undef;
	
	my $cmd="/usr/bin/gpg --cipher-algo BLOWFISH --batch --always-trust --output $tmpfile -e -a -r 'c_klar\@c-cs.com' <<EOF\n$value\nEOF\n";
	my $res=`$cmd`;
	
	open(FILE,"$tmpfile") or die("could'nt open $tmpfile, $!");
	my $retval=<FILE>;
	close(FILE);
	
	unlink($tmpfile);
	$retval=~s/\n|\r/\@NL\@/g;
	return $retval;
}

#---------------------------------------------------------------------------------------------------------------------------
sub Delineate
{
  my ($origtext,$linesize)=@_;
  my $pos=0;
  my @lines;
  my $safetycounter;
  my @rawlines=split(/[\x0d\x0a]+/,$origtext);
  my $line;
  foreach $line(@rawlines)
  {
  	push @lines,($line=~/(.{1,$linesize})/g);
  }
  return @lines;
}
