<?php 

	/* 
	** File: edit_invoice
	** Description: allow company personnel to edit invoices
	** Version: $Revision: 1.22 $
	** Created: 6/15/99
	** Author: Shannon -jj Behrens
	** Email: shannon.behrens@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/02/05 00:23:47 $
	** Log : $Log: edit_invoice,v $
	** Log : Revision 1.22  2000/02/05 00:23:47  leon
	** Log : Removing number_format in favor of formatMoney
	** Log :
	** Log : Revision 1.21  2000/01/13 23:55:17  leon
	** Log : The script now allows you to edit an invoice that was created by user
	** Log : who wasn't logged in.
	** Log :
	** Log : Revision 1.20  1999/12/16 21:58:45  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.19  1999/12/07 21:45:09  leon
	** Log : All forms should be using StartForm now...
	** Log :
	** Log : Revision 1.18  1999/12/06 21:17:25  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/09 00:28:16  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.16  1999/11/08 22:32:25  leon
	** Log : Added prepareText() function to use everywhere we were using htmlentities.
	** Log :
	** Log : Revision 1.15  1999/11/04 21:35:41  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/10/13 22:19:01  chris
	** Log : Moving text into constants in preparation of localization support.
	** Log :
	** Log : Revision 1.13  1999/10/13 00:42:28  chris
	** Log : Moving text into constants in preparation of localization support.
	** Log :
	** Log : Revision 1.12  1999/10/11 23:04:09  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.11  1999/09/20 19:20:03  jj
	** Log : For cancelled invoices, I am not longer allowing the admin to add new status records.  Should we go as far as disallow him from even viewing the invoice?
	** Log :
	** Log : Revision 1.10  1999/08/18 22:32:15  leon
	** Log : Returning opening PHP tag to XML-friendly tag
	** Log :
	** Log : Revision 1.9  1999/08/17 17:56:42  jj
	** Log : Modularized everything to do with addresses. Please see include/addressFunctions
	** Log :
	** Log : Revision 1.8  1999/08/10 18:01:47  jj
	** Log : Created and used an addressEditor function rather than cutting and pasting everytime.
	** Log :
	** Log : Revision 1.7  1999/08/09 22:30:31  jj
	** Log : Any selects for Country now use makeCountrySelect (an include)
	** Log :
	** Log : Revision 1.6  1999/08/09 18:41:33  jj
	** Log : Changed a few field labels to make them "nicer".
	** Log :
	** Log : Revision 1.5  1999/08/09 18:27:28  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.4  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.3  1999/07/28 19:27:31  leon
	** Log : Mass update based on code donation from a live project
	** Log :
	**
	** Copyright (c) 1999 Working Dogs. All rights reserved. 
	**
	** Expected input: $invoice_ID
	*/
	
	// Use the function to create the address editor forms
	include(APPLICATION_ROOT . "/modules/include/addressFunctions");

	//get attribute functions
	include(APPLICATION_ROOT . "/modules/include/attribute_functions");


	$continueReport = TRUE;
	
	//Make sure the user has admin rights
	if( !$UserInfo["Permission"]["Administrate"] )
	{
		print(L_EDITINVOICE_DENIED . "<BR>\n");
		$continueReport = FALSE;
	}
	
	
	/* 
	** Get the main invoice information and the two address pointers from 
	** the database. 
	*/
	if($continueReport)
	{
		$Query = "SELECT i.User, i.Created, b.Address AS billAddress, u.Address AS userAddress ";
		$Query .= "FROM invoice i LEFT JOIN user u ON i.User = u.ID, billing b ";
		$Query .= "WHERE i.ID = " . intval($invoice_ID) . " ";
		$Query .= "AND b.Invoice = " . intval($invoice_ID) . " ";

		if(!($DatabaseResult = mysql_query($Query, $DatabaseLink)) )
		{
			print("<!-- " . mysql_errno() . ": " . mysql_error() .
				"   Query was: $Query -->\n");
			$continueReport = FALSE;
		}
	}

	//test that the invoice was found, if not things are messed up	
	if(($continueReport) AND (mysql_num_rows($DatabaseResult) <= 0))
	{
		print("<i>Invoice \"$invoice_ID\" is was not found in ");
		print("the database.  This could be because you typed an invoice ");
		print("ID that doesn't exist.  It could also be that the invoice ");
		print("exists, but has no billing record.  This can happen under ");
		print("extreme cases.  You should immediately investigate this ");
		print("invoice in the database by hand.");

		$continueReport = FALSE;
	}


	if($continueReport)
	{
		$Row = mysql_fetch_object($DatabaseResult);
		$userID = $Row->User;
		$created = $Row->Created;
		$billAddressID = $Row->billAddress;
		$userAddressID = (integer)$Row->userAddress;
	}



	/* 
	** If $continueReport is true, then we can start by giving the admin
	** some basic info like the number of the invoice we're editing, a link
	** back to admin_invoice, 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_EDITINVOICE_INVOICENUMBER . "</B> $invoice_ID<BR>\n");

		/* Include the data. */ 
		print("<UL>\n");
		print("<LI><A HREF=\"" . ScreenURL("admin_invoice") . "\"> " . L_EDITINVOICE_RETURN . "</A> " . 
			L_EDITINVOICE_LISTOFINVOICES. "\n");
		print("<LI>" . L_EDITINVOICE_CREATED . " $created\n");

		/* Finish up the UL. */
		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 i.Status, 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. Once that is done, give the user a
	** form to add another status record.
	*/
	if ($continueReport)
	{	
		/* Start the overall table and heading. */
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>" . L_EDITINVOICE_INVOICESTATUS . "</B><BR>\n");

		/* Output the status table. */
		print("<TABLE>\n<TR>");
		print("<TD><B>" . L_EDITINVOICE_STATUS . "</B></TD>\n");
		print("<TD><B>" . L_EDITINVOICE_DATE . "</B></TD>\n");
		print("<TD><B>" . L_EDITINVOICE_NOTES . "</B></TD>\n");
		print("</TR>\n");
		/* Output each status row. */
		while ($statusRow = mysql_fetch_row($statusRecords))
		{
			list ($statusID, $name, $created, $description) = $statusRow;
			if ($statusID == INVOICE_CANCELLED) {
				$invoiceCancelled = TRUE;
			}
			print("<TR>\n");
			print("<TD>" . prepareText($name) . "</TD>\n");
			print("<TD>$created</TD>\n");
			print("<TD>" . prepareText($description) .
				"</TD>\n");
			print("</TR>\n");
		}
		print("</TABLE>\n");

		/* Output the form to allow the user to add another status record. */
		if (!$invoiceCancelled)
		{
			print(StartForm("edit_invoice", 'post', 'ADD_STATUS', FALSE, 
				array("invoice_ID"=>$invoice_ID)));

			print("<TABLE>\n");
			print("<TR><TD COLSPAN=\"2\"><B>" . L_EDITINVOICE_CHANGESTATUS . "</B></TD></TR>\n");

			/* 
			** "Status" is a select. We'll have to get the list of possible values
			** from the database.
			*/
			$valuesQuery = "SELECT ID, Name FROM status";
			/* Execute the query. */ 
			if ( !($valuesRecords = mysql_query($valuesQuery, $DatabaseLink)) )
			{
				print("<!-- " . mysql_errno() . ": " . mysql_error() . 
					"   Query was: $valuesQuery -->\n");
			}
			else 
			{
				print("<TR><TD>" . L_EDITINVOICE_STATUS2 . "</TD>\n");
				print("<TD><SELECT NAME=\"inputStatus\">\n");
				while ($row = mysql_fetch_row($valuesRecords))
				{
					print("<OPTION VALUE=\"" . $row[0] . "\">"); 
					print(prepareText($row[1]) . "\n");
				}
				print("</SELECT></TD></TR>\n");
			}

			print("<TR><TD>" . L_EDITINVOICE_NOTES2 . "</TD>\n");
			print("<TD><INPUT TYPE=\"text\" NAME=\"inputDescription\">\n");
			print("</TD></TR>\n");

			/* Finish up the form. */
			print("<TR><TD COLSPAN=\"2\">\n");
			print("<INPUT TYPE=\"SUBMIT\" VALUE=\"" . L_EDITINVOICE_SUBMIT . "\">\n");
			print("<INPUT TYPE=\"RESET\" VALUE=\"" . L_EDITINVOICE_RESET . "\">\n");
			print("</TD></TR>\n");
			print("</TABLE>\n");
			print("</FORM>\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. We'll put it all in a form so that it's editable.
	**
	** If this invoice was created by a user who wasn't logged in, then
	** we can't show this form, so we'll just skip it.
	*/
	if(($continueReport) AND ($userAddressID > 0))
	{
		print(StartForm("edit_invoice", 'post', 'UPDATE_ADDRESS', FALSE, 
			array("invoice_ID"=>$invoice_ID, "addressID"=>$userAddressID)));

		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>" . L_EDITINVOICE_USERCONTACTINFO . "</B>&nbsp;\n");
		print("<A HREF=\"" . ScreenURL("edit_user"));
		print("&ID=$userAddressID\">" . L_EDITINVOICE_MORE . "</A><BR>\n");
		
		outputAddress(getAddress($userAddressID), 
			array("Name_First",
				"Name_Last",
				"City",
				"StateProv")
			);
		
		print("</TD></TR></TABLE>\n");
		print("</FORM>\n");
	}



	/*
	** If $continueReport is true, then we can use $billAddressID to get 
	** all of the address information for the "billing" person. We'll use 
	** a form so that the fields are editable.
	*/
	if ($continueReport)
	{	
		/* Start the table, the form, and the heading. */

		print(StartForm("edit_invoice", 'post', 'UPDATE_ADDRESS', FALSE, 
			array("SearchType"=>"advanced")));

		print("<INPUT TYPE=\"hidden\" NAME=\"sid\" VALUE=\"$sid\">\n");
		print("<INPUT TYPE=\"hidden\" NAME=\"SCREEN\" VALUE=\"edit_invoice\">\n");
		print("<INPUT TYPE=\"hidden\" NAME=\"ACTION\" VALUE=\"UPDATE_ADDRESS\">\n");
		print("<INPUT TYPE=\"hidden\" NAME=\"invoice_ID\" " . 
			"VALUE=\"$invoice_ID\">\n");
		print("<INPUT TYPE=\"hidden\" NAME=\"addressID\" " . 
			"VALUE=\"$billAddressID\">\n");
		print("<TABLE BORDER=\"1\" WIDTH=\"100%\"><TR><TD>\n");
		print("<B>" . L_EDITINVOICE_BILLINGCONTACTINFO . "</B><BR>\n");
		
		printAddressFields(
			getAddress($billAddressID), 
			"input", 
			"ALL");
		
		print("</TD></TR></TABLE>\n");
		print("</FORM>\n");
	}



	/*
	** If $continueReport is true, then we can give the admin 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>Invoice Contents:</B><BR>\n");

		/* We'll have to get the list of sku's from the database. */
		$skuesQuery = "SELECT v.ID, v.SKU, v.ExternalSKU, 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>" . L_EDITINVOICE_NOITEMS . "</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_EDITINVOICE_IBID . "</B></TD>\n");
				print("<TD VALIGN=\"top\"><B>" . L_EDITINVOICE_SKU . "</B></TD>\n");
				print("<TD VALIGN=\"top\"><B>" . L_EDITINVOICE_EXTERNALSKU . "</B></TD>\n");
				print("<TD VALIGN=\"top\"><B>" . L_EDITINVOICE_QUANTITY . "</B></TD>\n");
				print("<TD VALIGN=\"top\"><B>" . L_EDITINVOICE_NAME . "</B></TD>\n");
				print("<TD VALIGN=\"top\"><B>" . L_EDITINVOICE_NOTES . "</B></TD>\n");
				print("</TR>\n");

				/* Output a row for each sku. */ 
				while ($skuRow = mysql_fetch_row($skuesRecords))
				{
					/* Parse the row. */
					list($skuID, $skuSKU, $skuExternalSKU, $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("edit_ibid"));
					print("&ibid=$skuID");
					print("\">$skuID</A></TD>\n");
					print("<TD>$skuSKU</TD>\n");
					print("<TD>" . prepareText($skuExternalSKU) . "</TD>\n");
					print("<TD>$skuQuantity</TD>\n");
					print("<TD>" . prepareText($skuItemName));
					print( $skuSkuName == "" ? "" :
						(": " . prepareText($skuSkuName)) );
					print("</TD>\n");

					if(is_array($sku_Variation))
					{
						print("<TD>\n");
						
						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("</TR>\n");
				}

				/* Finish up the table. */ 
				print("</TABLE>\n");			
			}
		}
		/* Finish up the form and 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_EDITINVOICE_INVOICETOTALS . "</B><BR>\n");
				print("<TABLE>\n");

		/* Get Leon's function for calculating the total, and execute it. */
		include(APPLICATION_ROOT . "/modules/include/calculateTotal");
		$totals = calculateTotal($invoice_ID);

		print("<TR><TD>" . L_EDITINVOICE_TOTALOFITEMS . "</TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($totals["Items"]) . "</TD></TR>\n");

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

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

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

		print("<TR><TD>" . L_EDITINVOICE_COUPON . "</TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($totals["Coupon"]) . "</TD></TR>\n");

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

		print("<TR><TD VALIGN=\"right\"><B>" . L_EDITINVOICE_TOTAL . "</B></TD>\n");
		print("<TD ALIGN=\"RIGHT\">" . formatMoney($totals["Grand"]) . "</TD></TR>\n");

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