<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Programmer<programmer@armia.com>        		              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com � 2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
?>
<?php
include "includes/config.php";
include "includes/session.php";
include "includes/functions.php";


if(isset( $_SESSION["sess_userid"]) and $_SESSION["sess_userid"]!= ""){
	$userid = $_SESSION["sess_userid"];
}

if(isCartEmpty($userid)){
	header("Location:viewcart.php");
	exit;
}

$payment_completed = "false";

$txtFirstName = $_SESSION["sessBillingFirstName"];
$txtLastName = $_SESSION["sessBillingLastName"] ;
$txtAddress = $_SESSION["sessBillingAddress1"];
$txtCity = $_SESSION["sessBillingCity"] ;
$txtState = $_SESSION["sessBillingState"];
$txtZIP = $_SESSION["sessBillingZIP"];
$txtEmail= $_SESSION["sessBillingEmail"];
$ddlCountry = $_SESSION["sessBillingCountry"];
$txtPhone=$_SESSION["sessBillingPhone"];

$gift_coupon_flag = 0;

$currency_attributes = displayCurrencyType();

	/*-------function call to check whether cart contains digital or gift coupon products so as to hide shipping---*/
	
	$hide_shipping_division = hideShipping();
	
	/*-------function call to check whether cart contains digital or gift coupon products so as to hide shipping------*/
							
	$check_shipping_enable = checkShippingEnable();


if(isset($_POST['gift_coupon_code']))
{

	
	
	$totaltopay = $_POST['cart_total'];
	

	$sql = "INSERT INTO  " . $tableprefix . "orders (
				user_id,
				billing_first_name,
				billing_last_name,
				billing_address1,
				billing_address2,
				billing_city,
				billing_state,
				billing_country,
				billing_zip,
				billing_fax,
				billing_email,
				billing_phone,
				shipping_first_name,
				shipping_last_name,
				shipping_address1,
				shipping_address2,
				shipping_city,
				shipping_state,
				shipping_country,
				shipping_zip,
				shipping_fax,
				shipping_email,
				shipping_phone,
				prefered_shippin_method,
				order_date,
				order_total_price,
				order_status,
				vorder_currency
				) VALUES(
				'".addslashes($_SESSION["sess_userid"])."',
				'".addslashes($_SESSION["sessBillingFirstName"])."',
				'".addslashes($_SESSION["sessBillingLastName"])."',
				'".addslashes($_SESSION["sessBillingAddress1"])."',
				'".addslashes($_SESSION["sessBillingAddress2"])."',
				'".addslashes($_SESSION["sessBillingCity"])."',
				'".addslashes($_SESSION["sessBillingState"])."',
				'".addslashes($_SESSION["sessBillingCountry"])."',
				'".addslashes($_SESSION["sessBillingZIP"])."',
				'".addslashes($_SESSION["sessBillingFAX"])."',
				'".addslashes($_SESSION["sessBillingEmail"])."',
				'".addslashes($_SESSION["sessBillingPhone"])."',
				'".addslashes($_SESSION["sessShippingFirstName"])."',
				'".addslashes($_SESSION["sessShippingLastName"])."',
				'".addslashes($_SESSION["sessShippingAddress1"])."',
				'".addslashes($_SESSION["sessShippingAddress2"])."',
				'".addslashes($_SESSION["sessShippingCity"])."',
				'".addslashes($_SESSION["sessShippingState"])."',
				'".addslashes($_SESSION["sessShippingCountry"])."',
				'".addslashes($_SESSION["sessShippingZIP"])."',
				'".addslashes($_SESSION["sessShippingFAX"])."',
				'".addslashes($_SESSION["sessShippingEmail"])."',
				'".addslashes($_SESSION["sessShippingPhone"])."',
				'".addslashes($_SESSION["sessShippingMethod"])."',
				now(),
				'".addslashes($totaltopay)."',
				'1',
				'".$currency_attributes[2]."'
				)";
		mysql_query($sql) or die(mysql_error());
        $orderid = mysql_insert_id();
		


/*---------------update the shipping details----------------*/
		
		if($check_shipping_enable == "Y" && $hide_shipping_division == 1)
		{ // start of shipping if
						
			$select_cart_products = "SELECT product_id FROM ".$tableprefix."cart 
							 		 WHERE user_id = ".$_SESSION["sess_userid"];
							 
			$result_cart_products = mysql_query($select_cart_products) or die(mysql_error());
			
			if(mysql_num_rows($result_cart_products) > 0)
			{
			
				while($cart_row = mysql_fetch_array($result_cart_products))
				{
			
			
					$update_shipping = "UPDATE ".$tableprefix."shipping_details
										SET norder_id = ".$orderid.",
											vshipping_currency = '".$currency_attributes[2]."',
											dshipped_date = now(),
											nshp_status = 'C'
										WHERE nshp_productid = ".$cart_row['product_id']."
										 AND nshp_status = 'P'";
					mysql_query($update_shipping) or die(mysql_error());
					
				} // end while
			
			} // end if		
			
							
		} // end of shipping if 
	

		
		/************************** Affilate payment block*********************************************/

           $sql = "select * from  " . $tableprefix . "users where user_id='".addslashes($_SESSION["sess_userid"])."'";
           $result = mysql_query($sql);
           $row = mysql_fetch_array($result);
           if ($row["affiliate_id"] != "" && $row["affiliate_id"] != "0" && $row["vaff_type"] != "paid")
		   {
                                $aid=$row['affiliate_id'];
								$userid=$row['user_id'];
								$txtUserName=$row['user_name'];
								$txtFirstName=$row['first_name'];
								$txtEmail=$row['email'];
								$txtorderdamount=$totaltopay;
                                 	$sql1 = "SELECT * FROM ".$tableprefix."settings ";
									$result1 = mysql_query($sql1);
									if(mysql_num_rows($result1) != 0)
									{
										$row1 = mysql_fetch_array($result1);
										
										/*referral charge calculation based on the currency type*/				
																			
										$txtReferralCharge = ($currency_attributes[1] * $row1["referral_charge"]);
										
									}
                                   $var_aff_comm = ($txtorderdamount * $txtReferralCharge / 100);

                       			$sql2 = "INSERT INTO ".$tableprefix."affiliate_registrations (
											affiliate_id,
											user_id,
											user_name ,
											user_first_name,
											user_last_name,
											user_email,
											referral_charge,
											registration_date,
											user_totalpurchasedamount
											) VALUES (
											'".addslashes($aid)."',
											'".addslashes($userid)."',
											'".addslashes($txtUserName)."',
											'".addslashes($txtFirstName)."',
											'".addslashes($txtLastName)."',
											'".addslashes($txtEmail)."',
											'".addslashes($var_aff_comm)."',
											now(),'$totaltopay'
											)";
											mysql_query($sql2);

											 $sql3 = " update " . $tableprefix . "users set vaff_type='paid' where user_id='".addslashes($_SESSION["sess_userid"])."'";
									         $result3 = mysql_query($sql3);
                                                                                 sendReferralPurchaseMailtoAffliate($aid);

           }

		/************************** Affilate payment block*********************************************/

		$product_download_details = MAIL_PRODUCT_DOWNLOAD_DETAILS."\r\n";
		$product_download_details .= "-----------------------\r\n";
		$product_download_flag = 0;
		$download_link = "";
		
		//$orderid = mysql_insert_id();
		$sql = "SELECT c.*,p.product_price,p.product_name,p.product_code,p.product_artist_id,p.discount,
						p.vdigital_product
				FROM " . $tableprefix . "cart c INNER JOIN " . $tableprefix . "products p ON c.product_id = p.product_id
				WHERE c.user_id = '".addslashes($_SESSION["sess_userid"])."' ";
							
		$res = mysql_query($sql);
		$artists = array();
		if(mysql_num_rows($res) != 0)
		{ // start if product details
			$i=0;
						
			while($row = mysql_fetch_array($res))
			{ // start while product details
						
				$productid = $row["product_id"];
				$gift_coupon_products .= $productid.",";
				$quantity = $row["quantity"];
								
				/*product price is calculated based on currency type*/
				
				
				 $get_convert_price = getSellerCurrency($row["product_id"]);
							 							 							 
				 if($get_convert_price != "")
				 {
					 $converted_price = ($row["product_price"]/$get_convert_price);
				 }
				 else
				 {
					$converted_price = $row["product_price"];
				 } 	 
				
				$productprice = number_format(($currency_attributes[1] * $converted_price),2,".","");
				
								
				$productname 	  =  $row["product_name"];
				$productcode 	  =  $row["product_code"];
				$productdiscount  =  $row["discount"];
				$artistid 		  = $row["product_artist_id"];
				
				
/*-------------------mail sending gift coupon code starts----------------------*/
						
		
		
			$select_gift_code = "SELECT vgift_coupon_code,ngift_coupon_amount
								 FROM ".$tableprefix."giftcoupon_master 
								 WHERE ngift_product_id = ".$productid;
								 
		 
			$result_gift_code = mysql_query($select_gift_code) or die(mysql_error());
			
			if(mysql_num_rows($result_gift_code)>0)
			{ // start of first if
			
				
				$gift_coupon_product_id = $productid;
				
				while($gift_code_row = mysql_fetch_array($result_gift_code))
				{ // start of while 2
				
/*--------------------creating random gift coupon code and updating the database-----------------------*/
							
						$gift_coupon_code = "GC".randomGiftCouponKey();
																		
											
						if($gift_code_row['vgift_coupon_code'] == "")
						{ // start of coupon code null checking
				
								
/*-----------updating the gift coupon code------------*/				
												
						$update_gift_coupon_code = "UPDATE ".$tableprefix."giftcoupon_master 
													SET vgift_coupon_code = '".$gift_coupon_code."',
													ngift_order_id  = ".$orderid."
													WHERE ngift_product_id = ".$productid;
						
						mysql_query($update_gift_coupon_code) or die(mysql_error());
											
						$gift_coupon_link .= MAIL_GIFT_CERTIFICATE_CODE." ".$gift_coupon_code."\r\n";
						$gift_coupon_link .= MAIL_GIFT_CERTIFICATE_AMOUNT." ".$productprice."\r\n\n";
						
						$select_coupon_count = "SELECT ngift_id FROM ".$tableprefix."giftcoupon_master WHERE ngift_order_id = ".$orderid;
																												
						$result_coupon_count = mysql_query($select_coupon_count) or die(mysql_error());
						
						for($i=1;$i<$row["quantity"];$i++)
						{ // start of for loop
										
										
							$gift_coupon_code = "GC".randomGiftCouponKey();
						
							$insert_coupon_code = "INSERT INTO ".$tableprefix."giftcoupon_master(vgift_coupon_code,ngift_product_id,
															ngift_order_id,ngift_coupon_amount,vgift_currency)
															VALUES('".$gift_coupon_code."',
															".$row["product_id"].",
															".$orderid.",
															".$productprice.",
															'USD')";
							
							mysql_query($insert_coupon_code) or die(mysql_error());
																	
							$gift_coupon_link .= MAIL_GIFT_CERTIFICATE_CODE." ".$gift_coupon_code."\r\n";
							$gift_coupon_link .= MAIL_GIFT_CERTIFICATE_AMOUNT." ".$productprice."\r\n\n";
							
						}	// end of for loop
					
													
				} // end of coupon code null checking		
				else
				{ 
/*----------if coupon code is not null--------------*/				
				
				
					$select_coupon_count = "SELECT ngift_id FROM ".$tableprefix."giftcoupon_master WHERE ngift_order_id = ".$orderid;
																											
					$result_coupon_count = mysql_query($select_coupon_count) or die(mysql_error());
									
					
					if(mysql_num_rows($result_coupon_count) < $row["quantity"])
					{
						
						$insert_coupon_code = "INSERT INTO ".$tableprefix."giftcoupon_master(vgift_coupon_code,ngift_product_id,
														ngift_order_id,ngift_coupon_amount,vgift_currency)
														VALUES('".$gift_coupon_code."',
														".$row["product_id"].",
														".$orderid.",
														".$productprice.",
														'USD')";
						
						mysql_query($insert_coupon_code) or die(mysql_error());
																
						$gift_coupon_link .= MAIL_GIFT_CERTIFICATE_CODE." ".$gift_coupon_code."\r\n";
						$gift_coupon_link .= MAIL_GIFT_CERTIFICATE_AMOUNT." ".$productprice."\r\n\n";
										
					}	
				
				
			
				}
				
			
			} // end of while 2
			
			$gift_coupon_flag = 1;
																				
		} // end of first if
			
		
		
		if($gift_coupon_flag == 1)
		{ // start of if condition
		
/*-------Email Template Reading Fuction Call--------*/				
				
				
				$select_user_email = "SELECT email FROM ".$tableprefix."users WHERE user_id = ".$_SESSION["sess_userid"];
				$result_user_email = mysql_query($select_user_email) or die(mysql_error());
				
				if(mysql_num_rows($result_user_email) > 0)
				{
					
					$user_email_row = mysql_fetch_assoc($result_user_email);
					$txtEmail = $user_email_row['email'];  
				}	
				
								
				$mailcontent = readEmailTemplate('gift_coupon');
				$mailcontent = str_replace('[coupon_details]',$gift_coupon_link,$mailcontent);
															
				$subject = MAIL_GIFT_COUPON_SUBJECT." ".SITE_NAME;
				
				$headers  = "MIME-Version: 1.0" . "\r\n";
				$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
				$headers .= "From: ".SITE_EMAIL."<".SITE_EMAIL.">" . "\r\n";
				
/*------------Seller Store Url---------------------*/								
				
// send the friendly url in mail based on config settings

				if($enable_seller_friendly == "Y")
				{
				
					$select_seller_name = "SELECT artist_name FROM ".$tableprefix."artists WHERE artist_id = ".$artistid;
					$result_seller_name = mysql_query($select_seller_name) or die(mysql_error());
					
					if(mysql_num_rows($result_seller_name) > 0)
					{
						
						$seller_name_row = mysql_fetch_assoc($result_seller_name);
						$txtSellerName = $seller_name_row['artist_name'];  
					}	
										
					$friendly_url = SITE_URL."/store/".$txtSellerName; 							
											
				
				}
				else
				{
				
													
					$friendly_url = SITE_URL."/showportfolio.php?artistid=".$artistid; 							
				
				
				}				
			
				$mailcontent .= "\n\n*-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*\r\n";
				$mailcontent .= "\r\n"."<font color='#FF0000'>".MAIL_GIFT_COUPON_NOTE."</font>"."\r\n\n";
				$mailcontent .= "<b>".$friendly_url."</b>";
				
/*------------Seller Store Url---------------------*/								
				
				$mailcontent = nl2br($mailcontent);
				
				$mail_send_details = "<html><head><link href='".SITE_URL."/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=".$logofolder."/".$logoimage." width='125' height='39'/></div></div><div>".$mailcontent."</div></div><div align='left' class='clear_float'><img src=".$imagefolder."/clear.gif width=1 height=1/></div></div></div></center></body></html>";
								
				mail($txtEmail,$subject,$mail_send_details,$headers);
					
		}// end of if condition
			
/*----------------------mail sending gift coupon code ends------------------------*/				

																
				
				
/*------------------Digital Product Download Starts-------------*/
				
				if($row['vdigital_product'] == "Y")
				{
								
						$digital_product_id = $row["product_id"];														
											
						$select_product_digital_code = "SELECT vdigital_product_name,vdigital_product_code,ndownload_try,ndownload_expiry,ndownload_expiry_days 
														FROM ".$tableprefix."digital_product 
														WHERE ndigital_productid = ".$row["product_id"];
														
						$result_product_digital_code = mysql_query($select_product_digital_code);
																		
						if(mysql_num_rows($result_product_digital_code) > 0)
						{
							while($product_digital_code_row = mysql_fetch_array($result_product_digital_code))
							{
							
								/*creating random product download code and updating the database*/
							
								$digital_product_code = randomDigitalProduct();
							
								if($product_digital_code_row['vdigital_product_code'] == "")
								{
								
								/*-------Calculating the download expiry days----------*/
								
									/*$select_digital_product_expiry = "SELECT ndownload_expiry_days FROM ".$tableprefix."digital_product 
																	  WHERE ndigital_productid = ".$row["product_id"];
									$result_digital_product_expiry = mysql_query($select_digital_product_expiry) or die(mysql_error());	
									
									$digital_product_expiry_row = mysql_fetch_assoc($result_digital_product_expiry);*/							
									
									$expiry_days = 	$product_digital_code_row['ndownload_expiry_days'];							  
									
									$valid_date_upto = date("Y-m-d H:s:m",mktime(date("H"),date("i"),date("s"),date("m"),date("d")+$expiry_days,date("Y")));
									
								/*-------Calculating the download expiry days----------*/	
																
									$update_product_digital_code = "UPDATE ".$tableprefix."digital_product 
																	SET vdigital_product_code = '".$digital_product_code."',
																	ndigital_orderid = ".$orderid.",
																	ndownload_expiry = '".$valid_date_upto."'  	 
																	WHERE ndigital_productid = ".$row["product_id"];
																	
									mysql_query($update_product_digital_code) or die(mysql_error());
									
									/*---------selecting the download try and download expiry date-----------*/
									
									$select_digital_product_details = "SELECT ndownload_try,ndownload_expiry 
													   				   FROM ".$tableprefix."digital_product WHERE ndigital_productid = ".$productid;
									$result_digital_product_details = mysql_query($select_digital_product_details) or die(mysql_error());
									
									$digital_product_details_row = mysql_fetch_assoc($result_digital_product_details);								   
																		
									$product_download_try = $digital_product_details_row["ndownload_try"];
									$download_expiry_date = $digital_product_details_row["ndownload_expiry"];
									
									/*---------selecting the download try and download expiry date-----------*/
									
									$download_link .= MAIL_DOWNLOAD_LINK." - ".SITE_URL."/digital_product_download.php?download_code=$digital_product_code\r\n";
									
									$select_digital_count = "SELECT ndigital_id FROM ".$tableprefix."digital_product WHERE ndigital_orderid = ".$orderid;
																											
									$result_digital_count = mysql_query($select_digital_count) or die(mysql_error());
									
									
									
									//echo "digital count = ".mysql_num_rows($result_digital_count)."\n";
									
									//echo "order count = ".$row["quantity"];
									
								
									for($i=1;$i<$row["quantity"];$i++)
								
									//if(mysql_num_rows($result_digital_count) <= $row["quantity"])
									{
									
								/*-------Calculating the download expiry days----------*/	
									
										$expiry_days = 	$product_digital_code_row['ndownload_expiry_days'];							  
									
										$valid_date_upto = date("Y-m-d H:s:m",mktime(date("H"),date("i"),date("s"),date("m"),date("d")+$expiry_days,date("Y")));
									
								/*-------Calculating the download expiry days----------*/	
									
										$digital_product_code = randomDigitalProduct();
									
										$insert_product_digital_code = "INSERT INTO ".$tableprefix."digital_product(vdigital_product_name,ndigital_productid,
																		ndigital_orderid,vdigital_product_code,ndownload_try,ndownload_count,ndownload_expiry,ndownload_expiry_days,
																		ndownload_status)VALUES('".$product_digital_code_row['vdigital_product_name']."',
																		".$row["product_id"].",
																		".$orderid.",
																		'".$digital_product_code."',
																		".$product_digital_code_row['ndownload_try'].",0,
																		'".$valid_date_upto."',".$product_digital_code_row['ndownload_expiry_days'].",0)";
										
										mysql_query($insert_product_digital_code) or die(mysql_error());
																				
										$download_link .= MAIL_DOWNLOAD_LINK." - ".SITE_URL."/digital_product_download.php?download_code=$digital_product_code\r\n";
										
									}	
									
									//exit;
															
								}
								else
								{
									
									$select_digital_count = "SELECT ndigital_id FROM ".$tableprefix."digital_product WHERE ndigital_orderid = ".$orderid;
																											
									$result_digital_count = mysql_query($select_digital_count) or die(mysql_error());
									
									
							/*---------selecting the download try and download expiry date-----------*/
									
									$select_digital_product_details = "SELECT ndownload_try,ndownload_expiry 
													   				   FROM ".$tableprefix."digital_product WHERE ndigital_productid = ".$productid;
									$result_digital_product_details = mysql_query($select_digital_product_details) or die(mysql_error());
									
									$digital_product_details_row = mysql_fetch_assoc($result_digital_product_details);								   
																		
									$product_download_try = $digital_product_details_row["ndownload_try"];
									$download_expiry_date = $digital_product_details_row["ndownload_expiry"];
									
							/*---------selecting the download try and download expiry date-----------*/
									
								
									//for($i=1;$i<$row["quantity"];$i++)
									if(mysql_num_rows($result_digital_count) < $row["quantity"])
									{
									
							/*-------Calculating the download expiry days----------*/	
									
										$expiry_days = 	$product_digital_code_row['ndownload_expiry_days'];							  
									
										$valid_date_upto = date("Y-m-d H:s:m",mktime(date("H"),date("i"),date("s"),date("m"),date("d")+$expiry_days,date("Y")));
									
							/*-------Calculating the download expiry days----------*/	
									
									
										$insert_product_digital_code = "INSERT INTO ".$tableprefix."digital_product(vdigital_product_name,ndigital_productid,
																		ndigital_orderid,vdigital_product_code,ndownload_try,ndownload_count,ndownload_expiry,ndownload_status) 
																		VALUES('".$product_digital_code_row['vdigital_product_name']."',
																		".$row["product_id"].",
																		".$orderid.",
																		'".$digital_product_code."',
																		".$product_digital_code_row['ndownload_try'].",0,
																		'".$valid_date_upto."',0)";
										
										mysql_query($insert_product_digital_code) or die(mysql_error());
																				
										$download_link .= MAIL_DOWNLOAD_LINK." - ".SITE_URL."/digital_product_download.php?download_code=$digital_product_code\r\n";
										
									}	
								
								}
							
							}
							
							
						}		
												
				$product_download_details .= MAIL_ORDER_TEXT_PRODUCT_NAME." - $productname\r\n";
				$product_download_details .= MAIL_ORDER_TEXT_QUANTITY." - $quantity\r\n";
				$product_download_details .= MAIL_PRODUCT_DOWNLOAD_PRODUCT_DOWNLOAD_TRY." - $product_download_try ".MAIL_PRODUCT_DOWNLOAD_TIMES."\r\n";
				$product_download_details .= MAIL_PRODUCT_DOWNLOAD_EXPIRY_DATE." - $download_expiry_date\r\n";
				$product_download_details .= $download_link;
				$product_download_flag = 1;
				}
				
				
/*-----------------Digital Product Download Ends----------------*/												
				
				
				
				$sql = "INSERT INTO  " . $tableprefix . "order_details (
				order_id,
				product_id,
				product_name,
				product_code,
				product_price,
				product_quantity,
				product_discount,
				artist_id,
				item_status,
				artist_payment_status
				)VALUES(
				'".addslashes($orderid)."',
				'".addslashes($productid)."',
				'".addslashes($productname)."',
				'".addslashes($productcode)."',
				'".addslashes($productprice)."',
				'".addslashes($quantity)."',
				'".addslashes($productdiscount)."',
				'".addslashes($artistid)."',
				'1',
				'0'
				)";
				mysql_query($sql);
				$artists[$i] = $artistid;
				$i++;
				$sql = "";
				
/*--------Updating the order status to 'delivered' if the product purchased is gift coupon------------*/		
		
				if($gift_coupon_flag == 1)
				{ // if gift coupon start
				
					$update_order_details = "UPDATE ".$tableprefix."order_details 
											 SET item_status = 4 
											 WHERE order_id  = ".$orderid.
											 " AND product_id = ".$gift_coupon_product_id;
											 
					mysql_query($update_order_details) or die(mysql_error());								 
					
				} // if gift coupon end					
				
/*--------Updating the order status to 'delivered' if the product purchased is gift coupon------------*/						
				
/*--------Updating the order status to 'delivered' if the product purchased is digital product------------*/

			if($product_download_flag == 1)
			{

				$update_order_details = "UPDATE ".$tableprefix."order_details 
										 SET item_status = 4 
										 WHERE order_id  = ".$orderid.
										 " AND product_id = ".$digital_product_id;
																			 
				mysql_query($update_order_details) or die(mysql_error());
			

			}


/*--------Updating the order status to 'delivered' if the product purchased is digital product------------*/				
				
				
				
				
			} // end while product details
		//} // end if product details
			
						

		
				
		
		if($product_download_flag == 1)
		{ // start product download if
				
			 
			$_SESSION['SESS_digital_product'] = 1;
			
/*-----------------Digital Product Mail Sending Starts----------------*/
			
			
			//if($product_download_flag == 1)
			//{
			
				$select_user_email = "SELECT user_name,email FROM ".$tableprefix."users WHERE user_id = ".$_SESSION["sess_userid"];
				$result_user_email = mysql_query($select_user_email) or die(mysql_error());
				$user_email_row = mysql_fetch_assoc($result_user_email);
				$user_name = $user_email_row['user_name']; 
				$product_download_details .= MAIL_PRODUCT_DOWNLOAD_USER_NAME." - $user_name\r\n";
				$txtEmailDownload = $user_email_row['email'];
				$subjectDownload = MAIL_PRODUCT_DOWNLOAD_DETAILS;
				
				$headers  = "MIME-Version: 1.0" . "\r\n";
				$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
				$headers .= "From: ".SITE_EMAIL."<".SITE_EMAIL.">" . "\r\n";
				
/*-------Email Template reading function call------------*/

				$mailcontent_digital_product = readEmailTemplate('digital_product');
				
				$product_download_details .= "\n\n*-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*\r\n";
				$product_download_details .= "<font color='#FF0000'>".MAIL_PRODUCT_DOWNLOAD_NOTE."</font>";
				
				$mailcontent_digital_product = str_replace('[product_details]',$product_download_details,$mailcontent_digital_product);
				
				$mailcontent_digital_product = nl2br($mailcontent_digital_product);			
				
				$mail_send_details = "<html><head><link href='".SITE_URL."/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=".$logofolder."/".$logoimage." width='125' height='39'/></div></div><div>".$mailcontent_digital_product."</div></div><div align='left' class='clear_float'><img src=".$imagefolder."/clear.gif width=1 height=1/></div></div></div></center></body></html>";
							
				$mailsent = mail($txtEmailDownload,$subjectDownload,$mail_send_details,$headers);
			
			} // end product download if	
			
/*-----------------Digital Product Mail Sending Ends----------------*/
			
			
			/*update gift coupon details*/
			
			//$format_gift_products = substr($gift_coupon_products,0,strlen($gift_coupon_products)-1);
						
			/*$select_currency_code = "SELECT vcurrency_code,nexchange_price FROM ".$tableprefix."currency_master WHERE vactive = 'Y'";
			$result_currency_code = mysql_query($select_currency_code) or die(mysql_error());
			$currency_row = mysql_fetch_assoc($result_currency_code);*/
			//$currency_code = displayCurrencyType();
			//$exchange_price = $currency_row['nexchange_price'];
			
			$select_gift_products = "SELECT ngift_coupon_products,ngift_coupon_amount
									 FROM ".$tableprefix."giftcoupon_master 
									 WHERE vgift_coupon_code = ".GetSQLValueString(trim($_POST['gift_coupon_code']),"text");
			$result_gift_products = mysql_query($select_gift_products) or die(mysql_error());
			$gift_products_row = mysql_fetch_assoc($result_gift_products);				
			$gift_coupon_products .= $gift_products_row['ngift_coupon_products']; 
			
			/*$check_coupon_valid = "SELECT gcm.ngift_coupon_amount,cm.nexchange_price
						   		   FROM ".$tableprefix."giftcoupon_master gcm,".$tableprefix."currency_master cm 
						  		   WHERE gcm.vgift_currency = cm.vcurrency_code
						    		AND gcm.vgift_coupon_code = ".GetSQLValueString(trim($_POST['gift_coupon_code']),"text");
			$result_coupon_valid = mysql_query($check_coupon_valid) or die(mysql_error());
			
			$coupon_row = mysql_fetch_assoc($result_coupon_valid);*/
			
			//$gift_dollar_amount = ($coupon_row['ngift_coupon_amount']/$coupon_row['nexchange_price']);
						
			$currency_value = displayCurrencyType();
			
			$gift_amount_calc = ($_POST['cart_total'] / $currency_value[1]);
			
			$gift_amount_final = $gift_products_row['ngift_coupon_amount'] - $gift_amount_calc;
			
			$update_coupon_amount = "UPDATE ".$tableprefix."giftcoupon_master 
									SET ngift_coupon_amount = ".number_format($gift_amount_final,2 ,".","").",
									vgift_currency = 'USD',
									ngift_coupon_products = '".$gift_coupon_products."' 
									WHERE vgift_coupon_code = ".GetSQLValueString(trim($_POST['gift_coupon_code']),"text");
									
						
			mysql_query($update_coupon_amount) or die(mysql_error());	
			
			
		}
		

		$artists=array_values(array_unique($artists)) ;

		$billingaddress = MAIL_ORDER_TEXT_BILLING_ADDRESS."\n";
		$billingaddress .= "================\n";
		$billingaddress .= $_SESSION["sessBillingFirstName"]." ".$_SESSION["sessBillingLastName"]. "\n";
		$billingaddress .= $_SESSION["sessBillingAddress1"].", ".$_SESSION["sessBillingAddress2"]. "\n";
		$billingaddress .= $_SESSION["sessBillingCity"]. "\n";
		$billingaddress .= $_SESSION["sessBillingState"]. "\n";
		$billingaddress .= $_SESSION["sessBillingCountry"]. "\n";
		$billingaddress .= $_SESSION["sessBillingZIP"]. "\n";
		$billingaddress .= MAIL_ORDER_TEXT_PHONE." ". $_SESSION["sessBillingPhone"]. "\n";
		$billingaddress .= $_SESSION["sessBillingEmail"]. "\n\n";

		$shippingaddress = MAIL_ORDER_TEXT_SHIPPING_ADDRESS."\n";
		$shippingaddress .= "=================\n";
		$shippingaddress .= $_SESSION["sessShippingFirstName"]." ".$_SESSION["sessShippingLastName"]. "\n";
		$shippingaddress .= $_SESSION["sessShippingAddress1"].", ".$_SESSION["sessShippingAddress2"]. "\n";
		$shippingaddress .= $_SESSION["sessShippingCity"]. "\n";
		$shippingaddress .= $_SESSION["sessShippingState"]. "\n";
		$shippingaddress .= $_SESSION["sessShippingCountry"]. "\n";
		$shippingaddress .= $_SESSION["sessShippingZIP"]. "\n";
		$shippingaddress .= MAIL_ORDER_TEXT_PHONE." ". $_SESSION["sessShippingPhone"]. "\n";
		$shippingaddress .= $_SESSION["sessShippingEmail"]. "\n\n";

		/*-------Email Template reading function call------------*/

		$mailcontent_seller = readEmailTemplate('order_notification_seller');

		/*$mailstart = MAIL_ORDER_TEXT_DEAR." ".SITE_NAME." seller,\n\n\n";
		$mailstart .= "A new order has been placed for you through the ".SITE_NAME." Site.\n";
		$mailstart .= MAIL_ORDER_TEXT_THE_DETAILS_ARE_AS_FOLLOWS.".\n\n";*/

		$headers  = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
		$headers .= "From: ".SITE_EMAIL."<".SITE_EMAIL.">" . "\r\n";
		
		
		/*$mailend = "With regards,\n";
		$mailend .= "Adminstrator,  ".SITE_NAME."";*/
		
		$ordersubject  = MAIL_ORDER_SUBJECT." ".SITE_NAME.".";
		
		
		for($k=0;$k<count($artists) ; $k++)
		{ // start of for loop
			$sql = "SELECT c.*,p.product_price,p.product_name,p.product_code,p.product_artist_id,p.product_stock,p.reorder_level,p.discount,s.email FROM " . $tableprefix . "cart c INNER JOIN " . $tableprefix . "products p ON c.product_id = p.product_id
		 		INNER JOIN " . $tableprefix . "artists s ON s.artist_id = p.product_artist_id
				WHERE c.user_id = '".addslashes($_SESSION["sess_userid"])."' AND  p.product_artist_id = '".addslashes($artists[$k])."' ";
			$res = mysql_query($sql);
			if(mysql_num_rows($res) != 0)
			{ // start if 3
				$count=1;
				$artistid = "";
				$productlist= "";
				$productlist_fillstock="";
				while($row = mysql_fetch_array($res))
				{ // start while 3
					$productid = $row["product_id"];
					$quantity = $row["quantity"];
					
					/*product price is calculated based on currency type*/
					
					$get_convert_price = getSellerCurrency($row["product_id"]);
							 							 							 
					 if($get_convert_price != "")
					 {
						 $converted_price = ($row["product_price"]/$get_convert_price);
					 }
					 else
					 {
						$converted_price = $row["product_price"];
					 } 	 
				
					$productprice = number_format(($currency_attributes[1] * $converted_price),2,".","");
					
					//$productprice =  $row["product_price"];
										
					$productname =  $row["product_name"];
					$productcode =  $row["product_code"];
					$artistid = $row["product_artist_id"];
					$artistemail = $row["email"];
					$discount=$row['discount']."%";
					if($productlist == "")
					{ // product list start
						$productlist .= MAIL_PRODUCT_DOWNLOAD_LABEL_PRODUCTS."\n";
						$productlist .= "========\n";
					} // product list end
					$productlist .= $count."\n";
					$productlist .= MAIL_PRODUCT_DOWNLOAD_PRODUCT_ID.": ".$productid."\n";
					$productlist .= MAIL_ORDER_TEXT_PRODUCT_CODE.": ".$productcode."\n";
					$productlist .= MAIL_ORDER_TEXT_PRODUCT_NAME.": ".$productname."\n";
					$productlist .= MAIL_PRODUCT_DOWNLOAD_PRODUCT_PRICE.": ".$productprice."\n";
					$productlist .= MAIL_ORDER_TEXT_DISCOUNT.": ".$discount."\n";
					$productlist .= MAIL_ORDER_TEXT_QUANTITY.": ".$quantity."\n\n";
					//send mail to seller when stock less than stock reorder level
					$currentstock=$row["product_stock"];
					if($row["reorder_level"]>0 and $currentstock<=$row["reorder_level"])
					{ // reorder start
						    $mailcontent_fillstock = MAIL_STOCK_RE_ORDER_NOTE; // "Your stock has gone under the reorder level set by you";

							$productlist_fillstock .= "Product Id: ".$productid."\n";
							$productlist_fillstock .= MAIL_ORDER_TEXT_PRODUCT_CODE.": ".$productcode."\n";
							$productlist_fillstock .= MAIL_ORDER_TEXT_PRODUCT_NAME.": ".$productname."\n";
							$productlist_fillstock .= MAIL_PRODUCT_DOWNLOAD_PRODUCT_PRICE.": ".$productprice."\n";
							$productlist_fillstock .= MAIL_TEXT_STOCK." : ".$currentstock."\n\n";
					} // reorder end
					$count++;
				} // end while 3
			} // end if 3
			
			$mailcontent_details = $productlist;
			$mailcontent_details .= $billingaddress;
			
/*---------Shipping details not available if gift coupon/digital product is purchased---------*/			
			
			if($gift_coupon_flag != 1 && $product_download_flag != 1)			
			{ // start of gift & digital if
			
				$mailcontent_details .= $shippingaddress;
			
			} // end of gift & digital if
			
			$mailcontent_seller = str_replace('[order_details]',$mailcontent_details,$mailcontent_seller);
			
			$mailcontent_seller = nl2br($mailcontent_seller);			
			
			$mail_send_details = " <html><head><link href='".SITE_URL."/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=".$logofolder."/".$logoimage." width='125' height='39'/></div></div><div>".$mailcontent_seller."</div></div><div align='left' class='clear_float'><img src=".$imagefolder."/clear.gif width=1 height=1/></div></div><div align='center' class='copyright'>Powered by <a href='http://www.iscripts.com/multicart'  target='_blank'><font color='#F4700E'><b>iScripts Multicart</b></font></a>&nbsp;&nbsp;&copy; 2007 iScripts.com. All Rights Reserved </div><div align='left' class='clear_float'><img src='".SITE_URL."/images/clear_admin.gif' alt='' width='1' height='1' /></div></div></center></body></html>";
						
			$mailsent = mail($artistemail,$ordersubject,$mail_send_details,$headers);
			
			$mailcontent_reorder = "";
			
			if($productlist_fillstock !="")
			{ // start of product fill if
			
/*-------Email Template reading function call------------*/			

			   $mailcontent_reorder = readEmailTemplate('stock_reorder');
			   $mailcontent_reorder = str_replace('[product_details]',$productlist_fillstock,$mailcontent_reorder);
			   $mailcontent_reorder = nl2br($mailcontent_reorder);			
			   
			   $mail_send_details_reorder = "<html><head><link href='".SITE_URL."/style/template1-admin.css' rel='stylesheet' type='text/css'></head><body><center><div align='left' id='layout'><div align='left' class='header'><div align='left' class='logo'><img src=".$logofolder."/".$logoimage." width='125' height='39'/></div></div><div>".$mailcontent_reorder."</div></div><div align='left' class='clear_float'><img src=".$imagefolder."/clear.gif width=1 height=1/></div></div></div></center></body></html>";
			   
			   /*$mailcontent_fillstock = MAIL_ORDER_TEXT_DEAR." ".SITE_NAME." seller,\n";
			   $mailcontent_fillstock .= "The following product(s) has gone under the reorder level set by you.Please refill your stock\n";
			   $mailcontent_fillstock .= $productlist_fillstock;
			   $mailcontent_fillstock .= $mailend;
			   */
			   $ordersubject_fillstock = MAIL_STOCK_RE_ORDER_SUBJECT." ".SITE_NAME;
			   
			   $mailsent = mail($artistemail,$ordersubject_fillstock,$mail_send_details_reorder,$headers);
			   
/*-------Email Template reading function call------------*/

			} // end of product fill if
		} // end of for loop

		emptyCart($_SESSION["sess_userid"]);
		$_SESSION["sess_addresses_collected"] = false;
		$_SESSION["sess_stock_adjusted"] = false;
		
		$payment_completed = "true";
		
	//}
//}
	
					


}


/*display the active template*/

$active_template = displayTemplate();


include "includes/htmltop.php";

/* Top File Name */

include_once ("includes/".$active_template[0]);

?>
<script src="js/gift_coupon_payment_ajax.js"></script>
<script src="js/javascript_check_userside.js"></script>
<script>
function checkCouponPaymentForm()
{

  var form_name = new Array('gift_coupon_code');		
  var display_name = new Array('Coupon Code');
  var count = 1;	

  if(check_fieldsUser('frmGiftCouponPayment',form_name,display_name,count))	
  {
  
  	
	showListCheck(document.frmGiftCouponPayment.gift_coupon_code.value,document.frmGiftCouponPayment.cart_total.value);
	 
   
  }
  else
  {
  
  		return false;
  
  }
   
}

</script>
<div align="left" class="main_body">
			<!--mainbody area start -->
			
			<div align="left" id="body_left_area">
				<!--body left area start -->
		
				
				
			<!--categories area start -->
			
<?php

	include_once("includes/categorylist.php");

?>			
			
			<!--categories area end -->	
			
			<!--body left area end -->
				</div>



		<!--center content area start-->	
		
		<form name="frmGiftCouponPayment" method="post">
		
		
		<div align="left" id="item_details">
	
	
		<!--items display area start -->
	
		<div align="left" id="items_top_area">
				<img src="<?php echo $active_template[3]?>/top_title_left.gif" alt="" class="items_top_area_img" />
				<div align="left" id="items_top_area_ttl"><?php echo GIFT_COUPON_PAY_TEXT;?></div>
				<img src="<?php echo $active_template[3]?>/top_title_right.gif" alt="" class="items_top_area_img" />
		</div>
		
		<div class="text_information" align="center"><?php echo $paymenterror?></div>
		
		<div>
				
		<table width="100%" border="0" cellspacing="2" cellpadding="2">
	
		<tr>
			<td width="2%">&nbsp;</td>
			<td>
<?php
	
		if($payment_completed == "false")
		{
	
	?>	
		<table width="60%" border="0" cellspacing="2" cellpadding="2" align="center">
			<tr>
				<td width="31%" class="maintext"><?php echo TOTAL_AMT_TEXT;?></td>
	
	<?php
	
			 $currency_attributes_gift = displayCurrencyType();
			 //echo $currency_attributes_gift[0];
			 
			 $display_gift_total = number_format(($currency_attributes_gift[1] * getCartTotal($_SESSION["sess_userid"])),2,".","");
																															 
			 //$gift_cart_total =  number_format(($currency_attributes_gift[1] * getCartTotal($_SESSION["sess_userid"]),2,".",""));
			
	
	?>
																																									
										<td>
<?php 
					
					echo $currency_attributes_gift[0];
					echo "&nbsp;";
					echo $display_gift_total;
?>
										</td>
									</tr>
<?php

		$check_shipping_enable = checkShippingEnable();
		
				
		if($check_shipping_enable == "Y" && $hide_shipping_division == 1)
		{
		 
			$shipping_cost = $currency_attributes_gift[1] * $_SESSION['SESS_upscost'];
?>		
			
		<tr>
			<td align="" valign="" class="maintext"><?php echo SHIPPING_COST_TEXT;?></td>
			<td width="69%">
<?php 				
					echo $currency_attributes_gift[0];
					echo "&nbsp;";
					echo $shipping_cost
?>
										</td>
									</tr>
									<tr>
										<td align="" valign="" class="maintext"><?php echo GRAND_TOTAL_TEXT;?></td>
										<td width="69%">
<?php 				
					echo $currency_attributes_gift[0];
					echo "&nbsp;";
					echo $display_gift_total + $shipping_cost;
?>
										</td><input type="hidden" name="cart_total" value="<?php echo $display_gift_total + $shipping_cost;?>">
									</tr>
									
<?php

		}
		else
		{

?>			
		
			<input type="hidden" name="cart_total" value="<?php echo $display_gift_total;?>">
		
<?php

		}

?>				  			
						
									<tr>
										<td align="" valign="" class="maintext"><?php echo GIFT_COUPON_CODE_TEXT;?></td>
										<td width="69%"><input type="text" name="gift_coupon_code"></td>
									</tr>
									<tr>
										<td colspan="2"><span class="required">*</span>&nbsp;<?php echo ENTER_CODE_TEXT;?> </td>
									</tr>
									<tr>
										<td colspan="2" align="center">
											<input type="button" name="btnGift" value="&nbsp;&nbsp;&nbsp;&nbsp;<?php echo PAY_TEXT;?>&nbsp;&nbsp;&nbsp;&nbsp;" class="button" onClick="return checkCouponPaymentForm();">
											<input type="button" name="back" value="<?php echo PAYMENT_OPTIONS_TEXT;?>" class="button" onClick="window.location='paymentoptions.php'">	
										</td>
									</tr>
								</table>
								
<?php
	}

	if($payment_completed == "true")
	{
		if($check_shipping_enable == "Y")
		{
                    if(function_exists('session_unregister')){
			session_unregister('SESS_upstype');
			session_unregister('SESS_upscost');
			session_unregister('SESS_upsweight');
                    }else{
                        
                                unset($_SESSION['SESS_upstype']);
				unset($_SESSION['SHIPPING_TOTAL']);
				unset($_SESSION['SESS_upsweight']);
                    }
		}	

?>	
		<table width="60%" border="0" cellspacing="2" cellpadding="2" align="center">
			<tr>
				<td class="text_information" colspan="2" align="center"><?php echo ORDER_PLACED_SUCCESS_TEXT;?></td>
			</tr>
<?php

if(isset($_SESSION['SESS_digital_product']))
{
?>		
			<tr>
				<td colspan="3" align="center" class="text_information">
						<?php echo PRODUCT_LINK_MAIL_TEXT;?>
				</td>
			</tr>
<?php

}

?>							
			<tr>
				<td>&nbsp;</td>
			</tr>
			<tr>
				<td align="center">
					<input type='button' value='<?php echo HOME_LINK;?>'  class='button' onClick="window.location.href='index.php'">
					&nbsp;&nbsp;<input type='button' value='<?php echo CONTINUE_SHOPPING_BUTTON;?>'  class='button' onClick="window.location.href='categorydetail.php'">
				</td>
			</tr>
		</table>
<?php
	
	}

?>	
				
				
								</td>
							</tr>
						</table>
					  
					
				
				
			</td>
		</tr>
	</table>
	
		</div>	
	
	
		<div align="left" class="float_clear1"></div>
					
					
		 <!--items display area end -->
		  </div>
		
			</form>
		<!--center content area end-->	


		<div align="left" class="clear"></div>		
		<!--mainbody area end -->
        </div>
		<div align="left" class="clear"></div>




				

<?php
include "includes/".$active_template[2];	/* Bottom File Name */
?>





