<?php

	/*
	** File: view_history
	** Description: Shows the user one of his past invoices.
	** Version: $Revision: 1.24 $
	** Created: 7/9/99
	** Author: Shannon -jj Behrens
	** Email: shannon.behrens@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/02/05 00:23:49 $
	** Log : $Log: view_invoice,v $
	** Log : Revision 1.24  2000/02/05 00:23:49  leon
	** Log : Removing number_format in favor of formatMoney
	** Log :
	** Log : Revision 1.23  1999/12/16 21:58:46  leon
	** Log : Refactored calculateTotal.  Now with fewer queries! Gift Wrap was being
	** Log : refered to as GiftWrap in the array returned by calculateTotal, so I changed
	** Log : it in the few places it was.  That allowed me to use a general strategy
	** Log : for storing fee totals.
	** Log :
	** Log : Revision 1.22  1999/12/06 21:17:29  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.21  1999/11/09 00:28:18  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.20  1999/11/08 22:32:31  leon
	** Log : Added prepareText() function to use everywhere we were using htmlentities.
	** Log :
	** Log : Revision 1.19  1999/11/04 21:35:46  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.18  1999/11/02 20:49:45  leon
	** Log : Added constant to control use of coupons
	** Log :
	** Log : Revision 1.17  1999/11/02 18:23:15  chris
	** Log : Added support for coupons.
	** Log :
	** Log : Revision 1.16  1999/10/12 23:14:50  leon
	** Log : Moved localization constants into 'english' module.  Added constant to
	** Log : control whether unregistered shoppers may checkout.
	** Log :
	** Log : Revision 1.15  1999/10/12 00:03:55  leon
	** Log : Moving text into constants in preparation of localization support
	** Log :
	** Log : Revision 1.14  1999/10/11 23:04:12  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/11 18:01:41  leon
	** Log : Pulling text into constants in preparation of building localization
	** Log : module.
	** Log :
	** Log : Revision 1.12  1999/09/10 00:21:09  jj
	** Log : Changed include("addressfunctions") -> require("addressfunctions");
	** Log :
	** Log : Revision 1.11  1999/08/24 00:28:38  jj
	** Log : Re-installed code that would let mortal users see status descriptions.
	** Log :
	** Log : Revision 1.10  1999/08/20 16:37:09  jj
	** Log : Mike Potter found a bug in create_user.
	** Log :
	** Log : Revision 1.9  1999/08/18 22:32:23  leon
	** Log : Returning opening PHP tag to XML-friendly tag
	** Log :
	** Log : Revision 1.8  1999/08/17 17:56:42  jj
	** Log : Modularized everything to do with addresses. Please see include/addressFunctions
	** Log :
	** Log : Revision 1.7  1999/08/11 22:46:50  jj
	** Log : Changed two small things: 1) the order of fields displayed on one of the forms 2) the alignment of one of the fields
	** Log :
	** Log : Revision 1.6  1999/08/10 23:16:42  jj
	** Log : Used $UserInfo for getting the user's address information rather than hitting the database.
	** Log :
	** Log : Revision 1.5  1999/08/10 00:04:48  jj
	** Log : Made use of UserInfo["ID"] instead of doing a query to figure out the user ID.
	** Log :
	** Log : Revision 1.4  1999/08/09 18:41:33  jj
	** Log : Changed a few field labels to make them "nicer".
	** Log :
	** Log : Revision 1.3  1999/08/09 18:27:29  jj
	** Log : Got rid of invoice status "Description" field any place where user could see it. God rid of any mention of batches (since Batch is not in build.sql).
	** Log :
	** Log : Revision 1.2  1999/07/30 16:40:57  jj
	** Log : Used wrong fields for name of product when I originally wrote these.  Bug fix.
	** Log :
	** Log : Revision 1.1  1999/07/28 19:41:13  leon
	** Log : Mass update based on code donation from a live project
	** Log :
	**
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	**
	** Expected Input: $sid, $invoice_ID
	*/


	/* Leon's function for calculating invoice totals. */
	include(APPLICATION_ROOT . "/modules/include/calculateTotal");

	// Function to output addresses
	include(APPLICATION_ROOT . "/modules/include/addressFunctions");

	//get attribute functions
	include(APPLICATION_ROOT . "/modules/include/attribute_functions");
	
	$continueReport = TRUE;
		
	
	
	/* 
	** Get the main invoice information and the billing address ID from 
	** the database. 
	*/
	$mainQuery = "SELECT i.User, i.Created, b.Address ";
	$mainQuery .= "FROM invoice i, billing b ";
	$mainQuery .= "WHERE i.ID = " . intval($invoice_ID) . " ";
	$mainQuery .= "AND b.Invoice = " . intval($invoice_ID);
	/* Execute the query. */ 
	if ( !($mainRecords = mysql_query($mainQuery, $DatabaseLink)) )
	{
		print("<!-- " . mysql_errno() . ": " . mysql_error() .
			"   Query was: $mainQuery -->\n");
		$continueReport = FALSE;
	}
	else 
	{
		/* Make sure that this is a valid invoice. */ 
		if (!mysql_num_rows($mainRecords))
		{
			print(L_VIEWINVOICE_INVALID . $invoice_ID . "<BR>\n");
			print("<A HREF=\"" . ScreenURL("order_history") . "\">");
			print(L_VIEWINVOICE_RETURN_TO_LIST);
			print("</A>");

			$continueReport = FALSE;
		}
		else 
		{
			$mainInvoiceInfo = mysql_fetch_row($mainRecords);
			$i = 0;
			$fromInvoiceUserID = $mainInvoiceInfo[$i++];
			$created = $mainInvoiceInfo[$i++];
			$billAddressID = $mainInvoiceInfo[$i++];
		}
	}


	
	/*
	** If $continueReport is true, in order to have "a little" bit of security,
	** we should verify that this $sid's userID does correspond to this 
	** invoice's userID.
	*/
	if ($continueReport)
	{
		if ($UserInfo["ID"] != $fromInvoiceUserID)
		{
			print(L_VIEWINVOICE_INVALID . $invoice_ID . "<BR>\n");
			print("<A HREF=\"" . ScreenURL("order_history") . "\">");
			print(L_VIEWINVOICE_RETURN_TO_LIST);
			print("</A>");

			$continueReport = FALSE;
		}
	}

	
	
	/* 
	** If $continueReport is true, then we can start by giving the user
	** some basic info like the number of the invoice we're editing, a link
	** back to order_history, when the invoice was created, etc.
	*/
	if ($continueReport)
	{
		/* Start the table and the heading. */
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>" . L_VIEWINVOICE_INVOICE_NUM . ":</B> $invoice_ID<BR>\n");

		/* Include the data. */ 
		print("<UL>\n");
		print("<LI><A HREF=\"" . ScreenURL("order_history") . "\">");
		print(L_VIEWINVOICE_RETURN_TO_HISTORY);
		print("</A>\n");
		print("<LI>");
		print(L_VIEWINVOICE_CREATED);
		print(": $created\n");
		print("</UL>\n");

		/* Finish up the table. */
		print("</TD></TR>\n</TABLE><BR>\n");
	}
	
	
	
	/*
	** If $continueReport is true, then we can retrieve the status information
	** from the database.  There may be multiple status rows for each invoice.
	*/
	if ($continueReport)
	{
		/*
		** Get the status information from the database. 
		*/
		$statusQuery = "SELECT s.Name, i.Created, i.Description ";
		$statusQuery .= "FROM status s, invoice_status i ";
		$statusQuery .= "WHERE i.Invoice=" . intval($invoice_ID) . " ";
		$statusQuery .= "AND i.Status = s.ID ";
		$statusQuery .= "ORDER BY i.Created";
		/* Execute the query. */
		if ( !($statusRecords = mysql_query($statusQuery, $DatabaseLink)) )
		{
			print("<!-- " . mysql_errno() . ": " . mysql_error() . 
				"   Query was: $statusQuery -->\n");
			$continueReport = FALSE;
		}
		else
		{
			/* Make sure we were able to get a record. */
			if ( !mysql_num_rows($statusRecords) )
			{
				print("<!-- There are no status records attached to this " . 
					"invoice! The query I used was $statusQuery -->\n");
				$continueReport = FALSE;
			}
		}
	}
	
	
	
	/*
	** Use $statusRecords, which we just created, to output a nice table 
	** for all of the status records. 
	*/
	if ($continueReport)
	{	
		/* Start the overall table and heading. */
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>".L_VIEWINVOICE_INVOICE_STATUS.":</B><BR>\n");
		
		/* Output the status table. */
		print("<TABLE>\n<TR>");
		print("<TD><B>".L_VIEWINVOICE_STATUS."</B></TD>\n");
		print("<TD><B>".L_VIEWINVOICE_DATE."</B></TD>\n");
		print("<TD><B>".L_VIEWINVOICE_NOTES."</B></TD>\n");
		print("</TR>\n");
		
		/* Output each status row. */
		while ($statusRow = mysql_fetch_row($statusRecords))
		{
			$i = 0;
			$statusStatus = $statusRow[$i++];
			$statusCreated = $statusRow[$i++];
			$statusDescription = $statusRow[$i++];
			print("<TR>\n");
			print("<TD>" . prepareText($statusStatus) . "</TD>\n");
			print("<TD>$statusCreated</TD>\n");
			print("<TD>" . prepareText($statusDescription) . "</TD>\n");
			print("</TR>\n");
		}
		print("</TABLE>\n");

		/* Finish up the overall table. */
		print("</TD></TR>\n</TABLE><BR>\n");
	}

	

	/*
	** If $continueReport is true, then we can output all of the user's address
	** information. 
	*/
	if ($continueReport)
	{
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>".L_VIEWINVOICE_CONTACT_INFO.":</B><BR>\n");
		outputAddress($UserInfo["Address"]);
		print("</TD></TR>\n</TABLE><BR>\n");
	}
	
	
	
	/* 
	** Retrieve all of the information from the "address" table attached to
	** $billAddressID and output it.
	*/
	if ($continueReport)
	{
		if ( !($billAddress = getAddress($billAddressID)) )
		{
			print(L_VIEWINVOICE_BAD_BILLING);
			$continueReport = FALSE;
		}
		else
		{
			print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
			print("<B>".L_VIEWINVOICE_BILLING_INFO.":</B><BR>\n");
			outputAddress($billAddress);
			print("</TD></TR>\n</TABLE><BR>\n");
		}
	}



	/*
	** If $continueReport is true, then we can give the user the list of 
	** sku's in this invoice.  
	*/ 
	if ($continueReport)
	{
		/* Start the table and the heading. */
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>".L_VIEWINVOICE_INVOICE_CONTENTS.":</B><BR>\n");

		/* We'll have to get the list of sku's from the database. */
		$skuesQuery = "SELECT v.ID, v.Quantity, i.Name, s.Name, v.Notes ";
		$skuesQuery .= "FROM item i, invoice_sku v, sku s ";
		$skuesQuery .= "WHERE v.Invoice = " . intval($invoice_ID) . " ";
		$skuesQuery .= "AND v.SKU = s.ID ";
		$skuesQuery .= "AND s.Item = i.ID";
		/* Execute the query. */ 
		if ( !($skuesRecords = mysql_query($skuesQuery, $DatabaseLink)) )
		{
			print("<!-- " . mysql_errno() . ": " . mysql_error() . 
				"   Query was: $skuesQuery -->\n");
			$continueReport = FALSE;
		}
		/* Retrieve the invoice skues, if any. */ 
		else
		{	/* No skues in this invoice. */
			if (!mysql_num_rows($skuesRecords))
			{ 
				print("<P><I>There are no items in this invoice.</I>\n");
			}
			/* Make a table full of the skues. */
			else
			{
				/* Start the table, and the headings. */ 
				print("<TABLE>\n<TR>\n");
				print("<TD VALIGN=\"top\"><B>".L_VIEWINVOICE_ITEM."</B></TD>\n");
				print("<TD VALIGN=\"top\"><B>".L_VIEWINVOICE_QUANTITY."</B></TD>\n");
				print("</TR>\n");

				/* Output a row for each sku. */ 
				while ($skuRow = mysql_fetch_row($skuesRecords))
				{
					/* Parse the row. */
					list($skuID, $skuQuantity, $skuItemName, $skuSkuName, 
						$skuNotes) = $skuRow;
					$sku_Variation = unserialize($skuNotes);

					/* Output the row. */
					print("<TR>\n");
					/* 
					** Give the user a link to view this ibid in more detail. 
					** I'm using ibid to represent a particular ID in the 
					** invoice_sku table. Ibid -> "in-basket ID".
					*/
					print("<TD><A HREF=\"" . ScreenURL("view_ibid"));
					print("&ibid=$skuID\">\n");
					print(prepareText($skuItemName) . // Item name + sku name 
						( $skuSkuName == "" ? "" :     // if there is one.
							": " . prepareText($skuSkuName) ) );
					print("</A>");

					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("</TD>\n");
					
					print("<TD ALIGN=\"CENTER\" VALIGN=\"top\">$skuQuantity</TD>\n");
					print("</TR>\n");
				}

				/* Finish up the table. */ 
				print("</TABLE>\n");			
			}
		}
		/* Finish up the table. */
		print("</TD></TR></TABLE><BR>\n");
	}
	
	

	/* 
	** If everything is okay so far, we can give a nice little "receipt-like" 
	** table detailing the invoice totals.
	*/
	if ($continueReport)
	{
		/* Start the table and heading. */
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>".L_VIEWINVOICE_TOTALS.":</B><BR>\n");
				print("<TABLE>\n");
		
		$Total = calculateTotal($invoice_ID);
		print("<TR><TD>".L_VIEWINVOICE_ITEMS_TOTAL."</TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($Total["Items"]) . "</TD></TR>\n");

		print("<TR><TD>".L_VIEWINVOICE_SHIPPING_TOTAL."</TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($Total["Shipping"]) . "</TD></TR>\n");

		print("<TR><TD>".L_VIEWINVOICE_FRIEGHT_TOTAL."</TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($Total["Freight"]) . "</TD></TR>\n");

		print("<TR><TD>".L_VIEWINVOICE_GIFTWRAP_TOTAL."</TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($Total["Gift Wrap"]) . "</TD></TR>\n");

		print("<TR><TD>".L_VIEWINVOICE_TAX_TOTAL."</TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($Total["Tax"]) . "</TD></TR>\n");

		if(USE_COUPONS)
		{
			print("<TR><TD>".L_VIEWINVOICE_COUPON_TOTAL."</TD>\n");
			print("<TD ALIGN=\"RIGHT\">" . formatMoney($Total["Coupon"]) . "</TD></TR>\n");
		}
		
		print("<TR><TD VALIGN=\"right\"><B>".L_VIEWINVOICE_TOTAL.":</B></TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($Total["Grand"]) . "</TD></TR>\n");

		/* Finish up the table. */
		print("</TABLE>\n");
		print("</TD></TR></TABLE><BR>\n");	
	}
	
?>
