<?php
	/*
	** File: calculateTotal
	** Description: function that calculates the total for an invoice
	** An array is returned with various subtotals
	** Version: 1.0
	** Created: 07/07/1999
	** Author: Leon Atkinson
	** Email: leon@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 1999/12/21 20:41:48 $
	**
	** Log : $Log: calculateTotal,v $
	** Log : Revision 1.8  1999/12/21 20:41:48  leon
	** Log : Fixed bug in billing that wasn't saving the address.  Moved coupon
	** Log : functionality into coupon module.
	** Log :
	** Log : Revision 1.7  1999/12/17 22:08:30  leon
	** Log : Added function to print invoice totals, consequently updated printTableRow
	** Log : to allow passing of styles.
	** Log :
	** Log : Revision 1.6  1999/12/16 21:58:43  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.5  1999/11/05 18:17:51  leon
	** Log : Reorganized coupon code.
	** Log :
	** Log : Revision 1.4  1999/11/02 18:23:08  chris
	** Log : Added support for coupons.
	** Log :
	** Log : Revision 1.3  1999/10/11 23:04:02  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.2  1999/08/18 22:32:03  leon
	** Log : Returning opening PHP tag to XML-friendly tag
	** Log :
	** Log : Revision 1.1  1999/07/28 21:18:33  leon
	** Log : New include modules based on code donation from a live project
	** Log :
	**
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	*/

	/*
	** Ensure that module isn't included twice
	*/

	$included_flag = 'INCLUDE_' . basename(__FILE__);
	
	if(defined($included_flag))
		//if this module has been included already, then the
		//constant will be defined.  Note the unusual use of
		//the return statement here.  Control will return to
		//the file that included it.
		return;
	
	define($included_flag, TRUE);	

	//need getFeeID
	include(APPLICATION_ROOT . "/modules/include/fee");


	/*
	** Function: calculateTotal
	** Input: INTEGER invoice
	** Output: ARRAY
	** Description: Returns totals for an invoice.  Caching
	** is used in case totals need to be fetched multiple times
	** in one request.
	*/
	function calculateTotal($invoice, $recalculate=FALSE)
	{
		global $DatabaseLink;

		//preserve totals over multiple calls
		static $InvoiceTotal;

		if($recalculate)
		{
			unset($InvoiceTotal[$invoice]);
		}

		//if the totals haven't been calculated,
		//then get them
		if(!isset($InvoiceTotal[$invoice]))
		{
			//init grand total
			$Total['Grand'] = 0.00;

			/*
			** get total item cost and freight
			**
			** We have to loop instead of summing because we need to choose
			** list price or sale price for each line item.
			*/
			$Total['Items'] = 0.00;
			$Total['Freight'] = 0.00;

			$Query = "SELECT Quantity, ListPrice, SalePrice, Freight ";
			$Query .= "FROM invoice_sku ";
			$Query .= "WHERE Invoice = $invoice ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);
			while($DatabaseRow = mysql_fetch_object($DatabaseResult))
			{
				if($DatabaseRow->SalePrice > 0)
				{
					$Total['Items'] += $DatabaseRow->Quantity * $DatabaseRow->SalePrice;
				}
				else
				{
					$Total['Items'] += $DatabaseRow->Quantity * $DatabaseRow->ListPrice;
				}
					
				$Total['Freight'] += $DatabaseRow->Quantity * $DatabaseRow->Freight;	
			}
			
			//add total of items and freight to grand total
			$Total['Grand'] += $Total['Items'] + $Total['Freight'];
	
			/*
			** get all the fees
			*/
			$Query = "SELECT Fee, SUM(Value) ";
			$Query .= "FROM invoice_fee ";
			$Query .= "WHERE Invoice = $invoice ";
			$Query .= "GROUP BY Fee ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);
			
			if(! $DatabaseResult)
			{
				print("\n\n<!--Failed to get fees!-->\n\n");
				
				//we probably should have a log entry here :)
			}
			else
			{
				while(list($tFee, $tValue) = mysql_fetch_row($DatabaseResult))
				{
					//coupons subtract from total
					if((getFeeName($tFee)) == "Coupon")
					{
						$tValue *= -1.00;
					}

					//store fee total indexed by name
					$Total[(getFeeName($tFee))] = $tValue;
					
					//add total to grand
					$Total['Grand'] += $tValue;
				}
			}
			
			//make sure a coupon doesn't turn the invoice
			//into a credit
			if($Total['Grand'] < 0.00)
			{
				$Total['Grand'] = 0.00;
			}
			
			//drop temporary array into cache
			$InvoiceTotal[$invoice] = $Total;
	
		}
		
		return($InvoiceTotal[$invoice]);
	
	}
	
	
	/*
	** Function: showTotals
	** Input: ARRAY total
	** Output: boolean
	** Description: Print all totals given the totals array returned
	** by calculateTotal().
	*/
	function showTotals($total)
	{
		//sort the array by fee name
		ksort($total);
		
		//print items total
		printTableRow("Items", 
			formatMoney($total["Items"]), 
			FALSE, 
			"font-weight: bold;", 
			"text-align: right;");
		
		//print fees
		reset($total);
		while(list($key) = each($total))
		{
			if(($key != "Items") AND ($key != "Grand"))
			{
				printTableRow($key, 
					formatMoney($total[$key]),
					FALSE, 
					"font-weight: bold;", 
					"text-align: right;");
			}
		}
		
		//print grand total
		printTableRow("", "<hr style=\"color: black;\">", FALSE);
		printTableRow("Grand Total", 
			formatMoney($total["Grand"]),
			FALSE, 
			"font-weight: bold;", 
			"text-align: right;");
		
		return(TRUE);
	}
?>