<?php
	/*
	** File: SUBMIT_ORDER
	** Description: create an invoice
	** Version: $Revision: 1.26 $
	** Created: 05/18/1999
	** Author: Leon Atkinson
	** Email: leon@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/03/08 16:55:36 $
	**
	** Log : $Log: SUBMIT_ORDER,v $
	** Log : Revision 1.26  2000/03/08 16:55:36  leon
	** Log : Fixed errant ActionResults usage.
	** Log :
	** Log : Revision 1.25  2000/01/14 17:21:53  leon
	** Log : Fixed errant address fields.
	** Log :
	** Log : Revision 1.24  2000/01/13 23:27:01  leon
	** Log : Added check for incomplete invoice before making it active.
	** Log :
	** Log : Revision 1.23  1999/12/30 00:41:13  jj
	** Log : Changed confirmation email to also list shipping destinations.
	** Log :
	** Log : Revision 1.22  1999/12/20 17:14:26  leon
	** Log : Moved text into english
	** Log :
	** Log : Revision 1.19  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.18  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.17  1999/11/15 18:56:21  leon
	** Log : Finished localizing action modules.
	** Log :
	** Log : Revision 1.16  1999/11/05 18:17:49  leon
	** Log : Reorganized coupon code.
	** Log :
	** Log : Revision 1.15  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.14  1999/11/02 20:49:41  leon
	** Log : Added constant to control use of coupons
	** Log :
	** Log : Revision 1.13  1999/11/02 18:23:06  chris
	** Log : Added support for coupons.
	** Log :
	** Log : Revision 1.12  1999/10/25 21:51:14  leon
	** Log : Parameterized email from header.
	** Log :
	** Log : Revision 1.11  1999/10/11 23:04:00  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.10  1999/10/04 22:09:52  leon
	** Log : Removed getInvoiceID.  The active invoice is now added to $UserInfo
	** Log : by the check sid functionality in init.
	** Log :
	** Log : Revision 1.9  1999/09/08 17:49:17  jj
	** Log : Removed bug that was using $UserInfo even if the user wasn't logged in.
	** Log :
	** Log : Revision 1.8  1999/08/18 22:31:52  leon
	** Log : Returning opening PHP tag to XML-friendly tag
	** Log :
	** Log : Revision 1.7  1999/08/11 17:00:23  jj
	** Log : Changed the email confirmation notice so that it was completely generic (it still had lines refering to a live project). Perhaps we should add some global constants such as "CONTACT_EMAIL" and "COMPANY_NAME".
	** Log :
	** Log : Revision 1.6  1999/08/10 21:24:18  jj
	** Log : Put the CVS variables back in (they were lost when I copied in code from a live site).
	** Log :
	**
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	*/

	include(APPLICATION_ROOT . "/modules/include/validateEmail");
	include(APPLICATION_ROOT . "/modules/include/addressFunctions");
	include(APPLICATION_ROOT . "/modules/include/listInvoiceContents");
	$ContinueProcessing = TRUE;
	
	//make sure we have an invoice to submit
	if($UserInfo['Invoice'] <= 0)
	{
		$ActionResults[] = L_SUBMITORDER_BAD_INVOICE;
		$SCREEN="contents";
		$ContinueProcessing = FALSE;
	}
	
	if($ContinueProcessing)
	{
		//make sure invoice isn't already set to active!
		$Query = "SELECT Active ";
		$Query .= "FROM invoice ";
		$Query .= "WHERE ID = " . intval($UserInfo['Invoice']) . " ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		$DatabaseRow = mysql_fetch_object($DatabaseResult);
		if($DatabaseRow->Active == 'Y')
		{
			//if a user gets here, he probably hit reload
			//on the thank-you page.  Bad news.
			$ActionResults[] = L_SUBMITORDER_INVOICE_EXISTS;
			$SCREEN="contents";
			$ContinueProcessing = FALSE;
		}
	}


	/* make sure this invoice has:
	**	1. A billing record with matching address record
	**	2. At least one invoice_sku record
	**	3. At least one shipping record with matching address record
	**
	** The intention is to avoid those cases where the user uses the
	** back button to screw up the order, then somehow returns to the
	** order_confirm screen and clicks submit.  Yes, these three queries
	** are expensive, but unfortunately necessary.
	*/
	if($ContinueProcessing)
	{
		//billing record
		$Query = "SELECT Address ";
		$Query .= "FROM billing b, address a ";
		$Query .= "WHERE b.Invoice=" . $UserInfo['Invoice'] . " ";
		$Query .= "AND b.Address = a.ID ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		if(!$DatabaseResult OR (mysql_num_rows($DatabaseResult) <= 0))
		{
			$ActionResults[] .= "Your invoice is missing billing information!<BR>";
			$SCREEN = "order_info";
			$ContinueProcessing = FALSE;
		}
	}

	if($ContinueProcessing)
	{
		//invoice_sku
		$Query = "SELECT ID ";
		$Query .= "FROM invoice_sku ";
		$Query .= "WHERE Invoice=" . $UserInfo['Invoice'] . " ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		if(!$DatabaseResult OR (mysql_num_rows($DatabaseResult) <= 0))
		{
			$ActionResults[] .= "Your invoice has no items!<BR>";
			$SCREEN = "order_info";
			$ContinueProcessing = FALSE;
		}
	}

	if($ContinueProcessing)
	{
		//shipping record
		$Query = "SELECT Address ";
		$Query .= "FROM shipping s, address a ";
		$Query .= "WHERE s.Invoice=" . $UserInfo['Invoice'] . " ";
		$Query .= "AND s.Address = a.ID ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		if(!$DatabaseResult OR (mysql_num_rows($DatabaseResult) <= 0))
		{
			$ActionResults[] .= "Your invoice is missing shipping information!<BR>";
			$SCREEN = "order_info";
			$ContinueProcessing = FALSE;
		}
	}


	if($ContinueProcessing)
	{
		//set the invoice as active
		$Query = "UPDATE invoice ";
		$Query .= "SET Active = 'Y' ";
		$Query .= "WHERE ID = " . $UserInfo['Invoice'] . " ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		if(!$DatabaseResult)
		{
			print("<!--\n");
			print("$Query \n");
			print(mysql_errno() . ": " . mysql_error()) . "\n"; 
			print("-->\n");
			$ActionResults[] = L_SUBMITORDER_ERROR_1;
			$ContinueProcessing = FALSE;
		}
	}
	

	if($ContinueProcessing)
	{
		//add creation status message
		$Query = "INSERT INTO invoice_status VALUES (0, " . $UserInfo['Invoice'] . ", 1, now(), '')";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		if(!$DatabaseResult)
		{
			print("<!--\n");
			print("$Query \n");
			print(mysql_errno() . ": " . mysql_error()) . "\n"; 
			print("-->\n");
			$ActionResults[] = L_SUBMITORDER_ERROR_2;
			$ContinueProcessing = FALSE;
		}
	}
	
	if($ContinueProcessing)
	{
		//set session as having no active invoice
		$Query = "UPDATE session ";
		$Query .= "SET Invoice=0 ";
		$Query .= "WHERE ID='$sid' ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		if(!$DatabaseResult)
		{
			print("<!--\n");
			print("$Query \n");
			print(mysql_errno() . ": " . mysql_error()) . "\n"; 
			print("-->\n");
			$ActionResults[] = L_SUBMITORDER_ERROR_3;
			$ContinueProcessing = FALSE;
		}
	}
	
	if($ContinueProcessing)
	{
		if(USE_COUPONS)
		{
			//store which coupons were used
			$Query = "INSERT INTO coupon_user ";
			$Query .= "SELECT Coupon, " . $UserInfo['ID'] . " ";
			$Query .= "FROM invoice_coupon ";
			$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_SUBMITORDER_ERROR_4;
				$ContinueProcessing = FALSE;
			}
		}
	}
	
	if($ContinueProcessing)
	{

		//get list of SKUs
		$Query = "SELECT SKU, Quantity ";
		$Query .= "FROM invoice_sku ";
		$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_SUBMITORDER_ERROR_5;
			$ContinueProcessing = FALSE;
		}
		while($DatabaseRow = mysql_fetch_row($DatabaseResult))
		{
			$ReduceStock_sku[] = $DatabaseRow[0];
			$ReduceStock_quantity[] = $DatabaseRow[1];
		}
	}
	
	if($ContinueProcessing)
	{
		//decrement available inventory for each entry
		for($index=0; $index < count($ReduceStock_sku); $index++)
		{
			$Query = "UPDATE inventory ";
			$Query .= "SET Available = Available - $ReduceStock_quantity[$index] ";
			$Query .= "WHERE SKU = $ReduceStock_sku[$index] ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);		
			if(!$DatabaseResult)
			{
				print("<!--\n");
				print("$Query \n");
				print(mysql_errno() . ": " . mysql_error()) . "\n"; 
				print("-->\n");
				$ActionResults[] = L_SUBMITORDER_ERROR_6;
				$ContinueProcessing = FALSE;
			}
		}
	}
	
	if($ContinueProcessing)
	{
		//get billing record
		$Query = "SELECT Address, Method, CreditCardNumber, CreditCardExpiration ";
		$Query .= "FROM billing ";
		$Query .= "WHERE Invoice = " . $UserInfo['Invoice'] . " ";

		if(!($DatabaseResult = mysql_query($Query, $DatabaseLink)))
		{
			print("<!-- " . mysql_errno() . ": " . mysql_error() . 
				"   Query was $query -->\n");
			$continueScript = FALSE;
		}
		else
		{
			
			if(!($DatabaseRow = mysql_fetch_object($DatabaseResult)))
			{
				print("Unable to get the address and billing information " . 
					"attached to this invoice.<BR>\n");
				$continueScript = FALSE;
			}
			else
			{ 
				$AddressID = $DatabaseRow->Address;
			
				$Ecom_Payment_Card_Type = $DatabaseRow->Method;
				$Ecom_Payment_Card_Number = $DatabaseRow->CreditCardNumber;
				$Ecom_Payment_Expiration = $DatabaseRow->CreditCardExpiration;
			}
		}
		
		//get the address
		//Yes, we could do both in one query, but isn't it
		//nice to have less lines of code?  Plus, we really should
		//have a getBilling() function.
		$billingAddress = getAddress($AddressID);
	}
	
	if($ContinueProcessing)
	{
		//send confirmation email
		if((SEND_EMAIL) AND validateEmail($billingAddress["Email"]))
		{
			$mail_body = L_SUBMITORDER_DEAR . 
				$billingAddress["Name_First"] . " " . 
				$billingAddress["Name_Last"] . ",\n\n";
			$mail_body .= L_SUBMITORDER_BODY;
			$mail_body .= L_SUBMITORDER_INVOICE . $UserInfo['Invoice'] .".\n\n";
			$mail_body .= L_SUBMITORDER_THANKS;
			
			//list each item in the invoice and where each item is being shipped to
			if ( listInvoiceContents(intval($UserInfo['Invoice']), $contentsString) )
			{
				$mail_body .= L_SUBMITORDER_INVOICE_CONTENTS;
				$mail_body .= $contentsString;
			}
			else
			{
				//output error message
				print( htmlentities($contentsString) ); 
			}

			mail($billingAddress["Email"], 
				L_ORDER_CONFIRMATION,
				$mail_body, 
				"From: " . EMAIL_FROM);
		}

		$ActionResults[] =  L_SUBMITORDER_SUCCESS;
	}
?>
