<?php
	/*
	** File: SET_SHIPPING_ALL
	** Description: Set shipping address for all SKUs on the incomplete invoice.
	** Also set fees relating to shipping and handling
	** Version: $Revision: 1.17 $
	** Created: 06/24/1999
	** Author: Leon Atkinson
	** Email: leon@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/03/08 16:48:25 $
	**
	** Log : $Log: SET_SHIPPING_ALL,v $
	** Log : Revision 1.17  2000/03/08 16:48:25  leon
	** Log : Fixed bug where the wrong variable for state/provinced was used.
	** Log :
	** Log : Revision 1.16  1999/12/09 23:23:23  leon
	** Log : Changed ActionResults use so that it's an array instead of a
	** Log : continually-growing string.  Note the little function in standard_library
	** Log : for printing out all the action results.
	** Log :
	** Log : Revision 1.15  1999/12/06 21:17:20  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.14  1999/11/15 18:56:21  leon
	** Log : Finished localizing action modules.
	** Log :
	** Log : Revision 1.13  1999/11/05 18:17:48  leon
	** Log : Reorganized coupon code.
	** Log :
	** Log : Revision 1.12  1999/11/04 21:35:31  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.11  1999/11/02 20:49:41  leon
	** Log : Added constant to control use of coupons
	** Log :
	** Log : Revision 1.10  1999/11/02 18:23:06  chris
	** Log : Added support for coupons.
	** Log :
	** Log : Revision 1.9  1999/10/26 17:31:34  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.8  1999/10/11 23:03:59  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.7  1999/10/04 22:09:51  leon
	** Log : Removed getInvoiceID.  The active invoice is now added to $UserInfo
	** Log : by the check sid functionality in init.
	** Log :
	** Log : Revision 1.6  1999/09/09 22:15:35  jj
	** Log : No longer any need to use the variable $addressFunctionsDefined.
	** Log :
	** Log : Revision 1.5  1999/08/18 22:31:52  leon
	** Log : Returning opening PHP tag to XML-friendly tag
	** Log :
	** Log : Revision 1.4  1999/08/18 19:12:06  jj
	** Log : Painstakingly dealt with the following question: which address fields 
	** Log : should we ask for, which should we require. Reasonable defaults set up.
	** Log :
	** Log : Revision 1.3  1999/08/18 16:19:31  jj
	** Log : All actions now use verifyAddress and insertAddress whenever appropriate.
	** Log :
	** Log : Revision 1.2  1999/08/17 17:57:23  jj
	** Log : Modularized everything to do with addresses. Please see include/addressFunctions
	** Log :
	** Log : Revision 1.1  1999/07/28 19:41:05  leon
	** Log : Mass update based on code donation from a live project
	** Log :
	**
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	*/

	//insertAddress function
	include(APPLICATION_ROOT . "/modules/include/addressFunctions");

	//createShipping function
	include(APPLICATION_ROOT . "/modules/include/createShipping");

	//ShippingByTotal function
	include(APPLICATION_ROOT . "/modules/include/ShippingByTotal");

	//getVariationID function
	include(APPLICATION_ROOT . "/modules/include/attribute_functions");

	//getFeeID function
	include(APPLICATION_ROOT . "/modules/include/fee");


	//get address from posted variables
	$shipAddress = getAddressFromEnvironment("Ecom_ShipTo_");


	//check for required fields
	$AddressIsGood = verifyAddress(
		array("Name_First", 
			"Name_Last", 
			"Street1",	
			"City", 
			"StateProv", 
			"CountryCode", 
			"PostalCode", 
			"Phone1"), 
		$shipAddress, &$ErrorText);


	if(!$AddressIsGood)
	{
		/* Ugh, something happened. */
		$SCREEN = "order_info";
		$ActionResults[] = $ErrorText;
	}
	else
	{

		if($UserInfo['Invoice']  > 0)
		{
			//get item total for the entire invoice
			$tItemCost = 0;
			$Query = "SELECT Quantity, ListPrice, SalePrice ";
			$Query .= "FROM invoice_sku ";
			$Query .= "WHERE Invoice = " . $UserInfo['Invoice'] . " ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);
			while($DatabaseRow = mysql_fetch_row($DatabaseResult))
			{
				$tQuantity = $DatabaseRow[0];
				$tListPrice = $DatabaseRow[1];
				$tSalePrice = $DatabaseRow[2];
				
				if($tSalePrice > 0)
				{
					$tListPrice = $tSalePrice;
				}
	
				$tItemCost += $tQuantity * $tListPrice;	
			}


			//get total of non-taxable items
			$tItemCostNonTaxable = 0;
			$Query = "SELECT s.Quantity, s.ListPrice, s.SalePrice ";
			$Query .= "FROM invoice_sku s, sku_variation v ";
			$Query .= "WHERE s.SKU = v.SKU ";
			$Query .= "AND v.Variation = " . getVariationID(getAttributeID("Tax"), "Not Taxable") . " ";
			$Query .= "AND Invoice = " . $UserInfo['Invoice'] . " ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);
			while($DatabaseRow = mysql_fetch_row($DatabaseResult))
			{
				$tQuantity = $DatabaseRow[0];
				$tListPrice = $DatabaseRow[1];
				$tSalePrice = $DatabaseRow[2];
				$tShipping = $DatabaseRow[3];
				
				if($tSalePrice > 0)
				{
					$tListPrice = $tSalePrice;
				}
	
				$tItemCostNonTaxable += $tQuantity * $tListPrice;	
			}
			
			
			//get total of items with free shipping
			$tItemCostFreeShipping = 0;
			$Query = "SELECT s.Quantity, s.ListPrice, s.SalePrice ";
			$Query .= "FROM invoice_sku s, sku_variation v ";
			$Query .= "WHERE s.SKU = v.SKU ";
			$Query .= "AND v.Variation = " . getVariationID(getAttributeID("Free Shipping"), "Free Shipping") . " ";
			$Query .= "AND Invoice = " . $UserInfo['Invoice'] . " ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);
			while($DatabaseRow = mysql_fetch_row($DatabaseResult))
			{
				$tQuantity = $DatabaseRow[0];
				$tListPrice = $DatabaseRow[1];
				$tSalePrice = $DatabaseRow[2];
				$tShipping = $DatabaseRow[3];
				
				if($tSalePrice > 0)
				{
					$tListPrice = $tSalePrice;
				}
	
				$tItemCostFreeShipping += $tQuantity * $tListPrice;	
			}




			//create the address row
			$AddressID = insertAddress($shipAddress);
			
			if($AddressID > 0)
			{

				//calculate shipping by total
				//this probably needs to be passed shipping method, too
				$TotalShipping = ShippingByTotal($tItemCost - $tItemCostFreeShipping);
	
				//erase previous shipping fees
				$Query = "DELETE FROM invoice_fee ";
				$Query .= "WHERE Invoice = " . $UserInfo['Invoice'] . " ";
				$Query .= "AND Fee = ".getFeeID('Shipping')." ";
				$DatabaseResult = mysql_query($Query, $DatabaseLink);
				
				//set shipping fee
				$Query = "INSERT INTO invoice_fee VALUES(" . $UserInfo['Invoice'] . 
					", ".getFeeID('Shipping').", $TotalShipping) ";
				$DatabaseResult = mysql_query($Query, $DatabaseLink);
				
				//calculate tax by total
				if($shipAddress["CountryCode"] == 'US')
				{
					$Query = "SELECT Rate, TaxShipping ";
					$Query .= "FROM tax ";
					$Query .= "WHERE State = '".addslashes($shipAddress["StateProv"])."' "; 
					$DatabaseResult = mysql_query($Query, $DatabaseLink);
					list($tax_Rate, $tax_TaxShipping) = mysql_fetch_row($DatabaseResult);
					
					if($tax_TaxShipping == 'Y')
					{
						$TotalTax = ($tItemCost - $tItemCostNonTaxable + $TotalShipping) * $tax_Rate;
					}
					else
					{
						$TotalTax = ($tItemCost - $tItemCostNonTaxable) * $tax_Rate;
					}
				}
				else
				{
					///No Tax for order sent outside US
					$TotalTax = 0.00;
				}
					
				//erase previous tax fees
				$Query = "DELETE FROM invoice_fee ";
				$Query .= "WHERE Invoice = " . $UserInfo['Invoice'] . " ";
				$Query .= "AND Fee = ".getFeeID('Tax')." ";
				$DatabaseResult = mysql_query($Query, $DatabaseLink);
				
				//set tax fee
				$Query = "INSERT INTO invoice_fee VALUES(" . 
					$UserInfo['Invoice'] . ", ".getFeeID('Tax').", $TotalTax) ";
				$DatabaseResult = mysql_query($Query, $DatabaseLink);


				//create shipping row
				if(!isset($ship_GiftMessage))
				{
					$ship_GiftMessage = "";
				}
				$shipping = createShipping($UserInfo['Invoice'], 
					$AddressID, $ship_Method, $ship_GiftMessage);
				
				if($shipping > 0)
				{
	
					//update all SKUs
					$Query = "UPDATE invoice_sku ";
					$Query .= "SET Shipping = $shipping ";
					$Query .= "WHERE Invoice = " . $UserInfo['Invoice'] . " ";
					$DatabaseResult = mysql_query($Query, $DatabaseLink);
					if(!$DatabaseResult)
					{
						print("<!--\n");
						print("$Query \n");
						print(mysql_errno() . ": " . mysql_error()) . "\n"; 
						print("-->\n");
			
						$ActionResults[] = L_SETSHIPPINGALL_ERROR_3;
						$SCREEN = "order_info";
					}
				}
				else
				{
					$ActionResults[] = L_SETSHIPPINGALL_ERROR_2;
					$SCREEN = "order_info";
				}				
			}
			else
			{
				$ActionResults[] = L_SETSHIPPINGALL_ERROR_1;
				$SCREEN = "order_info";
			}

		}
		else
		{
			print("<!-- Got to SET_SHIPPING_ALL without invoice -->");
			$SCREEN = "welcome";
		}
	}
	

?>
