<?php
	/*
	** File: SET_ORDER_INFO
	** Description: This is the action for order_express.
	** Also set fees relating to shipping and handling
	** Version: $Revision: 1.23 $
	** Created: 08/10/1999
	** Author: Leon Atkinson
	** Email: leon@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/03/13 17:47:34 $
	**
	** Log : $Log: SET_ORDER_INFO,v $
	** Log : Revision 1.23  2000/03/13 17:47:34  leon
	** Log : Fixing a couple more bugs related to old address variables.
	** Log :
	** Log : Revision 1.22  1999/12/21 20:54:27  leon
	** Log : Removed log entries (it's getting crazy).  Streamlined some stuff in
	** Log : SET_ORDER_INFO.
	** 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");

	//get credit card validation function
	include(APPLICATION_ROOT . "/modules/include/validateCard");

	//get calculateTotal
	include(APPLICATION_ROOT . "/modules/include/calculateTotal");

	//get functions for manipulating billing records
	include(APPLICATION_ROOT . "/modules/include/billing");

	//coupon functions
	if(USE_COUPONS)
	{
		include(APPLICATION_ROOT . "/modules/include/coupon");
	}

	//variable used to control continuation of script
	$continue = TRUE;

	/* 
	** Verify the address fields.
	*/
	if($continue) 
	{
		$shipAddress = getAddressFromEnvironment("Ecom_ShipTo_");

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

		if(!$AddressIsGood)
		{
			//prefix ActionResults with error message
			$ActionResults[] = L_SETORDERINFO_INSHIPPING . "<BR>" . $ErrorText;
			$continue = FALSE;
		}
	}


	if($continue) 
	{
		$billingAddress = getAddressFromEnvironment("Ecom_BillTo_");

		$AddressIsGood = verifyAddress(
			array("Name_First", 
				"Name_Last", 
				"Street1",	
				"City", 
				"StateProv", 
				"CountryCode", 
				"PostalCode", 
				"Email",
				"Phone1"), 
			$billingAddress, &$ErrorText);
	
		if(!$AddressIsGood)
		{
			//prefix ActionResults with error message
			$ActionResults[] =  L_SETORDERINFO_INBILLING . "<BR>" . $ErrorText;
			$continue = FALSE;
		}
	}	
	

	/*
	** Check that the credit card is not expired 
	*/
	if($continue)
	{
		if(($Ecom_Payment_Card_ExpDate_Year==0) OR ($Ecom_Payment_Card_ExpDate_Month==0))
		{
			$ActionResults[] =  L_VALIDATEORDER_WEIRD_DATES;
			$continue = FALSE;
			$SCREEN = "order_billing";
		}
		elseif((date("Y") > $Ecom_Payment_Card_ExpDate_Year) OR
			((date("Y") == $Ecom_Payment_Card_ExpDate_Year) AND
				(date("m") > $Ecom_Payment_Card_ExpDate_Month)) 
			)
		{
			$continue = FALSE;
			$ActionResults[] =  L_VALIDATEORDER_EXPIRED;
			$SCREEN = "order_billing";
		}
		else 
		{
			$Ecom_Payment_Expiration = 
				$Ecom_Payment_Card_ExpDate_Year . 
				"-" . 
				$Ecom_Payment_Card_ExpDate_Month . 
				"-01 00:00:00";
		}
	}	
	

	/*
	** Validate the credit card.
	*/
	if ($continue) 
	{
		if(!($Ecom_Payment_Card_Type = validateCard($Ecom_Payment_Card_Number)))
		{
			//Card didn't validate
			$ActionResults[] = L_SETORDERINFO_INVALID;
			$continue = FALSE;	
		}
	}


	/*
	** Check that the user has an invoice in progress
	*/
	if ($continue)
	{
		if($UserInfo['Invoice'] <= 0)
		{
			$ActionResults[] = mysql_errno() . ": " . mysql_error();
			$continue = FALSE;
		}
	}
	
	
	/*	
	** Get item total for the entire invoice.
	*/
	$Total = calculateTotal($UserInfo['Invoice']);


	/*
	** Create the address row.
	*/
	if ($continue)
	{
		$AddressID = insertAddress($shipAddress);

		if ($AddressID <= 0)
		{
			$ActionResults[] = mysql_errno() . ": " . mysql_error();
			$continue = FALSE;
		}
	}

			
	/*
	** Do fees and stuff.
	*/
	if ($continue)
	{
		$TotalShipping = ShippingByTotal($Total['Items']);

		//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 ";
		$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 = ($Total['Items'] + $TotalShipping) * $tax_Rate;
			}
			else
			{
				$TotalTax = $Total['Items'] * $tax_Rate;
			}
		}
		else
		{
			//No Tax for Canadians
			$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']; 
		$Query .= ", ".getFeeID('Tax').", $TotalTax) ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);

		//create shipping row
		$ship_GiftMessage = isset($ship_GiftMessage) ? $ship_GiftMessage : "";
		$shipping = createShipping($UserInfo['Invoice'], $AddressID, $ship_Method, $ship_GiftMessage);
		if ($shipping <= 0)
		{
			$ActionResults[] = $ActionResults[] = mysql_errno() . ": " . mysql_error();
			$continue = FALSE;
		}
		
		//reset totals
		calculateTotal($UserInfo['Invoice'], TRUE);
	}
	

	/*
	** Validate and set coupons
	*/
	if(USE_COUPONS AND ($bill_coupon != ""))
	{
		if(validateCouponList($bill_coupon, $Total['Grand'], $Reason))
		{
			//coupons are OK, so save fees
			if(!(useCouponList($bill_coupon, $UserInfo['Invoice'])))
			{
				//problems with the coupons, so try again
				$continue = FALSE;
				$ActionResults[] = "An error occurred while using your coupons!";
				$SCREEN="order_express";
			}
		}
		else
		{
			//problems with the coupons, so try again
			$continue = FALSE;
			$ActionResults[] =  $Reason;
			$SCREEN="order_express";
		}
	}
		
		
	/*
	** Do billing and stuff.
	*/
	if ($continue)
	{	
		//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_SETORDERINFO_ERROR_3;
			$SCREEN = "order_info";
		}
		
		/* 
		** Wipe out any other billing records for this invoice
		*/
		destroyInvoiceBilling($UserInfo['Invoice']);


		/*
		** create billing record (and its address record)
		*/
		$Ecom_Payment_NameOnCard = 
			$billingAddress["Name_First"] . " " . $billingAddress["Name_Last"];

		if(!createBilling(
			$UserInfo['Invoice'], 
			$billingAddress, 
			$Ecom_Payment_Card_Type, 
			$Ecom_Payment_NameOnCard,
			$Ecom_Payment_Card_Number, 
			$Ecom_Payment_Expiration))
		{
			//could not create the billing record!
			$ActionResults[] =  L_SETORDERINFO_CREATEBILL;
			$SCREEN = "order_express";
		}
		else
		{
			$ActionResults[] = L_SETORDERINFO_SUCCESS;
			$SCREEN = "order_confirm";
		}
	}
?>
