<?php
include_once 'includes/parallel-paypal.php';

if(isset($_SESSION["sess_userid"]) and $_SESSION["sess_userid"]!= ""){
	$userid = $_SESSION["sess_userid"];
}
else
{
	header ("location:viewcart.php");
	exit;
}


$message	 = '';

$msg_error	='';

if(isset($_SESSION["sess_guest_username"]) && $_SESSION["sess_guest_username"]!='')
{
	$usertype='guest';
}
else
{
	$usertype='user';
}

$currency_attributes= displayCurrencyType();

$seller_total_price = 0;

$total_admin_commission    = 0;

$seller_total_price_after_commission =0;

$receiverAmountArray=array();
$receiverEmailArray=array();
$receiverInvoiceIdArray=array();

$adminPaypalemail   = getSettingsValue("paypalemail");


/*--------------------------Select Max of  Order Id  from  Database --------------*/

$qry1="select max(order_id)+1  as Inv_id  from " .$tableprefix. "orders";

 $excqry1=mysql_query($qry1);

 $row1=mysql_fetch_array($excqry1);

 if($row1['Inv_id']!=''){

    $Inv_id     = $row1['Inv_id'];
}
else {

     $Inv_id     = 1;
}

 

  // Delete records from payment if record exists


    $sql_pay = "Select * FROM ".$tableprefix."artist_payments where order_id ='".$Inv_id."' ";

    $rs_pay =mysql_query($sql_pay) or die(mysql_error());

    if(mysql_num_rows($rs_pay)>0){

        $sql_del = "DELETE  FROM ".$tableprefix."artist_payments where order_id ='".$Inv_id."' ";

        $rs_del =mysql_query($sql_del) or die(mysql_error());


    }



 
/*----------------------------------------------------------------------------------*/
              

$sql = "SELECT distinct p.product_artist_id,a.paypalemail,a.commission
                FROM " . $tableprefix . "cart c INNER JOIN " . $tableprefix . "products p ON c.product_id = p.product_id
                INNER JOIN ".$tableprefix."artists a ON a.artist_id=p.product_artist_id
                WHERE c.user_id = '".addslashes($_SESSION["sess_userid"])."' ";
$res = mysql_query($sql) or die(mysql_error());


while($rsObj=mysql_fetch_object($res))
{
    
 $select_cart_details  = "SELECT c.*, p.product_name,(p.product_price+po.additional_price) AS product_price,po.discount,p.product_artist_id
					FROM ".$tableprefix."cart c
                                        INNER JOIN ".$tableprefix."product_options po ON po.product_option_id = c.product_option_id
                                        INNER JOIN ".$tableprefix."products p ON p.product_id = po.product_id
					WHERE c.user_id = '".addslashes($_SESSION["sess_userid"])."' AND p.product_artist_id ='".$rsObj->product_artist_id."' ";

$result_cart_details = mysql_query($select_cart_details) or die(mysql_error());

$product_price      =0;
$product_rate       = 0;

$product_tax        = 0;

$product_shipping_cost  = 0;

$total_tax_rate         = 0;

$total_shipping_cost    =  0;

$product_admin_commission  =0;

$itemTotal =0;
  
while($rw = mysql_fetch_array($result_cart_details))
	{
                    
				 $product_rate      =    $rw['product_price'];
				/*------------Multicart 2.0 Upgradation------------*/
                                $product_option_id =    $rw["product_option_id"];
                                
				$qty               =    $rw["quantity"];
                                
				$product_price     = $qty * $product_rate;

				if($rw["discount"] !=0){

				$discountprice                  = $product_rate-($product_rate*$rw["discount"])/100;
				$discountrate                   = ($discountprice*$qty);
				$product_price                  = $discountrate;

				}
                          
                               $itemTotal+=$product_price;

                               if(!empty($_SESSION["TAX_DETAILS"])) {

                               $product_tax+=$_SESSION["TAX_DETAILS"][$product_option_id];

                               }


                               if(!empty($_SESSION["SHIPPING_DETAILS"])) {
                                    $product_shipping_cost += $_SESSION["SHIPPING_DETAILS"][$product_option_id]['rate'];
                               }

            }

                            // Seller Product Total including tax, shipping


                               $seller_total_price = round($itemTotal +$product_tax +$product_shipping_cost,2);

                             if($_SESSION['sess_giftcertificate_code'] != '' &&  $_SESSION['sess_gift_amount_used'] !='')
                            {
                                           if($seller_total_price>$_SESSION['sess_gift_amount_used'])
                                               {

                                                    $seller_total_price = $seller_total_price-$_SESSION['sess_gift_amount_used'];
                                             }
                            }
                   
                               $product_admin_commission = ($itemTotal * ($rsObj->commission/100));

                               // Seller Total Amount after Commission Amount
                               
                               $seller_total_price_after_commission = $seller_total_price - $product_admin_commission;

                               // Admin Commission Total 
                               $total_admin_commission += $product_admin_commission;


                               // Update Seller Payment Table

                               $current_date=date("Y-m-d");
				// Insert To Artist Payment Table

                               

				$sql_payment= "INSERT INTO ".$tableprefix."artist_payments (artist_id,order_id,total_amount,amount_paid,payment_method,date_marked_for_payment,payment_date,payment_status,commission_percentage,seller_order_total_amount,admin_commision_amount)
									 VALUES('".$rsObj->product_artist_id."','".$Inv_id."','".$itemTotal."','".$seller_total_price_after_commission."','PAYPAL','".$current_date."','".$current_date."','P','".$rsObj->commission."','".$seller_total_price."','".$product_admin_commission."') ";
				mysql_query($sql_payment);

				$paymentid  = mysql_insert_id();
				$sql        = "UPDATE " . $tableprefix . "order_details SET artist_payment_status = '3', artist_payment_id = '".addslashes($paymentid)."' WHERE order_id  = '".addslashes($Inv_id)."' AND artist_id = '".addslashes($rsObj->product_artist_id)."'  ";
				mysql_query($sql);


                                // End 
            
            
            $receiverAmountArray[]    =    number_format(round($seller_total_price_after_commission,2),2,".","");

            $receiverEmailArray[]    =    stripslashes($rsObj->paypalemail);

            $receiverInvoiceIdArray[] =    time().session_id()."-".$rsObj->product_artist_id;

}


if($adminPaypalemail!='' && $product_admin_commission!=0)
    {
        array_push($receiverEmailArray,$adminPaypalemail);
 }


if (count(array_unique($receiverEmailArray)) < count($receiverEmailArray))  
{
	//$msg_error = "The receivers ".implode(" , ",$receiverEmailArray)." can't belong to the same PayPal account.";
        $msg_error = PP_PAY_RECEIVER_EMAIL_TEXT;
	$msg_error = str_replace("{EMAIL_ARRAY}", implode(" , ",$receiverEmailArray), $msg_error);
}
//print_r($receiverEmailArray);
if($total_admin_commission!=0)
    {
       $total_admin_commission   = number_format(round($total_admin_commission,2),2,".","");
      
       array_push($receiverAmountArray,$total_admin_commission);
}


// Digital, Gift Products Cart Count

      $digital_product_count    = digitalProductsCartCount($userid);
      
      $gift_product_count      = giftProductsCartCount($userid);


    
      
//

// Parallel Payemt Code Starts Here

$actionType            = "PAY";

$cancelUrl            = SITE_URL."/failure.php";    // TODO - If you are not executing the Pay call for a preapproval,
                                                //        then you must set a valid cancelUrl for the web approval flow
                                                //        that immediately follows this Pay call
$returnUrl            = SITE_URL."/parallel_pay_success.php";    // TODO - If you are not executing the Pay call for a preapproval,
                                                //        then you must set a valid returnUrl for the web approval flow
                                                //        that immediately follows this Pay call
$currencyCode        = getSettingsValue("admin_currency");

// for parallel payment, no primary indicators are needed, so set empty array
$receiverPrimaryArray = array();



//   Provide a value for each field that you want to include in the request, if left as an empty string the field will not be passed in the request
//$senderEmail                    = "buyer_1297270922_per@yahoo.com";        // TODO - If you are executing the Pay call against a preapprovalKey, you should set senderEmail

$senderEmail                    = "";
$feesPayer                        = "";

$ipnNotificationUrl                = SITE_URL."/paypal-parallel-ipn.php?orderid=".$Inv_id."&userid=".$_SESSION["sess_userid"]."&usertype=".$usertype."&giftflag=".$gift_product_count."&guestpassword=".$_SESSION["sess_guest_password"]."&digitalflag=".$digital_product_count;

//$memo                            = "Item Purchase with ".SITE_NAME;    // maxlength is 1000 characters

$memo                            = MSG_ITEM_PURCHASED_WITH_SITENAME;
$memo                            = str_replace("{SITE_NAME}", SITE_NAME, $memo);

$pin                            = "";        // TODO - If you are executing the Pay call against an existing preapproval
                                            //        the requires a pin, then you must set this
//$preapprovalKey                    = "PA-48386465L40680121";        // TODO - If you are executing the Pay call against an existing preapproval, set the preapprovalKey here
$preapprovalKey                        = "";
$reverseAllParallelPaymentsOnError    = "";    // TODO - Set this to "true" if you would like each parallel payment to be reversed if an error occurs
                                            //        defaults to "false" if you don't specify
$trackingId                        = generateTrackingID();    // generateTrackingID function is found in paypalplatform.php

//-------------------------------------------------
// Make the Pay API call
//
// The CallPay function is defined in the paypalplatform.php file,
// which is included at the top of this file.
//-------------------------------------------------

$resArray = CallPay ($actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray,
                        $receiverAmountArray, $receiverPrimaryArray, $receiverInvoiceIdArray,
                        $feesPayer, $ipnNotificationUrl, $memo, $pin, $preapprovalKey,
                        $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId
);

$ack = strtoupper($resArray["responseEnvelope.ack"]);

$payment_completed = false;

// Update Order Table 
if($ack=="SUCCESS" && $msg_error=='')
    {

        $totaltopay=getCartTotal($userid);

        $totaltopay = number_format($totaltopay,2,".","");
        $hide_shipping_division = hideShipping();

        $check_shipping_enable = checkShippingEnable();

        if($check_shipping_enable == "Y" && $hide_shipping_division == 1)
        {

                $shipping_cost = $_SESSION['SHIPPING_TOTAL'];
                $shipping_cost=number_format($shipping_cost,2,".","");

                $totaltopay = $totaltopay + $shipping_cost;

                $totaltopay=number_format($totaltopay,2,".","");

        }


        $totaltaxrate=number_format($_SESSION["TAX_TOTAL"],2,".","");

        if(isset($_SESSION['couponCode_det'])&& $_SESSION['couponCode_det']!='' ){
	$nameCouponCode=",couponCode,couponCodeDiscount";
	$valueCouponCode=',"'.$_SESSION['couponCode_det']['ccCode'].'",'.$_SESSION['couponCode_det']['ccDiscount'];
	$sql_updatecouponCode="UPDATE  " .$tableprefix. "couponCode SET subscriptionStatus='N' WHERE ccID =".$_SESSION['couponCode_det']['ccID'];
	mysql_query($sql_updatecouponCode);
	unset($_SESSION['couponCode_det']);
    }



        $amountpaid	= number_format($_SESSION['amount_paid'],2,".","");

		 $sql = "INSERT INTO  " .$tableprefix. "orders (
                                order_id,
				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.",
				namount_paid,
                                vpayment_status,
                                buyer_comments
				) VALUES(
                                '".$Inv_id."',
				'".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["sessShippingDisplayName"])."',
				now(),
				'".addslashes($totaltopay)."',
				'".addslashes($totaltaxrate)."',
				'1',
				'".addslashes($tx_token)."',
				'".$currency_attributes[2]."'".$valueCouponCode.",
				'".addslashes($amountpaid)."',
                                'P',
                                '".addslashes($_SESSION["SESS_BUYER_COMMENTS"])."'
				)";
		 mysql_query($sql);
		 $orderid = mysql_insert_id();

		 // Updating Buying Process using Gift Certificate Code

		if($_SESSION['sess_giftcertificate_code'] != '' &&  $_SESSION['sess_gift_amount_used'] !='')
		{
			$sql_up		="UPDATE " .$tableprefix. "orders SET vgiftcertificate_code='".addslashes($_SESSION['sess_giftcertificate_code'])."',
						nused_gift_amount=(nused_gift_amount + ".$_SESSION['sess_gift_amount_used']." )WHERE order_id='".$orderid."' ";
			$rs_up		=mysql_query($sql_up) or die(mysql_error());

			$sql_gift	="UPDATE " .$tableprefix. "giftcertificates SET nused_gift_amount=(nused_gift_amount + ".$_SESSION['sess_gift_amount_used']." )
							WHERE vgift_coupon_code ='".addslashes($_SESSION['sess_giftcertificate_code'])."' ";
			$rs_gift	=mysql_query($sql_gift) or die(mysql_error());

		}

		// End Gift Certificate Updation

		  // Store Coupon Code Details to Order Table // Modified By Asha ON 21-02-2011
		 if($_SESSION['couponCode_det']!='')
		 {
		 	// Update Order with Coupon Code Discount
			$sql_coupon_update="UPDATE " .$tableprefix. "orders SET  couponCodeDiscount ='".$_SESSION['couponCode_det']['ccDiscount']."', couponCode ='".$_SESSION['couponCode_det']['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)
		{

/*---------------inserting the shipping details----------------*/

			$select_cart_products = "SELECT c.product_option_id,c.product_id,p.product_name,po.product_shipping_weight FROM ".$tableprefix."cart c
                                                    INNER JOIN ".$tableprefix."product_options po ON po.product_option_id = c.product_option_id
                                                    INNER JOIN ".$tableprefix."products p ON p.product_id = po.product_id
                                                    WHERE c.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_obj = mysql_fetch_object($result_cart_products))
				{

                                        if(isset($_SESSION["SHIPPING_DETAILS"][$cart_obj->product_option_id]['preffered_shipping'])) {
                                           $product_name = $cart_obj->product_name;
                                           $optionVal = getProductOptionsName($cart_obj->product_option_id);
                                           $shipping_name = $_SESSION["SHIPPING_DETAILS"][$cart_obj->product_option_id]['preffered_shipping'];
                                           $shipping_cost = $_SESSION["SHIPPING_DETAILS"][$cart_obj->product_option_id]['rate'];
                                           $product_shipping_weight = $cart_obj->product_shipping_weight;
                                           $ship_product_option_id  = $cart_obj->product_option_id;
                                           $product_name .= $optionVal;
                                           $insert_shipping = "INSERT INTO ".$tableprefix."shipping_details
                                                                 (
                                                                 norder_id,
                                                                 vshipping_currency,
                                                                 dshipped_date,
                                                                 nshp_status,
                                                                 user_id,
                                                                 nshp_productid,
                                                                 nproduct_option_id,
                                                                 nshp_productname,
                                                                 vshipping_name,
                                                                 nshipping_cost,
                                                                 nshipping_weight
                                                                 )
                                                                 VALUES
                                                                 (
                                                                 ".$orderid.",
                                                                 '".$currency_attributes[2]."',
                                                                 now(),
                                                                 'C',
                                                                 '".addslashes($_SESSION["sess_userid"])."',
                                                                 ".$cart_obj->product_id.",
                                                                 ".$ship_product_option_id.",
                                                                 '".addslashes($product_name)."',
                                                                 '".addslashes($shipping_name)."',
                                                                 '".$shipping_cost."',
                                                                 '".$product_shipping_weight."'
                                                                  )
                                                                ";
					mysql_query($insert_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 =  $row1["referral_charge"];

									}
                                   $var_aff_comm = ($txtorderdamount * $txtReferralCharge / 100);

                       			$sql2 = "INSERT INTO ".$tableprefix."affiliate_registrations (
											affiliate_id,
											user_id,
											order_id,
											user_name ,
											user_first_name,
											user_last_name,
											user_email,
											referral_charge,
											registration_date,
											user_totalpurchasedamount
											) VALUES (
											'".addslashes($aid)."',
											'".addslashes($userid)."',
											'".addslashes($orderid)."',
											'".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);

           } // end if Affiliate Registraion

/************************** Affilate payment block*********************************************/
		//echo "sql==".$sql."<br><br>";

		$product_download_details = TXT_PRODUCT_DOWNLOAD_DETAILS."\r\n";
		$product_download_details .= "-----------------------\r\n";
		$product_download_flag = 0;
		$download_link = "";

		 $sql = "SELECT c.*,(p.product_price+po.additional_price) AS product_price,p.product_name,p.product_code,p.product_artist_id,po.discount,
						p.vdigital_product,ar.commission
				FROM " . $tableprefix . "cart c
                                INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = c.product_option_id
                                INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
                                INNER JOIN " . $tableprefix . "artists ar ON ar.artist_id = p.product_artist_id
				WHERE c.user_id = '".addslashes($_SESSION["sess_userid"])."' ";


		$res = mysql_query($sql);
		$artists = array();

                $product_commission_amt =0;
		if(mysql_num_rows($res) != 0)
		{
			$i=0;
			while($row = mysql_fetch_array($res))
			{
				$productid = $row["product_id"];
                                $product_option_id = $row["product_option_id"];
				$quantity = $row["quantity"];

				/*product price is calculated based on currency type*/

				$converted_price = $row["product_price"];

				$productprice = number_format($converted_price,2,".","");

				//$productprice =  $row["product_price"];

				$productname = $row["product_name"];
                                $optionVal   = getProductOptionsName($product_option_id);
                                $productname .= $optionVal;
				$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();

						$giftamount			= $productprice * $quantity;

						  $insert_coupon_code = "INSERT INTO ".$tableprefix."giftcertificates(vgift_coupon_code,ngift_product_id,
															ngift_order_id,ngift_coupon_amount,user_id,seller_id)
															VALUES('".$gift_coupon_code."',
															".$row["product_id"].",
															".$orderid.",
															".$giftamount.",'".$userid."','".$artistid."')";

						mysql_query($insert_coupon_code) or die(mysql_error());
				}

			$gift_coupon_flag = 1;

		} // end of mysql number of rows check


		//=======================End Gift Certificate Section ===================================


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"]." AND ndigital_orderid =0 ";
		$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();

								$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-----------*/


									$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('".addslashes($product_digital_code_row['vdigital_product_name'])."',
																		".$row["product_id"].",
																		".$orderid.",
																		'".$digital_product_code."',
																		".$product_digital_code_row['ndownload_try'].",0,
																		'".$valid_date_upto."',".addslashes($product_digital_code_row['ndownload_expiry_days']).",0)";
										mysql_query($insert_product_digital_code) or die(mysql_error());
									}	// end for loop
									//exit;
							} // end ehile


						} // emd if number of rows check

				$product_download_flag = 1;



		} // end digital product check

/*----------------------------------End check Digital Products--------------------------------------------------
/*----------------------------------Updating Gift Products----------------------------------------------------------*/

                                $product_tax    = $_SESSION["TAX_DETAILS"][$product_option_id];

                                 // Product Based Commission Calculation

                                $price_amt  = $productprice * $quantity;

                                $product_commission_amt = ($price_amt * $row["commission"])/100;

				 $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,
                                product_tax,
                                product_option_id,
                                product_commission_amount
				)VALUES(
				'".addslashes($orderid)."',
				'".addslashes($productid)."',
				'".addslashes($productname)."',
				'".addslashes($productcode)."',
				'".addslashes($productprice)."',
				'".addslashes($quantity)."',
				'".addslashes($productdiscount)."',
				'".addslashes($artistid)."',
				'1',
				'3',
                                '".$product_tax."',
                                '".$product_option_id."',
                                '".$product_commission_amt."'
				)";
				mysql_query($sql);
				//echo "sql==".$sql."<br><br>";
				$artists[$i] = $artistid;
				$i++;
				$sql = "";

				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());
				}
                                $reorderlevelcheck=checkSellerStock($product_option_id,$quantity);

                                if($reorderlevelcheck==1)
                                {
                                        // Send Stock Reorder Mail To Seller
                                        sendStockreordermail($product_option_id,$quantity);
                                }

			} // end while
		} // end number of rows


                 // Settle seller , Admin Amounts



                 // End

               
           $payment_completed =true;
    
    
}

// End 
if($ack=="SUCCESS" && $payment_completed)
{
    if ("" == $preapprovalKey)
    {
        // redirect for web approval flow
        $cmd = "cmd=_ap-payment&paykey=" . urldecode($resArray["payKey"]);

        RedirectToPayPal ( $cmd );

    }
    else
    {
        // payKey is the key that you can use to identify the result from this Pay call
        $payKey = urldecode($resArray["payKey"]);
        // paymentExecStatus is the status of the payment
        $paymentExecStatus = urldecode($resArray["paymentExecStatus"]);


    }
}
else
{
    //Display a user friendly Error on the page using any of the following error information returned by PayPal
    //TODO - There can be more than 1 error, so check for "error(1).errorId", then "error(2).errorId", and so on until you find no more errors.
	
	 $ErrorCode = urldecode($resArray["error(0).errorId"]);
    $ErrorMsg = urldecode($resArray["error(0).message"]);
    $ErrorDomain = urldecode($resArray["error(0).domain"]);
    $ErrorSeverity = urldecode($resArray["error(0).severity"]);
    $ErrorCategory = urldecode($resArray["error(0).category"]);
	
	$message.= $ErrorMsg;
	
   
    /*echo "Preapproval API call failed. ";
    echo "Detailed Error Message: " . $ErrorMsg;
    echo "Error Code: " . $ErrorCode;
    echo "Error Severity: " . $ErrorSeverity;
    echo "Error Domain: " . $ErrorDomain;
    echo "Error Category: " . $ErrorCategory;*/
}



$active_template = displayTemplate();


include "includes/htmltop.php";

/* Top File Name */

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


?>
<div align="left" class="main_body">

			<!--mainbody area start -->


		<!--center content area start-->

		<div align="left" id="item_details">


		<!--items display area start -->

		<div align="left" id="items_top_area">

				<div align="left" id="items_top_area_ttl"><?php echo PP_PAY_INFO_TEXT; ?></div>
		</div>

		<div>&nbsp;</div>
		
		<?php if($message!='')
		{
		?>

		<div class="text_information" align="center">
		
<b><?php echo PP_NOT_PROCESSED_TEXT; ?></b> <br>
		</div>
		
		<?php          } ?>

		<div align="center" id="items_display_area">

		<table cellpadding="0" cellspacing="0" width="100%">
			<tr>
				<td class="text_information" align="center">
				</td>
			</tr>
			<tr>
			  <td height="8" align="center" ><b> <?php echo $message?> </b></td>
		  </tr>


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

	<div align="left" class="float_clear1"></div>
	 <!--items display area end -->
	  </div>
	<!--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 */
?>	
