<?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";

//sendBuyerEmail($orderid,$_SESSION["sess_userid"]);


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



$currency_attributes=displayCurrencyType();

$adminCurrency	= GetAdminCurrency();


if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
	$_SESSION = array_map('stripslashes_deep', $_SESSION);
}

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

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


/*-------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------*/
$txtCCNumber = $_POST["txtCCNumber"];
$txtCVV2 = $_POST["txtCVV2"];
$txtMM = $_POST["txtMM"];
$txtYY = $_POST["txtYY"];

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


/*if(isset($_SESSION['couponCode_det']))
{
	$totaltopay = number_format(($currency_attributes[1] * getCartTotalcouponCode($userid,$_SESSION['couponCode_det'])),2,".","");
}else{

	$totaltopay = number_format(($currency_attributes[1] * getCartTotal($userid)),2,".","");
}*/

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

$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($check_shipping_enable == "Y" && $hide_shipping_division == 1)
{
 
	$shipping_cost = $_SESSION['SHIPPING_TOTAL'];
	
	$totaltopay=number_format($totaltopay,2,".","");
	
	$totaltopay = $totaltopay + $shipping_cost;
	
}

$totaltaxrate =0;

$shipping_cost = 0;

$totaltaxrate=number_format($_SESSION["TAX_TOTAL"],2,".","");
//shipping cost
$shipping_cost=number_format($_SESSION['SHIPPING_TOTAL'],2,".","");

$paymentMethod = "CC";

//getting payment info
$sql = "SELECT * FROM ".$tableprefix."settings ";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);




$gift_coupon_flag = 0;

if (isset($_POST["btnCompleteOrder"]))
 {
    $message = "";

    $paymentsuccessful = false;
    $paymenterror = "";

    $txtEnableAuthorize 	= getSettingsValue('vauthorize_enable');

    // Check Bluepay  payment is Enabled 

	$txtEnableBluepay = getSettingsValue('vbluepay_enable');


        $txtCCNumber = $_POST["txtCCNumber"];
        $txtCVV2 = $_POST["txtCVV2"];
        $txtMM = $_POST["txtMM"];
        $txtYY = $_POST["txtYY"];

        $paymentsuccessful = false;
        $paymenterror = "";


        // Check Bluepay  payment is Enabled

        if($txtEnableBluepay=='Y') {

                $order_total_amount     =   number_format($totaltopay+$totaltaxrate,2,".","");
                
		$txtBluepayAccountId = getSettingsValue('bluepay_accountid');

		$txtBluepaySecretKey = getSettingsValue('bluepay_secretkey');

		 $mode  = getSettingsValue('bluepay_test_mode');
                
		
		$card_expiry    = $txtMM.substr($txtYY,-2);
		include "includes/Bluepay.php";
		$bp = new Services_Bluepay();
		$bp->setValue("ACCOUNT_ID", $txtBluepayAccountId);
		$bp->setValue("SECRET_KEY", $txtBluepaySecretKey);
		$bp->setValue("TRANS_TYPE", 'SALE');
		$bp->setValue("MODE", $mode);		# Default is TEST --> Set to LIVE for live tx
		$bp->setValue("AMOUNT", $order_total_amount);	# ODD returns Approved, EVEN returns Declined in TEST mode
		$bp->setValue("PAYMENT_ACCOUNT", $txtCCNumber);	# Card Number
		$bp->setValue("CARD_EXPIRE", $card_expiry);
		$bp->setValue("NAME1", $txtFirstName);
		$bp->setValue("NAME2", $txtLastName);
		$bp->setValue("PHONE", $txtPhone);
		$bp->setValue("EMAIL", $txtEmail);
		$bp->setValue("COMPANY_NAME", SITE_NAME);
		$tamperProofSeal=md5($txtBluepaySecretKey.$txtBluepayAccountId.$order_total_amount.$mode);
		$bp->setValue("TAMPER_PROOF_SEAL", $tamperProofSeal);
		$bp->setValue("ADDR1", $txtAddress1);
		$bp->setValue("CITY", $txtCity);
		$bp->setValue("STATE", $txtState);
		$bp->setValue("ZIP", $txtZIP);
		$bp->setValue("COUNTRY", $ddlCountry);
		$bp->bp20post();
		$transactionid = $bp->getValue("TRANS_ID");
		$paymentsuccessful = false;
		if($transactionid != "" && $bp->getValue("MESSAGE")	== "Approved Sale" && $bp->getValue("STATUS")== "1") {
		$paymentsuccessful = true;
		}
		else {

	 $paymenterror = CANNOT_PROCESS_TEXT;
                  }
        }


   // Check Authorise payment Enabled

        if($txtEnableAuthorize == 'Y') {

                $txtAuthorizeLoginId        =     getSettingsValue("authorize_loginid");
                $txtAuthorizeTransKey       =     getSettingsValue("authorize_transkey");
                $txtCurrency                =     $adminCurrency['currency_code'];
                $txtAuthorizeEmail          =     getSettingsValue("authorize_email");
                $txtAuthorizeTestMode       =     getSettingsValue("authorize_test_mode");

              
               
                if($txtAuthorizeTestMode == "Y"){
                        $txtAuthorizeTestMode = "on";
                }else{
                        $txtAuthorizeTestMode = "off";
                }


                $referrer =  $_SERVER["HTTP_REFERER"];
                $qry1="select max(order_id)+1 as ordid from " . $tableprefix . "orders";
                $excqry1=mysql_query($qry1);
                $row1=mysql_fetch_array($excqry1);
                $Inv_id=$row1['ordid'];
                $Cust_id = $_SESSION["sess_userid"];
                $Cust_ip = getClientIP();
                $Company = "-NA-";
                $Phone=$txtPhone;
                if($txtLastName=="")
                  $txtLastName="-NA-";

                require "authorize.php";//process the card and return result. Comment this line and uncomment the two lines below to make payment test mode


        }


        // First Data Payment Integration  Done By Asha 
		$txtEnableFirstData	= getSettingsValue('vyourpay_enable');
		if($txtEnableFirstData=='Y')
		{
			include_once "includes/firstData.php";


			$mylphp=new firstData;



		if(getSettingsValue('vyourpay_mode')=='TEST')
		{
			//$myorder["host"]       = "208.72.248.102";   //secure.linkpt.net for Live
			$myorder["host"]       = "staging.linkpt.net";

                        $myorder["result"]     = "LIVE";

		}
		else
		{
			$myorder["host"]       = "secure.linkpt.net";   //secure.linkpt.net for Live
			$myorder["result"]     = "LIVE";
		}
			$myorder["port"]       = "1129";

			//##Merchantinfo
			$myorder["keyfile"]    = "pem/".getSettingsValue('vyourpay_certificate_file'); # Change this to the name and location of your certificate file
			$myorder["configfile"] =trim(getSettingsValue('vyourpay_storeid')); # Change this to your store number
			//## Orderoptions
                        
			 $myorder["ordertype"]    = "SALE" ; //The type of transaction. The possible values are SALE,PREAUTH,VOID,POSTAUTH,CREDIT, CALCSHIPPING

			$yearlen=strlen($txtYY);

			if($yearlen>2)
			{
				$CardYear= substr($txtYY,-2);
			}
			# card info
			$myorder["cardnumber"]   = $txtCCNumber ;
			$myorder["cardexpmonth"] = $txtMM;
			$myorder["cardexpyear"]  = $CardYear;
			$myorder["cvmindicator"] = "provided";
			$myorder["cvmvalue"]     =  $txtCVV2;
			//## Payment
			//$myorder["subtotal"]    = $totaltopay;
			//$myorder["tax"]         = number_format($totaltaxrate,2,".","");
			//$myorder["shipping"]    = number_format($shipping_cost,2,".","");
			//$myorder["vattax"]      = "0.00";
			$myorder["chargetotal"] = number_format($totaltopay+$totaltaxrate,2,".","");
			// ## Billing
			$myorder["name"]      = $txtFirstName;
			$myorder["address1"]  = $txtAddress1;
			$myorder["address2"]  = $txtAddress2;
			$myorder["city"]      = $txtCity;
			$myorder["state"]     = $txtState;
			$myorder["country"]   = $ddlCountry;
			$myorder["phone"]     = $txtPhone;
			$myorder["email"]     = $txtEmail;
			$myorder["fax"]    	  = $txtFAX;
			$myorder["addrnum"]   = '';   # Required for AVS. The numeric portion of the street address If not provided, transactions will downgrade.
			$myorder["zip"]       = $txtZIP; # Required for AVS. Billing zip or postal code If not provided, transactions will downgrade.
			//$items = array();
			//$myorder["items"][0] = $items; # put array of items into hash

			$myorder["comments"] = str_replace("{SITE_NAME}", SITE_NAME, MSG_PAYMENT_ITEM_SUBJECT);
                        

			$result = $mylphp->curl_process($myorder);  # use curl methods

			$transactionid		=	$result["r_ordernum"];

                       

			if($transactionid != "" && $result["r_approved"] == "APPROVED") {
				$paymentsuccessful = true;
			}
			if ($result["r_approved"] != "APPROVED")	// transaction failed, print the reason
			{
				if($result["r_error"]=='<')
                                {
                                   $paymenterror = PROCESS_TRY_LATER_TEXT;
                                }
                                  else
                                  {
                                    $paymenterror=$result["r_error"];
                                  }

				$msg_error=$paymenterror;
				$_SESSION['PAYMENT_ERROR']=$result["r_error"];
			}


}
	
	//$paymentsuccessful = true;
	// = "TEST1234444";
	
if($paymentsuccessful)
{ // check if credit card payment is success

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

		 $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.",
				namount_paid,
                                buyer_comments,
                                vpayment_status
				) 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["sessShippingDisplayName"])."',
				now(),
				'".addslashes($totaltopay)."',
				'".addslashes($totaltaxrate)."',
				'1',
				'".addslashes($tx_token)."',
				'".$currency_attributes[2]."'".$valueCouponCode.",
				'".addslashes($amountpaid)."',
                                '".addslashes($_SESSION["SESS_BUYER_COMMENTS"])."',
                                'C'
				)";
		 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 = "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;


                                if($row['discount']!=0)
                                    {

                                        $discountprice		=	$productprice-($productprice*$row["discount"])/100;
                                        $discountprice 		=	number_format($discountprice,2,".","");

                                        $discount_amount        = $discountprice * $quantity;

                                    }

                                    else
                                        {
                                            $discount_amount  = $price_amt;
                                    }


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


                                 // Product Based Commission Calculation End 
                                
				 $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',
				'0',
                                '".$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

} // end if credit card check


if($paymentsuccessful)
 {
/*--------Updating the order status to 'delivered' if the product purchased is gift coupon------------*/		
		if($gift_coupon_flag == 1)
		{
			if(isset($_SESSION['SESS_digital_product']) && $_SESSION['SESS_digital_product']!='')
			{
				
				unset($_SESSION['SESS_digital_product']);
				
			}
			
			$update_order_details = "UPDATE ".$tableprefix."order_details 
									 SET item_status = 4 
									 WHERE order_id  = ".$orderid." ";
			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($paymentsuccessful)
{
/*------------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($paymentsuccessful)
{
/*-----------------Digital Product Mail Sending Starts----------------*/
	if($product_download_flag == 1)
		{
			//(isset($_SESSION['SESS_digital_product']))?session_unregister('SESS_digital_product'):session_register('SESS_digital_product');
		
			$_SESSION['SESS_digital_product'] = 1;
			
		}	
	// Send Giftcertificate Mails 
		if($gift_coupon_flag == 1)
		{
			sendgiftCertificateMail_Buyer($orderid,$_SESSION["sess_userid"],$usertype);
			sendgiftCertificateMail_Seller($orderid,$_SESSION["sess_userid"]);
			sendgiftCertificateMail_Admin($orderid,$_SESSION["sess_userid"]);
		}
		
		//Send Digital Certificate Mails
		
		if($product_download_flag == 1)
		{
			sendDigitalCertificateMail_Buyer($orderid,$_SESSION["sess_userid"],$usertype);
			sendDigitalCertificateMail_Seller($orderid,$_SESSION["sess_userid"]);
			sendDigitalCertificateMail_Admin($orderid,$_SESSION["sess_userid"]);
		}
		
		
		
		
		if($product_download_flag!=1 && $gift_coupon_flag!=1)
		{
			sendBuyerEmail($orderid,$_SESSION["sess_userid"],$usertype);
			sendSellerEmail($orderid,$_SESSION["sess_userid"]);
			sendAdminEmail($orderid,$_SESSION["sess_userid"]);
			
		}

		
	
} // end if paypal check 


if($paymentsuccessful)
{ // check if paypal is success
		
		adjustStock($_SESSION["sess_userid"],"-" );
		emptyCart($_SESSION["sess_userid"]);
		$_SESSION["sess_addresses_collected"] = false;
		$_SESSION["sess_stock_adjusted"] = false;
		$_SESSION['couponCode_det']='';
		if(isset($_SESSION['guest_login']) && $_SESSION['guest_login']!='')
		{
			unset($_SESSION['guest_login']);
			unset($_SESSION['sess_userid']);
			$_SESSION['guest_login']='';
			$_SESSION["sess_userid"]='';
		}	
		$_SESSION["sess_guest_username"]='';
		$_SESSION["sess_guest_password"]='';
		 $_SESSION["sessShippingDisplayName"]='';
		 $_SESSION['sess_giftcertificate_code']='';
		 $_SESSION['sess_gift_amount_used']='';
		 $_SESSION['amount_paid']='';
		 $_SESSION['sess_giftcertificate_available_amt']='';
                 $_SESSION["SESS_BUYER_COMMENTS"] ='';
                 $_SESSION["TAX_TOTAL"] ='';
                    unset($_SESSION['SHIPPING_TOTAL']);
                    $_SESSION["SHIPPING_DETAILS"]   =array();
                     unset($_SESSION["SHIPPING_DETAILS"]);
                     unset($_SESSION["TAX_DETAILS"]);
                     unset($_SESSION['couponCode_det']);

		 
		 
 }		
	
}

if (isset($_POST["btnCancelOrder"])) {
	$message = "";
	adjustStock($_SESSION["sess_userid"],"+" );
	emptyCart($_SESSION["sess_userid"]);
	$_SESSION["sess_addresses_collected"] = false;
	$_SESSION["sess_stock_adjusted"] = false;
	$redirecturl = SITE_URL."/index.php";
	header("Location:$redirecturl");
	exit;
}

/*display the active template*/

$active_template = displayTemplate();


include "includes/htmltop.php";

/* Top File Name */

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

?>
<script language="javascript" src="includes/function.js"></script>
<script language="javascript" >
function validateForm(){
	var frm = window.document.frmPayment;
    if (frm.txtCCNumber.value.length == 0 ) {
		alert('<?php echo INVALID_CARD_TEXT;?>');
		return false;
	}else if (frm.txtMM.value.length == 0 || frm.txtYY.value.length == 0 || frm.txtYY.value < 2005 || frm.txtMM.value > 12 ) {
		alert('<?php echo INVALID_CARD_EXPIRY_DATE_TEXT?>');
		return false;
	}else{
		return true;
	}
}


function onlyNumeric(){
         if (event.keyCode<48||event.keyCode>57)
         return false;
}

function checkNumber(t) {
        if(t.value.length == 0 ||  isNaN(t.value) || t.value.substr(0,1) == " " || parseInt(t.value) < 0) {
                t.value="";
        }
}

</script>


			<div align="left" class="main_body">
			<!--mainbody area start -->

		<!--center content area start-->		
		
		<form action="<?php echo $_SERVER["PHP_SELF"]?>" method="post" name="frmPayment" >
		<input type="hidden" name="userid" value="<?php echo $userid ?>">
		<input type="hidden" name="totaltopay" value="<?php echo $totaltopay?>">
		<input type="hidden" name="paymentMethod" value="<?php echo $paymentMethod?>">
		
		<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 CREDIT_CARD_PAY_TEXT; ?></div>
		</div>
		<br>
		
		<div class="text_information" align="center"><?php echo $paymenterror?></div>
		
		<div>
		
		<fieldset>
		<div class="payment_styles">
		<table width="100%" border="0" cellspacing="3" cellpadding="3">
<?php

if(!$paymentsuccessful)
{

?>
		
		<tr>
			<td><?php echo TOTAL_ITEM_COST_TEXT;?></td>
			<td colspan="2">
<?php
  
 if(isset($_SESSION['couponCode_det']))
{
	  $display_total = number_format(getCartTotalcouponCode($_SESSION["sess_userid"],$_SESSION['couponCode_det']),2,".","");
}else{
	  $display_total = number_format(getCartTotal($_SESSION["sess_userid"]),2,".","");
}
   
   
   if(isset($_SESSION['couponCode_det']))
{
	$display_total = number_format(getCartTotalcouponCode($_SESSION["sess_userid"],$_SESSION['couponCode_det']),2,".","");
}else{

  $display_total = number_format(getCartTotal($_SESSION["sess_userid"]),2,".","");
}
   
   echo $adminCurrency['currency_symbol'];
   echo "&nbsp;";
   echo number_format(getCartTotal($_SESSION["sess_userid"]),2,".","");
?></td>
		 </tr>
<?php	
  
	$check_shipping_enable = checkShippingEnable();
	if($check_shipping_enable == "Y" && $hide_shipping_division == 1)
	{
		 
		$shipping_cost = $_SESSION['SHIPPING_TOTAL'];
	}
				
		
		else
		{
																																					
	?> 
	
		<input type="hidden" name="cart_total" value="<?php echo $display_total;?>">
	
	<?php
	
		}
	
	?>
				

<?php if($shipping_cost!=0){ ?>
	 <tr>
		<td><?php echo TOTAL_SHIP_COST_TEXT;?></td>
		<td colspan="2">
<?php 				
						 echo $adminCurrency['currency_symbol'];
						echo "&nbsp;";
						echo number_format($shipping_cost,2,".","");
?>
		</td>
		</tr>
<?php } // end shipping cost check ?>
		<?php if($_SESSION["TAX_TOTAL"]!=0)
		{ // check tax rate is empty or not 
		?>
		<tr>
		  <td>&nbsp;Tax Rate </td>
		  <td align="left" colspan="2"><?php 
		  	echo "&#36;";
			echo "&nbsp;"; 
			echo number_format($_SESSION["TAX_TOTAL"],2,".","");?>
		  </tr>  
		  <?php } ?> 
		  
		  <?php if($_SESSION['couponCode_det']['ccDiscount']!='')
			{ 
			?>
			<tr>
		  <td><?php echo COUPON_CODE_TEXT1;?> ' <?php echo $_SESSION['couponCode_det']['ccCode'] ?>' <?php echo DISCOUNT_TEXT;?>   </td>
		  <td align="left" colspan="2">
			<?php echo $_SESSION['couponCode_det']['ccDiscount'];?> % 
		  </tr>  
			
			
		<?php } ?>
			 
		  
<?php if($_SESSION['sess_giftcertificate_code']!='' && $_SESSION['sess_gift_amount_used']!='')
{

?>

		<tr>
		  <td>&nbsp;<?php echo GIFT_AMT_TEXT; ?> </td>
		  <td align="left" colspan="2"><?php 
		  	 echo $adminCurrency['currency_symbol'];
			echo "&nbsp;"; 
			echo number_format($_SESSION['sess_gift_amount_used'],2,".","");?>  
		  </tr>  

<?php  } ?>		    
		  <tr>
				<td><?php echo TOTAL_PAY_TEXT;?></td>
				<td align="left" colspan="2">
				
	<?php 				
						$grandtotal=$display_total + $shipping_cost +$totaltaxrate;
						
						if($_SESSION['sess_gift_amount_used']>0)
						{
							$amount_to_pay	= $grandtotal-$_SESSION['sess_gift_amount_used'];
						}
						else
						{
							$amount_to_pay	= $grandtotal;
						}
						echo $adminCurrency['currency_symbol'];
   						echo "&nbsp;";
						
						echo number_format($amount_to_pay,2,".","");
						
				echo '<input type="hidden" name="cart_total" value='.number_format($amount_to_pay,2,".","").'>';

?>
	
		  
		  <tr>
			<td width="25%"><?php echo CARD_NUM_TEXT;?></td>
			<td width="28%" align="left"><input type=text name="txtCCNumber" maxlength=16 class=textarea value="<?php echo $txtCCNumber?>" size="30" tabindex="1"></td>
		  </tr>
		  <tr>
			<td><?php echo CARD_VALIDATE_CODE;?></td>
			<td><input type="text" name="txtCVV2" maxlength="10" class="textarea" value="<?php echo $txtCVV2?>" size="15" tabindex="2">&nbsp;
			<a style="cursor:pointer" onClick="Javascript:window.open('credit_card_validation_image.php', 'CardValidationImage','menubar=0,resizable=0,width=300,height=220')"><img src="<?php echo SECURE_SITE_URL."/images/question_mark.jpg"?>" title="<?php echo WHAT_THIS_TEXT;?>" height="25"></a>
			</td>
			<td width="47%"></td>
		  </tr>
		  <tr>
			<td><?php echo EXP_DATE_TEXT;?></td>
			<td colspan="2">
			<select name="txtMM" onBlur="javascript:checkNumber(this);" tabindex="3">
			<?php 
			for($i=1;$i<13;$i++)
			{
			if($i<10)
			$val = "0".$i;
			else
			$val = $i;
			?>
			<option value="<?php echo $val;?>" <?php if($val==$txtMM || $i==$txtMM) echo "selected";?>><?php echo $val;?></option>
			<?php
			}
			?>
			</select>
			<select name="txtYY" id="txtYY" onBlur="javascript:checkNumber(this);" tabindex="4">
			<?php 
			for($j=date("Y");$j<(date("Y")+35);$j++)
			{
j
			?>
			<option value="<?php echo $j;?>" <?php if($j==$txtYY) echo "selected";?>><?php echo $j;?></option>
			<?php
			}
			?>
			</select>
			</td>
		  </tr>

		  <tr>
			<td colspan="3">&nbsp;</td>
		  </tr>
		  
		  <tr>
			 <td colspan="3" align="center">				   &nbsp;&nbsp;
				   <input   type="submit" name="btnCancelOrder" value="<?php echo CANCEL_ORDER_TEXT;?>" class="button" onclick="" tabindex="6">
				   <input type="submit"  name="btnCompleteOrder" value="<?php echo ORDER_COMPLETE_TEXT;?>" class="button" onClick="return validateForm();" tabindex="5">
			</td>
		  </tr>
		<?php
		 }
		 else
		 {
		 
			if($check_shipping_enable == "Y")
			{
				unset($_SESSION['SESS_upstype']);
				unset($_SESSION['SHIPPING_TOTAL']);
				unset($_SESSION['SESS_upsweight']);
			}	
		 ?>

		<tr>
			<td colspan="3" align="center"  style="background-color: ">
					<b style="background-color:#000000; margin-bottom:15px; font-family:Arial, Helvetica, sans-serif; font-size:12px; padding:10px 10px 10px 10px; color:#67CB1A;"><?php echo ORDER_PLACED_SUCESS_TEXT; ?></b>
			</td>
		</tr>
		<tr>
		  <td height="8" colspan="3" align="center" ></td>
		  </tr>

<?php

if(isset($_SESSION['SESS_digital_product']) && $_SESSION['SESS_digital_product']!='')
{
?>		
		<tr>
			<td colspan="3" align="center" style="color:#006600;">
					<b style="background-color:#000000; padding:10px 10px 10px 10px; font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#67CB1A;"><?php echo PRODUCT_LINK_MAIL_TEXT; ?></b>
			</td>
		</tr>
<?php

}
$_SESSION['SESS_digital_product']='';
unset($_SESSION['SESS_digital_product']);
?>		
		<tr>
			<td colspan="3">&nbsp;</td>
		</tr>
		<tr>
			<td colspan="3" 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 CONTINUE_SHOPPING_BUTTON; ?>'  class='button' onClick="window.location.href='<?php echo SITE_URL?>/categorydetail.php'">
			</td>
		</tr>

<?php

 }
 
?>
   		</table>
		<div class="clear"></div>
		</div>
		</fieldset>		
	
		</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 */
?>



