<?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.                                                       |
// +----------------------------------------------------------------------+
include "includes/config.php";
include "includes/session.php";
include "includes/functions.php";

$sql = "SELECT * FROM ".$tableprefix."settings ";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$txtPaypalEmail = $row["paypalemail"];
$txtPaypalSandbox = $row["enablepaypalsandbox"];

					$row_paypal = mysql_fetch_assoc(mysql_query("SELECT enable_buyerToseller FROM ".$tableprefix."settings "));
					
					if($row_paypal["enable_buyerToseller"]=="Y"){
					  //  $txtPaypalEmail = "";
						//$auth_token     = "";
						if($_SESSION['SESS_ARTISTID']!='')
 						 {	
							$row_art = mysql_fetch_assoc(mysql_query("SELECT  paypalemail,paypalidentitytoken ,enablepaypalsandbox FROM ".$tableprefix."artists WHERE artist_id=".$_SESSION['SESS_ARTISTID']));
							$txtPaypalEmail=$row_art['paypalemail'];
							$auth_token = $row_art["paypalidentitytoken"];
							$txtPaypalSandbox = $row_art["enablepaypalsandbox"];
						}
						
					}
					

$gift_coupon_flag = 0;
$paypal_check = 0;

if($txtPaypalSandbox == "Y"){

	$paypalurl = "www.sandbox.paypal.com";

}else{

	$paypalurl = "www.paypal.com";

}

/** check paypal****************/
                    $sql = "SELECT * FROM ".$tableprefix."settings ";
					$res = mysql_query($sql);
					$row = mysql_fetch_array($res);
					$auth_token = $row["paypalidentitytoken"];

$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) 
{
	$value = urlencode(stripslashes($value));
	$req .= "&$key=$value";
}//end foreach

$lines = explode("&", $req);
$keyarray = array();

$cc_flag=false;

// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ($paypalurl, 80, $errno, $errstr, 30);

if (!$fp) 
{
	// HTTP ERROR
}//end if
else 
{
	fputs ($fp, $header . $req);
	while (!feof($fp)) 
	{
		$res = fgets ($fp, 1024);
		if (strcmp ($res, "VERIFIED") == 0) 
		{
			// check the payment_status is Completed
			// check that txn_id has not been previously processed
			// check that receiver_email is your Primary PayPal email
			// check that payment_amount/payment_currency are correct
			// process payment
			$cc_flag=true;

			for ($i=1; $i<count($lines);$i++)
			{
				list($key,$val) = explode("=", $lines[$i]);
				$keyarray[urldecode($key)] = urldecode($val);
				//echo("key : " . urldecode($key) . "   value : " . urldecode($val) . "<br>");
			}//end for loop
		}//end if
		else if (strcmp ($res, "INVALID") == 0) 
		{
			// log for manual investigation
		}//end else if
	}//end while loop
	fclose ($fp);
}//end else

//filter custom value
$CustomArray=@split('-',$keyarray['custom']);

function displayCurrencyTypeNew($type)
{
		global $tableprefix;
	
		$currency_array = array();
		
	if(isset($type) or $type != "")
	{
	
		$select_currency_type = "SELECT vcurrency_symbol,nexchange_price,vcurrency_code FROM ".$tableprefix."currency_master 
								 WHERE ncurrency_id = ".$type;
	
	}
	else
	{
	
		$select_currency_type = "SELECT vcurrency_symbol,nexchange_price,vcurrency_code FROM ".$tableprefix."currency_master 
								 WHERE vactive = 'Y'";
	
	}

	
	$result_currency_type = mysql_query($select_currency_type) or die(mysql_error());
	
	$currency_row = mysql_fetch_assoc($result_currency_type);
	$currencySymbol=$currency_row['vcurrency_symbol'];
	
	array_push($currency_array,$currency_row['vcurrency_symbol'],$currency_row['nexchange_price'],$currency_row['vcurrency_code']);
	
	return $currency_array; 
}//end function

function hideShippingNew($uid)
{
	global $tableprefix;
	
	$hide_shipping_division = 0;

	$select_cart_digital = "SELECT ct.cart_id FROM ".$tableprefix."cart ct,".$tableprefix."products prd
							WHERE ct.product_id = prd.product_id
						 	AND vdigital_product = 'Y'
						 	AND ct.user_id = ".$uid;
								 
	$result_cart_digital = mysql_query($select_cart_digital) or die(mysql_error());		
									 
	$select_cart_gift = "SELECT ct.cart_id FROM ".$tableprefix."cart ct,".$tableprefix."products prd,".$tableprefix."categories ctry
						  WHERE ct.product_id = prd.product_id
						   AND prd.product_category = ctry.category_id 
						   AND ctry.gift_certificate_flag = 'Y'
						   AND ct.user_id = ".$uid;		
						   
	$result_cart_gift = mysql_query($select_cart_gift) or die(mysql_error());
	
	if(mysql_num_rows($result_cart_digital) == 0 && mysql_num_rows($result_cart_gift) == 0)
	{
	
		$hide_shipping_division = 1;
	
	}

	return $hide_shipping_division;
}//end function

/*******************************/
$currency_attributes = displayCurrencyTypeNew($CustomArray[16]);

/*-------function call to check whether cart contains digital or gift coupon products so as to hide shipping---*/

$hide_shipping_division = hideShippingNew($CustomArray[0]);

/*-------function call to check whether cart contains digital or gift coupon products so as to hide shipping------*/


$check_shipping_enable = checkShippingEnable();

$shipping_cost=$keyarray['shipping'];
$totaltopay=$keyarray['payment_gross'];

$totaltaxrate=number_format($keyarray['tax'],2,".","");
//shipping cost
$shipping_cost=number_format($shipping_cost,2,".","");


if(isset($CustomArray[17]))
{
	$nameCouponCode=",couponCode,couponCodeDiscount";
	$valueCouponCode=',"'.$CustomArray[17]['ccCode'].'",'.$CustomArray[17]['ccDiscount'];	
	$sql_updatecouponCode="UPDATE  " .$tableprefix. "couponCode SET subscriptionStatus='N' WHERE ccID =".$CustomArray[17]['ccID'];
	mysql_query($sql_updatecouponCode);
	unset($CustomArray[17]);
}//end if

if(trim($keyarray['txn_id'])!='' && $keyarray['txn_type'] == "web_accept")
{
	$var_id=$keyarray['option_selection1'];
	$in_login_name=$keyarray['option_selection2'];
	$txnid=$keyarray['txn_id'];
	$var_txnid=$txnid;
	$paypal_check=0;

	if($paypal_check==0)
	{ // check if paypal is success
				$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,
					taxrate,
					order_status,
					transaction_id,
					vorder_currency".$nameCouponCode."
					) VALUES(
					'".addslashes($CustomArray[0])."',
					'".addslashes($keyarray['first_name'])."',
					'".addslashes($keyarray['last_name'])."',
					'".addslashes($keyarray['address_street'])."',
					'".addslashes($keyarray['address_name'])."',
					'".addslashes($keyarray['address_city'])."',
					'".addslashes($keyarray['address_state'])."',
					'".addslashes($keyarray['address_country'])."',
					'".addslashes($keyarray['address_zip'])."',
					'".addslashes($CustomArray[1])."',
					'".addslashes($CustomArray[2])."',
					'".addslashes($CustomArray[3])."',
					'".addslashes($CustomArray[4])."',
					'".addslashes($CustomArray[5])."',
					'".addslashes($CustomArray[6])."',
					'".addslashes($CustomArray[7])."',
					'".addslashes($CustomArray[8])."',
					'".addslashes($CustomArray[9])."',
					'".addslashes($CustomArray[10])."',
					'".addslashes($CustomArray[11])."',
					'".addslashes($CustomArray[12])."',
					'".addslashes($CustomArray[13])."',
					'".addslashes($CustomArray[14])."',
					'".addslashes($CustomArray[15])."',
					now(),
					'".addslashes($totaltopay)."',
					'".addslashes($totaltaxrate)."',
					'1',
					'".addslashes($txnid)."'
					'".$currency_attributes[2]."'".$valueCouponCode."
					)";
					
			 mysql_query($sql);
			 $orderid = mysql_insert_id();
			 
			   // Store Coupon Code Details to Order Table // Modified By Asha ON 21-02-2011
		 if($CustomArray[17]['ccDiscount']!='')
		 {
		 	// Update Order with Coupon Code Discount
			$sql_coupon_update="UPDATE " .$tableprefix. "orders SET  couponCodeDiscount ='".$CustomArray[17]['ccDiscount']."', couponCode ='".$CustomArray[17]['ccCode']."' where order_id='".$orderid."' ";
			$rs_update_c=mysql_query($sql_coupon_update) or die(mysql_error());
			// End Update
		 }
		// End Coupon Code Modification
		
		
			$check_shipping_enable = checkShippingEnable();
	
			if($check_shipping_enable == "Y" && $hide_shipping_division == 1)
			{
			
	/*---------------update the shipping details----------------*/
			
				$select_cart_products = "SELECT product_id FROM ".$tableprefix."cart 
										 WHERE user_id = ".$CustomArray[0];
								 
				$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' AND user_id='".addslashes($CustomArray[0])."' ";
						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($CustomArray[0])."'";
			   $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($CustomArray[0])."'";
												 $result3 = mysql_query($sql3);
	
			   } // end if Affiliate Registraion
	
	/************************** Affilate payment block*********************************************/
			//echo "sql==".$sql."<br><br>";
			
			$product_download_details = "Product Download Details\r\n";
			$product_download_details .= "-----------------------\r\n";
			$product_download_flag = 0;
			$download_link = "";			
	
			$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($CustomArray[0])."' ";
			$res = mysql_query($sql);
			$artists = array();
			if(mysql_num_rows($res) != 0)
			{
				$i=0;
				while($row = mysql_fetch_array($res))
				{
					$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"];
					$productdiscount = $row["discount"];
					$artistid = $row["product_artist_id"];
					
	/*========================================Gift Certificate Section=================================*/					
$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();
						
						 $insert_coupon_code = "INSERT INTO ".$tableprefix."giftcertificates(vgift_coupon_code,ngift_product_id,
															ngift_order_id,ngift_coupon_amount)
															VALUES('".$gift_coupon_code."',
															".$row["product_id"].",
															".$orderid.",
															".$productprice.")";
							
						mysql_query($insert_coupon_code) or die(mysql_error());
				}		
			
			$gift_coupon_flag = 1;
																				
		} // end of mysql number of rows check 
		
		
		//=======================End Gift Certificate Section ===================================
			
	/*--------------------------------------Check Digital Products*/
	
	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'] == "")
							{
									$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 .= "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 .= "Download Link - ".SITE_URL."/digital_product_download.php?download_code=$digital_product_code\r\n";
										}	// end for loop 
										//exit;
									} // end if  digital product code check 
									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 .= "Download Link - ".SITE_URL."/digital_product_download.php?download_code=$digital_product_code\r\n";
											
										}	 // end if mysqlnum rows check 
									
									} // end else 
								
								} // end ehile 
								
								
							} // emd if number of rows check 
													
					$product_download_details .= "Product Name - $productname\r\n";
					$product_download_details .= "Quantity - $quantity\r\n";
					$product_download_details .= "Product Download Try - $product_download_try Time(s)\r\n";
					$product_download_details .= "Download Expiry Date - $download_expiry_date\r\n";
					$product_download_details .= $download_link;
					$product_download_flag = 1;
			} // end digital product check 
					
	/*----------------------------------End check Digital Products--------------------------------------------------
	/*----------------------------------Updating Gift Products----------------------------------------------------------*/							
					
					 $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);
					//echo "sql==".$sql."<br><br>";
					$artists[$i] = $artistid;
					$i++;
					$sql = "";
				} // end while 
			} // end number of rows 
			
	} // end if pay pal success check 
	
	if($paypal_check == 0)
	 {
	/*--------Updating the order status to 'delivered' if the product purchased is gift coupon------------*/		
			if($gift_coupon_flag == 1)
			{
			
				$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());								 
				
			}	// end if gift flag 
	/*--------Updating the order status to 'delivered' if the product purchased is digital product------------*/			
	}
	
	if($paypal_check == 0)
	{
	/*------------Checking whether the amount sent to paypal is equal to amount paid----------*/			
			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------------*/			
	}
	
	
if($paypal_check == 0)
 {
$current_date=date('Y-m-d');
	
	if($row_paypal["enable_buyerToseller"]=="Y")
	{
		$second_seller = false;
		if($_SESSION['SESS_ARTISTID']!=''){
			   ///////// Insert in to artists payments.......
			   $sqlpayment = "INSERT INTO " . $tableprefix . "artist_payments (artist_id,order_id,commission_percentage,total_amount,amount_paid,date_marked_for_payment,payment_date,payment_status)
							  VALUES ('".addslashes($artistid)."','".addslashes($orderid)."','0','".addslashes($totaltopay)."','".addslashes($totaltopay)."','".addslashes($current_date)."','".addslashes($current_date)."','C') ";
			   mysql_query($sqlpayment);
			   $paymentid  = mysql_insert_id();
			   $sql        = "UPDATE " . $tableprefix . "order_details SET artist_payment_status = '3', artist_payment_id = '".addslashes($paymentid)."' WHERE order_id  = '".addslashes($orderid)."' AND artist_id = '".addslashes($artistid)."'  ";
				mysql_query($sql);
		}
	
	}
	
 }
	if($paypal_check == 0)
	{
	
		
/*-----------------Digital Product Mail Sending Starts----------------*/
		if($product_download_flag == 1)
		{
                         if (function_exists('session_unregister')){
                            (isset($_SESSION['SESS_digital_product']))?session_unregister('SESS_digital_product'):session_register('SESS_digital_product');
                         }
                         else{
                             unset($_SESSION['SESS_digital_product']);
                         }
			$_SESSION['SESS_digital_product'] = 1;
			$select_user_email = "SELECT user_name,email FROM ".$tableprefix."users WHERE user_id = ".$CustomArray[0];
			$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 .= "User Name - $user_name\r\n\n";
			
			$txtEmailDownload = $user_email_row['email'];
			$subjectDownload = "Digital Product Order placed at ".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";
/*-------Email Template reading function call------------*/
			$mailcontent_digital_product = readEmailTemplate('digital_product');
			
			$product_download_details .= "\n\n*-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*\r\n";
			$product_download_details .= "<font color='#FF0000'>Note: If you do not have pop-ups enabled on your browser, the product download many not work properly.So please enable pop-ups before downloading !!</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);
		}	
/*-----------------Digital Product Mail Sending Ends----------------*/

		// Send Giftcertificate Mails 
		if($gift_coupon_flag == 1)
		{
			sendgiftCertificateMail_Buyer($orderid,$CustomArray[0]);
		}
		
		else
		{
			sendBuyerEmail($orderid,$CustomArray[0]);
			sendSellerEmail($orderid,$CustomArray[0]);
			sendAdminEmail($orderid,$CustomArray[0]);
			
		}
		
		//Send Mail To Buyer 
	

	} // end if paypal check 
}//end ipn check if
		emptyCart($CustomArray[0]);
		$_SESSION["sess_addresses_collected"] = false;
		$_SESSION["sess_stock_adjusted"] = false;
?>