<?php
	/*
	** File: order_express
	** Description: single page for billing and shipping
	** Version: $Revision: 1.31 $
	** Created: 08/10/1999
	** Author: Leon Atkinson
	** Email: leon@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/02/05 00:23:48 $
	** Log : $Log: order_express,v $
	** Log : Revision 1.31  2000/02/05 00:23:48  leon
	** Log : Removing number_format in favor of formatMoney
	** Log :
	** Log : Revision 1.30  2000/02/04 18:57:24  leon
	** Log : Removing delete link from basket contents.  It was piggy-backed unto
	** Log : the code for updating the rest of the basket stuff, but it wasn't
	** Log : working.  It was causing the loss of all gift wrap selections.
	** Log :
	** Log : Revision 1.29  1999/12/09 04:00:38  jj
	** Log : Fixed some broken JavaScript (bug found by John Ashton).
	** Log :
	** Log : Revision 1.28  1999/12/08 00:55:11  leon
	** Log : Pulled functions for creating table rows out of addressFunctions and
	** Log : generalized them.  I'm leaving wrappers for the old functions, but I
	** Log : will removed them in the coming weeks.
	** Log :
	** Log : Revision 1.27  1999/12/06 21:17:28  leon
	** Log : ECML compliance
	** Log : Overhauled address functions to use ECML form field names.  Ditto with
	** Log : the billing fields on the checkout forms.  Note the change to build.sql.
	** Log : Yes, the address table changed to accomodate new fields.  The billing
	** Log : table changed too.
	** Log :
	** Log : Revision 1.26  1999/11/09 00:28:17  leon
	** Log : Changed use of notes column.  This column now stores an array of variation
	** Log : IDs in serialized form.  Names for attributes and variations are pulled
	** Log : from the database using two new functions in the attribute_functions
	** Log : include module.
	** Log :
	** Log : Revision 1.25  1999/11/08 22:32:29  leon
	** Log : Added prepareText() function to use everywhere we were using htmlentities.
	** Log :
	** Log : Revision 1.24  1999/11/05 18:17:54  leon
	** Log : Reorganized coupon code.
	** Log :
	** Log : Revision 1.23  1999/11/04 21:35:44  leon
	** Log : Cleaned up the use of paths.  Paths are now all set in index.php3 as
	** Log : constants.  Example settings for Apache/Unix, Apache/Win32, and IIS.
	** Log :
	** Log : Revision 1.22  1999/11/02 20:49:44  leon
	** Log : Added constant to control use of coupons
	** Log :
	** Log : Revision 1.21  1999/11/02 19:30:02  leon
	** Log : Added line to include variation functions that was mistakenly deleted.
	** Log :
	** Log : Revision 1.20  1999/11/02 18:23:14  chris
	** Log : Added support for coupons.
	** Log :
	** Log : Revision 1.19  1999/10/26 17:31:37  leon
	** Log : Removed constants defining variations.  Instead functions wrap the tables.
	** Log : They use caching to reduce the number of database queries.
	** Log :
	** Log : Revision 1.18  1999/10/25 22:41:35  leon
	** Log : Made constant for privacy statement, printed statement on relavant pages.
	** Log :
	** Log : Revision 1.17  1999/10/14 20:42:20  leon
	** Log : Added formatMoney function, cleaned up references to GIFTWRAP_COST.
	** Log :
	** Log : Revision 1.16  1999/10/13 22:19:05  chris
	** Log : Moving text into constants in preparation of localization support.
	** Log :
	** Log : Revision 1.15  1999/10/13 00:42:32  chris
	** Log : Moving text into constants in preparation of localization support.
	** Log :
	** Log : Revision 1.14  1999/10/11 23:04:11  leon
	** Log : Removed all require()'s, added block to stop double include()'s
	** Log :
	** Log : Require wasn't giving any performance advantage because it was always
	** Log : being called with a variable.  Futhermore, using return inside a
	** Log : require()'d file does not work in PHP4.
	** Log :
	** Log : Revision 1.13  1999/10/04 22:09:57  leon
	** Log : Removed getInvoiceID.  The active invoice is now added to $UserInfo
	** Log : by the check sid functionality in init.
	** Log :
	** Log : Revision 1.12  1999/10/04 20:03:47  leon
	** Log : This is the first step in re-organizing include files.  The browser cloaking
	** Log : variables have been moved in to include/init.  Whether they are generated
	** Log : at all is controlled by constant in global_settings.  They get set into
	** Log : constants just to be proper, since they shouldn't be changed.  Also, the
	** Log : check_sid module has been moved into include/init, which gets rid of an
	** Log : include().
	** Log :
	** Log : Revision 1.11  1999/09/16 17:56:02  jj
	** Log : There was a bug created in Dantz because of the lack of a comment (my fault). I've added an appropriate comment.
	** Log :
	** Log : Revision 1.10  1999/09/10 00:21:09  jj
	** Log : Changed include("addressfunctions") -> require("addressfunctions");
	** Log :
	** Log : Revision 1.9  1999/09/09 22:19:38  jj
	** Log : No longer any need to use the variable $addressFunctionsDefined.
	** Log :
	** Log : Revision 1.8  1999/08/23 23:38:43  jj
	** Log : Added JavaScript to order_express so that the user can click to have billing info = shipping info (instead of filling it out twice).
	** Log :
	** Log : Revision 1.7  1999/08/18 22:32:19  leon
	** Log : Returning opening PHP tag to XML-friendly tag
	** Log :
	** Log : Revision 1.6  1999/08/18 19:12:46  jj
	** Log : Painstakingly dealt with the following question: which address fields should we
	** Log : ask for, which should we require. Reasonable defaults set up.
	** Log :
	** Log : Revision 1.5  1999/08/18 16:46:39  jj
	** Log : Fixed bug: when you updated quantities on order_express, it returned you to the wrong SCREEN.
	** Log :
	** Log : Revision 1.4  1999/08/17 17:56:42  jj
	** Log : Modularized everything to do with addresses. Please see include/addressFunctions
	** Log :
	** Log : Revision 1.3  1999/08/11 20:05:29  jj
	** Log : Fixed any references to the gift wrap variation so that it uses the global constant.
	** Log :
	** Log : Revision 1.2  1999/08/11 19:43:32  jj
	** Log : Replaced all instances of eMail with email or Email (as fitting).
	** Log :
	** Log : Revision 1.1  1999/08/10 22:49:43  leon
	** Log : Added "Express Order" screen that allows the user to set shippng and
	** Log : info all on one page.  It was added to the side nav, too.
	** Log :
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	*/

	// Address related functions
	include(APPLICATION_ROOT . "/modules/include/addressFunctions");

	//get attribute functions
	include(APPLICATION_ROOT . "/modules/include/attribute_functions");


	$continueScript = TRUE;

	/*
	** Get items from invoice.
	*/
	$Query = "SELECT ss.ID, ss.ExternalSKU, s.Name, ss.ListPrice, " . 
		"ss.SalePrice, i.Name, ss.Quantity, ss.Freight, ss.GiftWrap, s.ID, " . 
		"ss.Notes ";
	$Query .= "FROM invoice_sku ss, sku s, item i ";
	$Query .= "WHERE ss.SKU = s.ID ";
	$Query .= "AND s.Item = i.ID ";
	$Query .= "AND ss.Invoice = " . $UserInfo['Invoice'] . " ";
	if ( !($DatabaseResult = mysql_query($Query, $DatabaseLink)) )
	{
		print("<!-- " . mysql_errno() . ":  " . mysql_error() . 
			"   Query was $Query -->\n");
		$continueScript = FALSE;
	}
	else
	{
		if ( !mysql_numrows($DatabaseResult) )
		{
			/* The user must have removed the last item from his basket. */
			print("<BR>" . L_ORDEREXPRESS_NOMOREITEMS . "<BR>\n");
			print("<P>" . L_ORDEREXPRESS_DELETETHISINVOICE . " ");
			print("<A HREF=\"" . ScreenURL("contents") . 
				"&ACTION=PURGE_INVOICE\">" . L_ORDEREXPRESS_HERE . "</A>.\n");
			$continueScript = FALSE;
		}
		else
		{
			while($DatabaseRow = mysql_fetch_row($DatabaseResult))
			{
				$basket["invoice_sku"][] = $DatabaseRow[0];
				$basket["ExternalSKU"][] = $DatabaseRow[1];
				$basket["Name"][] = $DatabaseRow[2];
				$basket["Price"][] = $DatabaseRow[3];
				$basket["SalePrice"][] = $DatabaseRow[4];
				$basket["ItemName"][] = $DatabaseRow[5];
				$basket["Quantity"][] = $DatabaseRow[6];
				$basket["Freight"][] = $DatabaseRow[7];
				$basket["GiftWrap"][] = $DatabaseRow[8];
				$basket["SKU"][] = $DatabaseRow[9];
				$basket["Notes"][] = unserialize($DatabaseRow[10]);
			}
		}
	}
		
	
	
	/* 
	** Get sku giftwrap-ability.
	*/
	if ($continueScript)
	{
		$Query = "SELECT SKU ";
		$Query .= "FROM sku_variation ";
		$Query .= "WHERE Variation = " . getVariationID(getAttributeID("Gift Wrap"), "Available") . " ";
		$Query .= "AND SKU in (0";
		for($index = 0; $index < count($basket["SKU"]); $index++)
		{
			$Query .= ", " . $basket["SKU"][$index];
		}		
		$Query .= ") ";
		if ( !($DatabaseResult = mysql_query($Query, $DatabaseLink)) )
		{
			print("<!-- " . mysql_errno() . ":  " . mysql_error() . 
				"   Query was: Query. -->\n");
			$continueScript = FALSE;
		}
		else 
		{
			while($DatabaseRow = mysql_fetch_row($DatabaseResult))
			{
				$GiftWrap[($DatabaseRow[0])] = TRUE;
			}
		}
	}
	
	
	
	/*
	** Output the table with all the items in it.
	*/
	if ($continueScript)
	{
		print(startForm('order_express', 'post', 'UPDATE_INVOICE_SKU'));
		print("<BR><TABLE BORDER=\"0\">\n");
		print("<TR>\n");
		print("<TH>" . L_ORDEREXPRESS_ITEM . "</TH>\n");
		print("<TH>" . L_ORDEREXPRESS_PRICE . "<SUP>*</SUP></TH>\n");
		print("<TH>" . L_ORDEREXPRESS_QUANTITY . "</TH>\n");
		print("<TH>" . L_ORDEREXPRESS_GIFTWRAP . "<SUP>*</SUP></TH>\n");
		print("<TH>" . L_ORDEREXPRESS_SUBTOTAL . "</TH>\n");
		print("</TR>\n");

		print("<TR>\n");
		print("<TD COLSPAN=\"5\"><HR COLOR=\"#800000\"></TD>\n");
		print("</TR>\n");

		/* Output the items. */
		for($index=0; $index < count($basket["invoice_sku"]); $index++)
		{
			//grabbing these values from the array will make
			//the code more readable hopefully (you're right, it does :P )
			$basket_ID = $basket["invoice_sku"][$index];
			$sku_ExternalSKU = $basket["ExternalSKU"][$index];
			$sku_Name = $basket["Name"][$index];
			$sku_Price = $basket["Price"][$index];
			$sku_SalePrice = $basket["SalePrice"][$index];
			$item_Name = $basket["ItemName"][$index];
			$basket_Quantity = $basket["Quantity"][$index];
			$sku_Freight = $basket["Freight"][$index];
			$sku_GiftWrap = $basket["GiftWrap"][$index];
			$sku_ID = $basket["SKU"][$index];
			$sku_Variation = $basket["Notes"][$index];
			if($sku_SalePrice > 0)
			{
				$sku_Price = $sku_SalePrice;
			}
			print("<TR>\n");

			/* 
			** Item description
			*/			
			print("<TD>");
			print("<FONT SIZE=\"2\">");
			print(prepareText($item_Name));
			if ($sku_Name != "")
			{
				print(": " . prepareText($sku_Name));
			}
			
			if(is_array($sku_Variation))
			{
				while(list($key, $variation_ID) = each($sku_Variation))
				{
					print("<BR>\n");
					
					$variation = getVariationInfo($variation_ID);
					$attribute = getAttributeInfo($variation["Attribute"]);
					
					print(prepareText($attribute["Name"] . ": " . $variation["Name"]));
				}
			}
			
			print("</FONT>");
			print("</TD>\n");

			/* 
			** Price (with extra shipping)
			*/			
			print("<TD>" . formatMoney($sku_Price));
			if($sku_Freight > 0)
			{
				print(" (" . formatMoney($sku_Freight) . ")");
			}
			print("</TD>\n");
	
			/* 
			** Quantity
			*/			
			print("<TD ALIGN=\"center\">");
			print("<INPUT TYPE=\"text\" SIZE=\"3\" ");
			print("NAME=\"inputBasket[$basket_ID]\" ");
			print("VALUE=\"$basket_Quantity\">");
			print("</TD>\n");

			/* 
			** Gift Wrap Checkbox
			*/			
			print("<TD ALIGN=\"center\">");
			if(isset($GiftWrap[$sku_ID]))
			{
				print("<INPUT TYPE=\"checkbox\" ");
				print("NAME=\"inputGiftWrap[$basket_ID]\" ");
				print("VALUE=\"Y\"");
				if($sku_GiftWrap == 'Y')
				{
					print(" CHECKED");
				}
				print(">");
			}
			else
			{
				print("N/A");
			}
			print("</TD>\n");

			/*
			** Subtotal
			*/
			$SubTotal = $basket_Quantity * ($sku_Price + $sku_Freight);
			if($sku_GiftWrap == 'Y')
			{
				$SubTotal += $basket_Quantity * GIFTWRAP_COST;
			}
			print("<TD ALIGN=\"right\">" . formatMoney($SubTotal) . 
				"</TD>\n");
			print("</TR>\n");
			print("<TR>\n");
			print("<TD COLSPAN=\"5\"><HR COLOR=\"#800000\"></TD>\n");
			print("</TR>\n");
		} /* Done outputting list of items. */
		
		/* Small print stuff. */
		print("<TR>\n");
		print("<TD COLSPAN=\"5\">");
		print("<FONT SIZE=\"1\">* " . L_ORDEREXPRESS_CHARGESINPARENTHESES . "</FONT><BR>\n");
		print("<FONT SIZE=\"1\">* " . L_ORDEREXPRESS_GIFTWRAPIS . "</FONT>");
		print("</TD>\n");
		print("</TR>\n");

		/* Submit button. */
		print("<TR>\n");
		print("<TD COLSPAN=\"5\" ALIGN=\"right\">");
		print("<INPUT TYPE=\"submit\" VALUE=\"" . L_ORDEREXPRESS_SUBMITCHANGES . "\">\n");
		print("</TD>\n");
		print("</TR>\n");

		/* Finish up the table and the form. */
		print("</TABLE>\n");
		print("</FORM>\n");
	} /* Done outputting the table of items. */

	if($continueScript)
	{
		/* Start the form, and do the main shipping address part. */
		print(StartForm("order_express", 'post', 'SET_ORDER_INFO', TRUE, 
			array("Ecom_SchemaVersion"=>"http://www.ecml.org/version1.0"), 
			'', '', 'shippingForm'));
	}

	/*
	** Done updating quantities, below this, we can start doing shipping 
	** information. 
	*/
	if ($continueScript)
	{
		print(L_ORDEREXPRESS_PLEASEFILLOUTSHIPPINGADDRESS . "<BR>\n");
	}



	/* 
	** Get default shipping and billing address information:
	** If this is the second time around (user omitted something), use those
	** values, otherwise, try to use $UserInfo (if available). Remember --
	** if you add or remove fields, make sure to update the JavaScript below.
	*/
	if(isset($Ecom_ShipTo_Postal_Name_First))
	{
		$shipAddress = getAddressFromEnvironment("Ecom_ShipTo_");
		$billingAddress = getAddressFromEnvironment("Ecom_BillTo_");
	}
	else if (isset($UserInfo))
	{
		$shipAddress = $UserInfo["Address"];
		$billingAddress = $UserInfo["Address"];
	}
	else
	{
		$shipAddress = 0;
		$billingAddress = 0;
	}
	


	/* 
	** Okay, time to actually get the shipping and billing information.
	*/ 			
	if ($continueScript)
	{
		print("<TABLE BORDER=\"0\">\n");
		print("<TR>\n");
		print("<TD COLSPAN=\"2\"><B>" . L_ORDEREXPRESS_SHIPPINGINFORMATION . "</B></TD>\n");
		print("</TR>\n");

		printAddressFields(
			$shipAddress, 
			"Ecom_ShipTo_", 
			"ALL", 
			0, 
			0, 
			FALSE);
		
		/* Shipping method. */
		print("<TR><TD>" . L_ORDEREXPRESS_SHIPPINGMETHOD . "</TD>\n");
		print("<TD><SELECT NAME=\"ship_Method\">\n");
		$Query = "SELECT ID, Name ";
		$Query .= "FROM shipping_method ";
		$Query .= "ORDER BY DisplayPrecedence ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		while($DatabaseRow = mysql_fetch_row($DatabaseResult))
		{
			print("<OPTION VALUE=\"$DatabaseRow[0]\"");
			if(isset($ship_Method) AND ($DatabaseRow[0] == $ship_Method))
			{
				print(" SELECTED");
			}
			print(">" . prepareText($DatabaseRow[1]) . "\n");
		}
		print("</SELECT></TD></TR>\n");

		/* Separate the shipping and billing sections. */
		print("<TR><TD COLSPAN=\"2\">&nbsp;</TD></TR>\n");

		/* Do the main billing address part. */
		print("<TR><TD COLSPAN=\"2\"><B>" . L_ORDEREXPRESS_BILLINGINFORMATION . "</B>\n");


		
		/* 
		** Right in the middle of the billing address section heading, give
		** the user a link, "Same as shipping," that will fill in the billing
		** fields with the values from the shipping section.
		*/
		if((GENERATE_CLOAKING_CONSTANTS) AND (BROWSER_JAVASCRIPTOK))
		{
			print("&nbsp;&nbsp;<A HREF=\"javascript:void(0)\" ");
			print(" ONCLICK=\"setBilling(); return true;\">");
			print(L_ORDEREXPRESS_SAMEASSHIPPING . ".</A>\n");
			print("<SCRIPT LANGUAGE=\"JavaScript\">\n");
			print("function setBilling()\n");
			print("{\n");

			//loop through all the address fields
			//this array is define in the addressFunctions module
			reset($AddressInfo);
			while(list($FieldName) = each($AddressInfo))
			{
				if($FieldName=="StateProv")
				{
					print("\t var numStates = document.forms.shippingForm.Ecom_BillTo_Postal_StateProv.options.length; \n");
					print("\t var i; \n");
					print("\t for (i=0 ; i<numStates ; i++) \n");
					print("\t { \n");
					print("\t \t document.forms.shippingForm.Ecom_BillTo_Postal_StateProv.options[i].selected = \n");
					print("\t \t \t document.forms.shippingForm.Ecom_ShipTo_Postal_StateProv.options[i].selected; \n");
					print("\t } \n");			
				}
				elseif($FieldName=="CountryCode")
				{
					print("\t var numCountries = document.forms.shippingForm.Ecom_BillTo_Postal_CountryCode.options.length; \n");
					print("\t for (i=0 ; i<numCountries ; i++) \n");
					print("\t { \n");
					print("\t \t document.forms.shippingForm.Ecom_BillTo_Postal_CountryCode.options[i].selected = \n");
					print("\t \t \t document.forms.shippingForm.Ecom_ShipTo_Postal_CountryCode.options[i].selected; \n");
					print("\t } \n");			
				}
				else
				{
					print("\t document.forms.shippingForm.Ecom_BillTo_");
					print($AddressInfo[$FieldName][ADDR_VAR]);
					print(".value = \n");
					
					print("\t \t document.forms.shippingForm.Ecom_ShipTo_");
					print($AddressInfo[$FieldName][ADDR_VAR]);
					print(".value; \n\n");
				}
			}

			print("}\n");
			print("</SCRIPT>\n");
		}
		
		
				
		/* Continue on with the billing section. */		
		print("</TD></TR>\n");

		printAddressFields(
			$billingAddress, 
			"Ecom_BillTo_", 
			"ALL", 
			0, 
			0, 
			FALSE);
		
		/* Billing method. */
		print("<TR><TD>" . L_ORDEREXPRESS_BILLINGMETHOD . "</TD>\n");
		print("<TD><SELECT NAME=\"Ecom_Payment_Card_Type\">\n");
		$Query = "SELECT ID, Name ";
		$Query .= "FROM billing_method ";
		$Query .= "ORDER BY DisplayPrecedence ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		while($DatabaseRow = mysql_fetch_row($DatabaseResult))
		{
			print("<OPTION VALUE=\"$DatabaseRow[0]\"");
			if(isset($Ecom_Payment_Card_Type) AND ($DatabaseRow[0] == $Ecom_Payment_Card_Type))
			{
				print(" SELECTED");
			}
			print(">" . prepareText($DatabaseRow[1]) . "\n");
		}
		print("</SELECT></TD></TR>\n");
	
		printEditRow(L_ORDEREXPRESS_CREDITCARDNUMBER, "Ecom_Payment_Card_Number", 
			$Ecom_Payment_Card_Number);
	
		/* Credit card expiration = month pull down + year pull down. */
		print("<TR><TD>" . L_ORDEREXPRESS_EXPIRATIONDATE . "</TD>\n");
		print("<TD><SELECT NAME=\"Ecom_Payment_Card_ExpDate_Month\">\n");
		$monthName = array(1=>"January", "February", "March",
			"April", "May", "June", "July", "August",
			"September", "October", "November", "December");
		for ($i=1 ; $i<=12 ; $i++)
		{
			print("<OPTION VALUE=\"$i\"" . 
				($Ecom_Payment_Card_ExpDate_Month == $i ? " SELECTED" : "") . 
				">$monthName[$i]\n");
		}
		print("</SELECT>\n");
		$currentDate = getdate();
		print("<SELECT NAME=\"Ecom_Payment_Card_ExpDate_Year\">\n");
		/* Output something like <OPTION VALUE="2001" SELECTED>2001 */
		for ($i=0 ; $i<=5 ; $i++)
		{
			$year = $currentDate["year"]+$i;
			print("<OPTION VALUE=\"$year\"" . 
				($Ecom_Payment_Card_ExpDate_Year == $year ? " SELECTED" : "") . 
				">$year\n");
		}
		print("</SELECT>\n");	
		print("</TD></TR>\n");

		// If the user is logged in, let them enter a coupon
		if(USE_COUPONS AND (isset($UserInfo["ID"])) AND ($UserInfo["ID"] > 0))
		{
			print("<TR>\n");
			print("<TD>Coupon Code</TD>\n");
			print("<TD>");
			print("<INPUT TYPE=\"TEXT\" NAME=\"bill_coupon\" VALUE=\"$bill_coupon\" SIZE=\"40\">\n");
			print("</TD></TR>\n");
		}
	
		/* Finish up. */		
		print("<TR><TD COLSPAN=\"2\">\n");	
		print("<INPUT TYPE=\"SUBMIT\" VALUE=\"" . L_ORDEREXPRESS_CONTINUE . "\">\n");
		print("</TD></TR>\n");
		print("</TABLE>\n");
		print("</FORM>\n");
	}

	print(PRIVACY_STATEMENT);

?>
