<?php
	/*
	** File: SET_SHIPPING
	** Description: Set shipping address for given SKUs on the incomplete invoice
	** Version: $Revision: 1.20 $
	** Created: 06/25/1999
	** Author: Leon Atkinson
	** Email: leon@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/03/13 17:47:34 $
	**
	** Log : $Log: SET_SHIPPING,v $
	** Log : Revision 1.20  2000/03/13 17:47:34  leon
	** Log : Fixing a couple more bugs related to old address variables.
	** Log :
	** Log : Revision 1.19  2000/03/08 16:48:25  leon
	** Log : Fixed bug where the wrong variable for state/provinced was used.
	** Log :
	** Log : Revision 1.18  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.17  1999/12/06 21:17:19  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.16  1999/11/15 18:56:21  leon
	** Log : Finished localizing action modules.
	** Log :
	** Log : Revision 1.15  1999/11/09 00:28:14  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.14  1999/11/05 22:37:51  leon
	** Log : Completed removal of all hardcoded fees.  All references to fee IDs
	** Log : go through getFeeID function.
	** 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:30  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:05  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 16:19:31  jj
	** Log : All actions now use verifyAddress and insertAddress whenever appropriate.
	** Log :
	** Log : Revision 1.3  1999/08/17 17:57:23  jj
	** Log : Modularized everything to do with addresses. Please see include/addressFunctions
	** Log :
	** Log : Revision 1.2  1999/08/09 22:31:45  jj
	** Log : There was a typo in one of the error messages.
	** Log :
	** Log : Revision 1.1  1999/07/28 19:41:04  leon
	** Log : Mass update based on code donation from a live project
	** Log :
	**
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	*/

	//has a function for creating addresses
	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");

	$continueScript = TRUE;

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


	/* 
	** Verify data. Note, $actionShipAddress is used again, below.
	*/
	//check for required fields
	$AddressIsGood = verifyAddress(
		array("Name_First", 
			"Name_Last", 
			"Street1",	
			"City", 
			"StateProv", 
			"CountryCode", 
			"PostalCode", 
			"Phone1"), 
		$shipAddress, &$ErrorText);

	if(!$AddressIsGood)
	{
		$continueScript = FALSE;
	}
	elseif( count($SelectedSKU) == 0 )
	{
		$ActionResults[] = L_SETSHIPPING_CHOOSE_ITEM . $ErrorText;
		$continueScript = FALSE;
	}



	/* 
	** Make sure we can get the ID of the incomplete invoice for this user.
	*/
	if ($continueScript)
	{
		if($UserInfo['Invoice'] <= 0)
		{
			$ActionResults[] = L_SETSHIPPING_NO_INVOICE .
				" <!-- Invoice #" . $UserInfo['Invoice'] . " -->";
			$continueScript = FALSE;
		}			
	}
	

	/*
	** Insert the address into the address table. 
	*/
	if ($continueScript)
	{
		$AddressID = insertAddress($shipAddress);
		
		if ($AddressID <= 0)
		{
			$ActionResults[] = L_SETSHIPPING_FAILED_ADDRESS .
				"<!-- unable to add an address to the database -->\n";
			$continueScript = FALSE;
		}
	}
	
	
	
	/*
	** Create shipping row.
	*/
	if ($continueScript)
	{
		$ship_GiftMessage = isset($ship_GiftMessage) ? $ship_GiftMessage : "";
		$shipping = createShipping($UserInfo['Invoice'], $AddressID, $ship_Method, $ship_GiftMessage);
		if ($shipping <= 0)
		{
			$ActionResults[] = L_SETSHIPPING_FAILED_CREATE .
				"<!-- unable to add shipping row to the database -->\n";
			$continueScript = FALSE;
		}
	}
	
	
	
	/*
	** Update the shipping information for the selected skues.
	*/
	if ($continueScript)
	{
		/* make list of invoice_sku IDs */
		$invoice_sku_IDs = "0";
		for($index=0; $index < count($SelectedSKU); $index++)
		{
			$invoice_sku_IDs .= ", " . $SelectedSKU[$index];
		}

		/* update selected SKUs */
		$Query = "UPDATE invoice_sku ";
		$Query .= "SET Shipping = $shipping ";
		$Query .= "WHERE ID in ($invoice_sku_IDs) ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		if(!$DatabaseResult)
		{
			$ActionResults[] = L_SETSHIPPING_FAILED_UPDATE .
				"<!-- Unable to set shipping: $Query -->\n";
			$continueScript = FALSE;
		}
	}
	
	
	
		
	/*
	** Deal with the rather extraordinary case that everything went okay.
	*/
	if ($continueScript)
	{
		/* Clear out checkboxes and do a happy message. */
		unset($SelectedSKU);
		$ActionResults[] = "Address set!";

		/* See if we have finished *ALL* of the addresses. */
		$Query = "SELECT COUNT(*) ";
		$Query .= "FROM invoice_sku ";
		$Query .= "WHERE Shipping=0 ";
		$Query .= "AND Invoice=" . $UserInfo['Invoice'] . " ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		list($AddressesLeft) = mysql_fetch_row($DatabaseResult);
		if($AddressesLeft == 0)
		{
			$SCREEN="order_billing";
			$ActionResults[] = L_SETSHIPPING_FINISHED;
		}

		//get item total for this shipping address
		$tItemCost = 0;
		$Query = "SELECT Quantity, ListPrice, SalePrice ";
		$Query .= "FROM invoice_sku ";
		$Query .= "WHERE ID in ($invoice_sku_IDs) ";
		$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;
			}

			$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 ID in ($invoice_sku_IDs) ";
		$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 ID in ($invoice_sku_IDs) ";
		$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;	
		}



		/* Add shipping by total. Probably needs to be passed shipping method, 
		** too.
		*/
		$TotalShipping = ShippingByTotal($tItemCost - $tItemCostFreeShipping);

		/* Delete 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 ";
		$Query .= "VALUES(" . $UserInfo['Invoice'] . ", ";
		$Query .= 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;
		}

		// Add tax fee
		$Query = "INSERT INTO invoice_fee ";
		$Query .= "VALUES(" . $UserInfo['Invoice'] . ", ";
		$Query .= getFeeID('Tax').", $TotalTax) ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);


	}
	
?>
