    <?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 (C) 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";


$currency_attributes=displayCurrencyType();

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_artistid"]) and $_SESSION["sess_artistid"]!= ""){
	$userid = $_SESSION["sess_artistid"];
}else{
	header("Location:login.php");
	exit;
}

if(checkArtistExpired($userid)){
	header("Location:seller_plan_upgrade.php?sellerid=".$userid);
	exit;
}

$pids = $_GET['pid'];

$productListingFee = getSettingsValue('product_listing_fee');

if($pids != '')
{
    if(!empty($pids))
    {
        //$pids = array_unique($pids);
        $sql = "SELECT product_id, product_name
                  FROM ".$tableprefix."products p
                 WHERE p.product_id IN (". mysql_real_escape_string($pids) .")
            AND p.product_artist_id = " . $userid;
        
        $resultsP = mysql_query($sql) or die(mysql_error());
        $prdCount = mysql_num_rows($resultsP);
    }
}

if(!($productListingFee > 0) || !($prdCount > 0))
{
    header("Location:mycatalog.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"];

//getting payment info
$arsql = "SELECT first_name,last_name,address1,address2,city,state,country,zip,fax,phone,email
    FROM ".$tableprefix."artists 
        WHERE artist_id = " . $userid;
$resa = mysql_query($arsql);
$rowa = mysql_fetch_array($resa);


$txtFirstName   = $rowa["first_name"];
$txtLastName    = $rowa["last_name"];
$txtAddress1 = $rowa["address1"];
$txtAddress2 = $rowa["address2"];
$txtCity = $rowa["city"] ;
$txtState = $rowa["state"];
$txtZIP = $rowa["zip"];
$txtEmail= $rowa["email"];
$ddlCountry = $rowa["country"];
$txtPhone=$rowa["phone"];

$currency_attributes = displayCurrencyType();
$adminCurrency	= GetAdminCurrency();




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




$paymentMethod = "CC";

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


$txtEnableAuthorize 	= getSettingsValue('vauthorize_enable');
$txtEnableBluepay       = getSettingsValue('vbluepay_enable');
$txtEnableFirstData	= getSettingsValue('vyourpay_enable');

$txtEnableStripe	= getSettingsValue('stripe_payment_enable');
if($txtEnableStripe=="Y"){
$txtStripePublishKey = getSettingsValue('stripe_publish_key');
$txtStripeSecretKey = getSettingsValue('stripe_secretkey');
$stripeMode  = getSettingsValue('stripe_payment_test_mode');
}

$totaltopay = $productListingFee * $prdCount;

$totaltopay = number_format($totaltopay,2,".","");
if (isset($_POST["totaltopay"]) && $_POST["totaltopay"]!="" )
 {
    
if($txtEnableAuthorize == 'Y')
{
$txtAuthorizeLoginId = $row["authorize_loginid"];
$txtAuthorizeTransKey = $row["authorize_transkey"];
$txtCurrency = "USD";
$txtAuthorizeEmail = $row["authorize_email"];
$txtAuthorizeTestMode = $row["authorize_test_mode"];
if($txtAuthorizeTestMode == "Y"){
	$txtAuthorizeTestMode = "on";
}else{
	$txtAuthorizeTestMode = "off";
}



$gift_coupon_flag = 0;

	$message = "";

	$paymentsuccessful = false;
	$paymenterror = "";
	$referrer =  $_SERVER["HTTP_REFERER"];
    
    $Cust_ip = getClientIP();
	
	
	$txtAddress = $txtAddress1;
	if(!$ddlCountry)
	$ddlCountry = $bill_country;
	if(!$txtState)
	$txtState = $bill_state;
	
    $Company = "-NA-";
    $Phone=$txtPhone;
    if($txtLastName=="")
      $txtLastName="-NA-";
	
	require "../authorize-product-listing.php";//process the card and return result. Comment this line and uncomment the two lines below to make payment test mode
	//$paymentsuccessful = true;
	// = "TEST1234444";
 }elseif($txtEnableBluepay=='Y') {

                
                
		$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", $totaltopay);	# 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.$totaltopay.$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 = "Sorry, the transaction cannot be processed";
                  }
        }elseif($txtEnableFirstData=='Y')
		{
			include_once "../includes/firstData.php";


			$mylphp=new firstData;

$myorder = array();

		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,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"] = "Item Purchase Information with  ".SITE_NAME." online store";

			$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 = "Unable to process your payment. Try again later.";
                                }
                                  else
                                  {
                                    $paymenterror=$result["r_error"];
                                  }

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


}else if($txtEnableStripe=="Y"){ // Stripe payment code

            include_once "../library/stripe/Stripe.php";
            Stripe::setApiKey($txtStripeSecretKey);
            try {
                if (!isset($_POST['stripeToken'])){
                   //throw new Exception("The Stripe Token was not generated correctly");
                    $paymenterror = $error;
                }
                    $order_total  = $totaltopay;
                    $orderTotal   = round($order_total);
                  
                    $txtCurrency                =     $adminCurrency['currency_code'];
                    Stripe_Charge::create(array("amount" => $orderTotal * 100,
                                    "currency" => $txtCurrency,
                                    "card" => $_POST['stripeToken'],
                                    "description" => $txtEmail));
                        $success = '<div class="alert alert-success">
                                    <strong>Success!</strong> Your payment was successful.
                                                    </div>';
                        
                    $paymentsuccessful = true;
                }
                catch (Exception $e) {
                      $error = '<div class="alert alert-danger">
                                        <strong>Error!</strong> '.$e->getMessage().'
                                        </div>';
                      
                      $paymenterror = $error;
                }
                 
                 

 }
	
     
if($paymentsuccessful)
{
    $sql = "UPDATE ".$tableprefix."products
               SET payment_status = 'COMPLETED'
             WHERE product_id IN (". mysql_real_escape_string($pids) .")
               AND product_artist_id = " . $userid;
        $resultsP = mysql_query($sql) or die(mysql_error());
        
        $pids = explode(',', $pids);
        if(!empty($pids))
        {
            foreach($pids as $id)
            { 	
                    $sql = "INSERT INTO ".$tableprefix."product_listing_fee_payment
                                    SET payment_status = 'COMPLETED',
                                        product_id = '". mysql_real_escape_string($id) ."',
                                        total_amount = '". mysql_real_escape_string($productListingFee) ."',
                                        amount_paid= '". mysql_real_escape_string($productListingFee) ."',
                                        payment_method = 'CREDIT_CARD'";
                    $resultsP = mysql_query($sql) or die(mysql_error());
            }
        }
        
        
        header("Location:myproducts.php?message=Payment completed successfully");
}
else
{
    
}
//------------------------------Ends here--------------------------------------------------------------//



	
 }



	
		


if ($_POST["btnCancelOrder"] == "Cancel") {
	$redirecturl = SITE_URL."/sellers/myproducts.php";
	header("Location:$redirecturl");
	exit;
}




include "../includes/htmltop.php";
?>


		
		<body>
		
		<center>
		
		<div align="left" id="layout">
		
		
				
				
				<!--header area start -->
<?php
	include_once("../includes/topheader_seller.php")
?>
				
				<!--header area end -->
				
				
				
				
				<div align="left" class="main_body">
				<!--main body start -->
				
				
				
<?php
    include_once("../includes/artisttopmenu.php")
?>		
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>																					
<script language="javascript" src="../includes/function.js"></script>
<script language="javascript" >
function validateForm(){
	 var frm = window.document.frmPayment;
        var yearVal = frm.txtYY.value;
        var month = frm.txtMM.value;
        currentMonth = new Date().getMonth() + 1,
        currentYear  = new Date().getFullYear();
        
      if (frm.txtCCNumber.value.length == 0 ) {
		alert('<?php echo MSG_VALID_CREDIT_CARD_NUMBER;?>');
		return false;
	}else if (frm.txtCVV2.value.length == 0 ) {
		alert('<?php echo MSG_VALID_CREDIT_CARD_CVV;?>');
		
		return false;
	}else if ((frm.txtMM.value.length == 0 || frm.txtMM.value > 12 ) || (yearVal < currentYear || yearVal > currentYear + 100)   ) {
		alert('<?php echo MSG_VALID_CREDIT_CARD_EXPIRY?>');
		return false;
                
           
	}else if(yearVal < currentYear || (yearVal == currentYear && month < currentMonth)) {
                alert('<?php echo MSG_VALID_CREDIT_CARD_EXPIRY?>');
		return false;
        } else{
		var txtEnableStripe = '<?php echo $txtEnableStripe; ?>';
                if(txtEnableStripe=="Y"){
                    Stripe.card.createToken({
                            number: $('#txtCCNumber').val(),
                            cvc: $('#txtCVV2').val(),
                            exp_month: $('#txtMM').val(),
                            exp_year: $('#txtYY').val(),
                            name: '<?php echo $txtFirstName; ?>',
                            address_line1: '<?php echo $txtAddress1; ?>',
                            address_city: '<?php echo $txtCity; ?>',
                            address_zip: '<?php echo $txtZIP; ?>',
                            address_state: '<?php echo $txtState; ?>',
                            address_country: '<?php echo $ddlCountry; ?>'
                        }, stripeResponseHandler);
                        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="";
        }
}
Stripe.setPublishableKey('<?php echo $txtStripePublishKey; ?>');
 
  function stripeResponseHandler(status, response) {
        if (response.error) {
            // re-enable the submit button
          document.getElementById('a_x200').style.display = 'block';
            // show the errors on the form
            $(".payment-errors").html(response.error.message);
        } else {
            var form$ = $("#frmPayment");
            // token contains id, last4, and card type
            var token = response['id'];
            // insert the token into the form so it gets submitted to the server
            form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
            // and submit
            form$.get(0).submit();
        }
}

</script>							
					<div align="left" class="content_area">
					
					<!--content area start -->
					<div class="text_information" align="center">
                                            <div class="alert alert-danger" id="a_x200" style="display: none;"> <strong>Error!</strong>
                                                <span class="payment-errors"></span> </div>
                                                <?php echo $paymenterror?>
                                        </div>
            		<br>
											
					<div align="left">																			
		<form action="<?php echo $_SERVER["PHP_SELF"]?>?&pid=<?php echo $pids; ?>" method="post" id="frmPayment" 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?>">
					
			<input type="hidden" name="userid" value="<?php echo htmlentities($userid);?>">
		<fieldset>
		<table width="100%" border="0" cellspacing="2" cellpadding="2" class="manage_table">
<?php

if(!$paymentsuccessful)
{

?>
		
		<tr>
		  <td height="40" colspan="3"><h2><strong>Payment Details </strong></h2></td>
		  </tr>
		<tr>
			<td>Total to Pay</td>
			<td colspan="2">
<?php
  echo $adminCurrency['currency_symbol']." ".number_format($totaltopay,2,".","");
?></td>
		 </tr>
<?php	
  
	$check_shipping_enable = checkShippingEnable();
	if($check_shipping_enable == "Y" && $hide_shipping_division == 1)
	{
		 
		$shipping_cost = $_SESSION['SESS_upscost'];
				
				
?>		

		
				<td>Grand Total</td>
			<td align="left" colspan="2"><input type="hidden" name="cart_total" value="1000">
	<?php 				
						 echo $currency_attributes[0];
   						 echo "&nbsp;";
						$grandtotal=$display_total ;
						echo number_format($grandtotal,2,".","");
		}
		else
		{
																																					
	?> 
	
		<input type="hidden" name="cart_total" value="<?php echo $display_total;?>">
	
	<?php
	
		}
	
	?>
	
		  
		  <tr>
			<td width="25%">Card Number</td>
			<td width="28%" align="left"><input type=text name="txtCCNumber" id="txtCCNumber" maxlength=16 class=textbox value="<?php echo $txtCCNumber?>" size="30"></td>
		  </tr>
		  <tr>
			<td>Card Validation Code</td>
			<td><input type="text" name="txtCVV2" id="txtCVV2" maxlength="10" class="textbox" value="<?php echo $txtCVV2?>" size="15">&nbsp;
			</td>
			<td width="47%"></td>
		  </tr>
		  <tr>
			<td>Expiration Date :(MM/YYYY)</td>
			<td colspan="2">
			<select name="txtMM" id="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++)
			{
			?>
			<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="2" align="center">
				  <input type="submit"  name="btnCancelOrder" value="Cancel" class="button" onclick="window.location.href='<?php echo SITE_URL?>/sellers/artistmain.php'">
				   	<input type="submit"  name="btnCompleteOrder" value="Pay Now" class="button" onclick="return validateForm();">&nbsp;&nbsp;
			</td>
		  </tr>
		<?php
		 }
		 else
		 {
		 ?>

		<tr>
			<td colspan="3" align="center" class="text_information">
					Your Payment has  successfully Completed!
			</td>
		</tr>
		<tr>
			<td colspan="3">&nbsp;</td>
		</tr>
		<tr>
			<td colspan="3" align="center">
				<input type='button' value='Home'  class='button' onClick="window.location.href='<?php echo SITE_URL?>/sellers/artistmain.php'">
&nbsp;&nbsp;			</td>
		</tr>

<?php
 }
?>
   		</table>
		</fieldset></form>
				
				</div>
										
				<!--content area end-->
								
				</div>
				
								

					<div align="left" class="clear_float"><img src="<?php echo $imagefolder;?>/clear.gif" alt="" width="1" height="1" /></div>
				<!--main body end -->
				</div>
				
				
<?php
	include "../includes/footer.php";
?>