<?php
	/*
	** File: coupon
	** Description: functions for dealing with coupons
	** Version: $Revision: 1.2 $
	** Created: 11/4/1999
	** Author: Leon Atkinson
	** Email: leon@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 1999/12/21 20:41:48 $
	** Log : $Log: coupon,v $
	** Log : Revision 1.2  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.1  1999/11/05 18:17:51  leon
	** Log : Reorganized coupon code.
	** Log :
	**
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	*/

	$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);	

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


	/*
	** return the ID of a coupon based on the name
	*/
	function getCouponID($name)
	{
		GLOBAL $DatabaseLink;
		STATIC $coupon;
		
		if(!is_array($coupon))
		{
			//pull coupon names into array
			$Query = "SELECT ID, Name ";
			$Query .= "FROM coupon ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);
			while($DatabaseRow = mysql_fetch_object($DatabaseResult))
			{
				$coupon[strtoupper($DatabaseRow->Name)] = $DatabaseRow->ID;
			}			
		}
		
		return(intval($coupon[strtoupper($name)]));
	}

	/*
	** Returns an associative array for a coupon row
	*/
	function getCouponInfo($coupon)
	{
		GLOBAL $DatabaseLink;
		STATIC $info;
		
		if(!is_array($info))
		{
			//pull coupon table into array
			$Query = "SELECT ID, Name, DollarOff, PercentageOff, ";
			$Query .= "MinAmountPurchased, ";
			$Query .= "DATE_FORMAT(StartDate, '%Y%m%d') AS StartDate, ";
			$Query .= "DATE_FORMAT(EndDate, '%Y%m%d') AS EndDate, ";
			$Query .= "NeverExpires, Combineable ";
			$Query .= "FROM coupon ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);
			while($DatabaseRow = mysql_fetch_array($DatabaseResult))
			{
				$info[($DatabaseRow['ID'])] = $DatabaseRow;
			}			
		}

		return($info[$coupon]);
	}

	/*
	** Returns a dollar amount for coupon based on
	** the coupon ID and a given order total.
	*/
	function getCouponValue($coupon, $total)
	{
		//get the info on the coupon
		$info = getCouponInfo($coupon);
		
		//calculate the dollar amount
		if($info["DollarOff"] > 0)
		{
			$CouponValue = $info["DollarOff"];
		}
		else
		{
			$CouponValue = (doubleval($info["PercentageOff"]) / 100.00) * doubleval($total);
		}
		
		return($CouponValue);
	}

	/*
	** returns the number of a times a coupon has been used by a user
	*/
	function getCouponUses($coupon, $user)
	{
		GLOBAL $DatabaseLink;
		STATIC $uses;
		
		if(!is_array($uses[$user]))
		{
			$Query = "SELECT Coupon, COUNT(*) AS Uses ";
			$Query .= "FROM coupon_user ";
			$Query .= "WHERE User = $user ";
			$Query .= "GROUP BY coupon ";
			$DatabaseResult = mysql_query($Query, $DatabaseLink);
			while($DatabaseRow = mysql_fetch_object($DatabaseResult))
			{
				$uses[$user][($DatabaseRow->Coupon)] = $DatabaseRow->Uses;
			}			
		}

		return(intval($uses[$user][$coupon]));
	}


	/*
	** returns TRUE or FALSE based on whether a coupon is valid for
	** an order total an may be used with multiple coupons.
	*/
	function validateCoupon($coupon, $total, $multiple, &$reason)
	{
		global $DatabaseLink, $UserInfo;

		//get the info on the coupon
		$info = getCouponInfo($coupon);

		//start off assuming the coupon is good,
		//but quit on the first problem we find
		$valid = TRUE;

		//see if we recognize this coupon at all
		if(!isset($info['ID']) OR ($info['ID'] <= 0))
		{
			//the coupon isn't recognized
			$reason = "Unrecognized coupon";
			$valid = FALSE;
		}

		//check that it hasn't been used before
		if($valid AND (getCouponUses($coupon, $UserInfo['ID']) > 0))
		{
			//the coupon was used previously
			$reason = "You may not use this coupon more than once: " . $info['Name'];
			$valid = FALSE;
		}

		//make sure this coupon is combineable
		if($valid AND $multiple AND ($info['Combineable']==0))
		{
			//the coupon may be not combined with others
			$reason = "This coupon may not be used with others: " . $info['Name'];
			$valid = FALSE;
		}

		//make sure the total meets the minimum
		if($valid AND ($total <= $info['MinAmountPurchased']))
		{
			//the coupon needs a bigger order total
			$reason = $info['Name'] . " requires minium purchase of " . 
				formatMoney($info['MinAmountPurchased']);
		}
		
		//make sure coupon is live
		$tStart = mktime(0,0,0,
			substr($info['StartDate'], 4, 2),
			substr($info['StartDate'], 6, 2),
			substr($info['StartDate'], 0, 4));

		$tEnd = mktime(0,0,0,
			substr($info['EndDate'], 4, 2),
			substr($info['EndDate'], 6, 2),
			substr($info['EndDate'], 0, 4));

	
		if($valid AND ($info['NeverExpires'] == 0) AND (time() < $tStart))
		{
			//coupon isn't live yet
			$reason = "Coupon is not active yet.";
			$valid = FALSE;
		}

		if($valid AND ($info['NeverExpires'] == 0) AND (time() > $tEnd))
		{
			//coupon is expired
			$reason = "Coupon is expired. $tEnd " . time();
			$valid = FALSE;
		}

		return($valid);
	}

	/*
	** Function: validateCouponList
	** Input: STRING list, DOUBLE total, STRING REFERENCE reason
	** Output: BOOLEAN
	** Description: Given a list of coupons separated by spaces,
	** check each one for being valid.
	*/
	function validateCouponList($list, $total, &$reason)
	{
		//Get array of coupons separated by spaces
		//Then make an array with coupon codes for keys
		//and TRUE for values.  This elminates duplicates.
		
		$tcoupon = split(" ", $list);
		while(list($key, $current_coupon) = each($tcoupon))
		{
			$coupon[$current_coupon] = TRUE;
		}
		
		//check whether we have multiple coupons because
		//some coupons may not be combined with others
		$MultipleCoupons = FALSE;
		if(count($coupon) >  1)
		{
			$MultipleCoupons = TRUE;
		}

		$AllCouponsOK = TRUE;

		while($AllCouponsOK AND (list($current_coupon) = each($coupon)))
		{
			$AllCouponsOK = validateCoupon(getCouponID($current_coupon), $total, 
				$MultipleCoupons, $reason);
		}
		
		return($AllCouponsOK);
	}


	/*
	** Function: useCouponList
	** Input: STRING list, INTEGER invoice
	** Output: BOOLEAN
	** Description: Given a list of coupons separated by spaces,
	** attach each to the invoice.
	*/
	function useCouponList($list, $invoice)
	{
		global $DatabaseLink;

		/*
		** remove previous coupons
		*/
		$Query = "DELETE FROM invoice_coupon ";
		$Query .= "WHERE Invoice = $invoice ";
		if(!($DatabaseResult = mysql_query($Query, $DatabaseLink)))
		{
			//PANIC
			//The query didn't work!
			//(A call to the future log functionality should go here)
			print("\n\n<!-- ($Query) failed!\n" . 
				mysql_errno() . ": " . mysql_error() . "-->\n\n");

			return(FALSE);
		}
		
		/*
		** remove previous coupon fees
		*/
		$Query = "DELETE FROM invoice_fee ";
		$Query .= "WHERE Invoice = $invoice ";
		$Query .= "AND Fee = ".getFeeID('Coupon')." ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		if(!($DatabaseResult = mysql_query($Query, $DatabaseLink)))
		{
			//PANIC
			//The query didn't work!
			//(A call to the future log functionality should go here)
			print("\n\n<!-- ($Query) failed!\n" . 
				mysql_errno() . ": " . mysql_error() . "-->\n\n");

			return(FALSE);
		}

		/*
		** loop over each coupon
		*/
		$Total = calculateTotal($invoice);
		$coupon = split(" ", $list);
		reset($coupon);
		while(list($key, $current_coupon) = each($coupon))
		{
			//attach coupon to invoice
			$Query = "INSERT INTO invoice_coupon ";
			$Query .= "VALUES($invoice,  ".getCouponID($current_coupon).")";
			if(!($DatabaseResult = mysql_query($Query, $DatabaseLink)))
			{
				//PANIC
				//The query didn't work!
				//(A call to the future log functionality should go here)
				print("\n\n<!-- ($Query) failed!\n" . 
					mysql_errno() . ": " . mysql_error() . "-->\n\n");
	
				return(FALSE);
			}

			//add coupon fee
			$Query = "INSERT INTO invoice_fee ";
			$Query .= "VALUES($invoice, ";
			$Query .= getFeeID("Coupon") . ", ";
			$Query .= getCouponValue(getCouponID($current_coupon), $Total['Grand']) . ") ";
			if(!($DatabaseResult = mysql_query($Query, $DatabaseLink)))
			{
				//PANIC
				//The query didn't work!
				//(A call to the future log functionality should go here)
				print("\n\n<!-- ($Query) failed!\n" . 
					mysql_errno() . ": " . mysql_error() . "-->\n\n");
	
				return(FALSE);
			}

		}
		
		//Since we've added fees, we need to force a recalculation
		//of totals.  Ah, the pleasures of caching. :)
		calculateTotal($invoice, TRUE);
		
		return(TRUE);
	}
?>