<?php
//This code is copyright (c) ViciSoft SL, all rights reserved.
//The contents of this file are protected under law as the intellectual property
//of ViciSoft SL. Any use, reproduction, disclosure or copying
//of any kind without the express and written permission of ViciSoft SL is forbidden.
//Author: Vince Reid, vincereid@gmail.com
$isvsadmindir=TRUE;
include 'db_conn_open.php';
include 'inc/languagefile.php';
include 'includes.php';
include 'inc/incemail.php';
include 'inc/incfunctions.php';

if(@$htmlemails==TRUE) $emlNl='<br />'; else $emlNl="\n";
$emailtxt='Stripe Webhook Debug'.$emlNl;
function already_authorized($tid){
	global $ordTransSession;
	$isalready=FALSE;
	$sSQL="SELECT ordAuthNumber,ordAuthStatus,ordTransSession FROM orders WHERE ordID='" . escape_string($tid) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(trim($rs['ordAuthNumber'])!=''&&trim($rs['ordAuthNumber'])!='no ipn'&&trim($rs['ordAuthNumber'])!='CHECK MANUALLY')$isalready=TRUE;
		$ordTransSession=$rs['ordTransSession'];
	}
	if($isalready&&@$digidownloademail!=''){
		if(substr($rs['ordAuthStatus'],0,8)=='Pending:'){
			$sSQL="SELECT cartProdID FROM products INNER JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID WHERE cartOrderID='" . escape_string($tid) . " AND pDownload<>''";
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0) $isalready=FALSE;
		}
	}
	ect_free_result($result);
	return($isalready);
}
$alreadygotadmin=getadminsettings();
if(getget('pprov')=='29'&&is_numeric(getget('ordid'))){
	if(getpayprovdetx(29,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$ordID=getget('ordid');
		$success=FALSE;
		
		$sSQL="SELECT ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordCountry,ordPhone,ordZip,ordEmail,ordAuthNumber,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAuthNumber,ordTransID,ordStatus FROM orders WHERE ordPayProvider=29 AND ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$amount=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
		}
		
		$jsonContent = json_decode(file_get_contents('php://input'));
		$payment_token=$jsonContent->paymentToken;

		$fields = array(
			'security_key' => $data1,
			'payment_token' => $jsonContent->paymentToken,
			'amount' => $amount,
			'email' => $jsonContent->email,
			'phone' => $jsonContent->phone,
			'city' => $jsonContent->city,
			'address1' => $jsonContent->address1,
			'country' => $jsonContent->country,
			'first_name' => $jsonContent->firstName,
			'last_name' => $jsonContent->lastName,
			'zip' => $jsonContent->postalCode,
			'cavv' => $jsonContent->cavv,
			'xid' => $jsonContent->xid,
			'eci' => $jsonContent->eci,
			'cardholder_auth' => $jsonContent->cardHolderAuth,
			'three_ds_version' => $jsonContent->threeDsVersion,
			'directory_server_id' => $jsonContent->directoryServiceId
		);

		$curl = curl_init();

		curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://secure.nmi.com/api/transact.php',
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS => $fields
		));

		$response = curl_exec($curl);

		curl_close($curl);
		
		$response_arr=explode('&',$response);
		foreach($response_arr as $value){
			$itemarr=explode('=',$value);
			if($itemarr[0]=='responsetext') $success=($itemarr[1]=='SUCCESS');
			if($itemarr[0]=='authcode') $authcode=$itemarr[1];
			if($itemarr[0]=='transactionid') $transactionid=$itemarr[1];
			if($itemarr[0]=='cvvresponse') $cvvresponse=$itemarr[1];
		}
		if($success){
			$do_send_emails=! already_authorized($ordID);
			ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
			ect_query("UPDATE orders SET ordStatus=3,ordAuthNumber='" . escape_string($authcode) . "',ordTransID='" . escape_string($transactionid) . "',ordCVV='".escape_string($cvvresponse)."',ordTransSession='" . escape_string($payment_token) . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<3 AND ordPayProvider=29") or ect_error();
			if($do_send_emails) do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
		}
	}
}elseif(getpayprovdetx(@$_GET['pprov']=='31'?31:23,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
	$payload=file_get_contents("php://input");
	$emailtxt.='PAYLOAD: ' . $payload . $emlNl;
	$jsarray=json_decode($payload);
	if(@$_GET['pprov']=='31'){
		$ordID=@$jsarray->{'transaction'}->{'merchantRef'};
		$signature=hash('sha256',$ordID.$adminSecret.'pay360');
		if(is_numeric($ordID)&&$signature==getget('signature')){
			$transactionid = $jsarray->{'transaction'}->{'transactionId'};
			ect_query("UPDATE orders SET ordTransID='" . escape_string($transactionid) . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<3 AND ordPayProvider=31") or ect_error();
		}
	}else{
		// No longer used for Stripe
	}
}
if(@$debugmode==TRUE){
	$emailtxt.='POST values' . $emlNl;
	foreach(@$_POST as $key=>$val){
		$emailtxt.=$key . ' : ' . $val . $emlNl;
	}
	$emailtxt.='GET values' . $emlNl;
	foreach(@$_GET as $key=>$val){
		$emailtxt.=$key . ' : ' . $val . $emlNl;
	}
	dosendemail($emailAddr, $emailAddr, '', 'stripewebhook.php debug', $emailtxt);
}
?>