<?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;
$GLOBALS['isectadmin']=TRUE;
include 'db_conn_open.php';
include 'inc/languagefile.php';
include 'includes.php';
include 'inc/incemail.php';
include 'inc/incfunctions.php';

$verification_status='';
$transmission_id=@$_SERVER['HTTP_PAYPAL_TRANSMISSION_ID'];
$transmission_time=@$_SERVER['HTTP_PAYPAL_TRANSMISSION_TIME']; // 2016-02-18T20:01:35Z",
$cert_url=@$_SERVER['HTTP_PAYPAL_CERT_URL']; // cert_url",
$auth_algo=@$_SERVER['HTTP_PAYPAL_AUTH_ALGO']; // SHA256withRSA",
$transmission_sig=@$_SERVER['HTTP_PAYPAL_TRANSMISSION_SIG']; // lmI95Jx3Y9nhR5SJWlHVIWpg4AgFk7n9bCHSRxbrd8A9zrhdu2rMyFrmz+Zjh3s3boXB07VXCXUZy/UFzUlnGJn0wDugt7FlSvdKeIJenLRemUxYCPVoEZzg9VFNqOa48gMkvF+XTpxBeUx/kWy6B5cp7GkT2+pOowfRK7OaynuxUoKW3JcMWw272VKjLTtTAShncla7tGF+55rxyt2KNZIIqxNMJ48RDZheGU5w1npu9dZHnPgTXB9iomeVRoD8O/jhRpnKsGrDschyNdkeh81BJJMH4Ctc6lnCCquoP/GzCzz33MMsNdid7vL/NIWaCsekQpW26FpWPi/tfj8nLA==",
$webhook_id='';

function vr_json_encode($tval){
	return '"' . $tval . '"';
}

function dogetallheaders(){
	$allheaders=getallheaders();
	$outtxt='';
	foreach($allheaders as $key => $val){
		$outtxt.=$key . ' : ' . $val . "\r\n";
	}
	return $outtxt;
}
if(getpayprovdetx(27,$data1,$data2,$data3,$data4,$webhook_id,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
	$bodyReceived = file_get_contents('php://input');
	$requestxx='{
		"transmission_id":' . vr_json_encode($transmission_id) . ',
		"transmission_time":' . vr_json_encode($transmission_time) . ',
		"cert_url":' . vr_json_encode($cert_url) . ',
		"auth_algo":' . vr_json_encode($auth_algo) . ',
		"transmission_sig":' . vr_json_encode($transmission_sig) . ',
		"webhook_id":' . vr_json_encode($webhook_id) . ',
		"webhook_event":' . $bodyReceived . '
	}';
	if($access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
		$GLOBALS['xmlfnheaders']=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
		if(callcurlfunction('https://api.' . ($demomode?'sandbox.':'') . 'paypal.com/v1/notifications/verify-webhook-signature',$requestxx,$jres,'',$errormsg,FALSE)){
			$jsarray=json_decode($jres);
			$verification_status=@$jsarray->{'verification_status'};
		}
	}
	$alreadygotadmin=getadminsettings();
	if(@$debugmode==TRUE){
		$emailtxt='bodyReceived: ' . $bodyReceived;
		dosendemail($emailAddr, $emailAddr, '', 'ppwebhook.php debug', $emailtxt);
	}
	/* TMP : Waiting for feedback from PayPal */
	if( TRUE || $verification_status=='SUCCESS'){
		$jsarray=json_decode($bodyReceived);
		$tid=@$jsarray->{'id'};
		$xmlfnuser=$data1;
		$xmlfnpassword=$data2;
		if(callcurlfunction('https://api.' . ($demomode?'sandbox.':'') . 'paypal.com/v1/notifications/webhooks-events/' . $tid,'',$jres,'',$errormsg,FALSE)){
			$jsarray=json_decode($jres);
			$newid=@$jsarray->{'id'};

			if($tid==$newid){
				$event_type=@$jsarray->{'event_type'};
				switch($event_type){
				case 'PAYMENT.CAPTURE.COMPLETED':
					$ordtransid=@$jsarray->{'resource'}->{'supplementary_data'}->{'related_ids'}->{'order_id'};
					$sSQL="SELECT ordID FROM orders WHERE ordDate>'" . date('Y-m-d',time()-(365*24*60*60)) . "' AND ordTransID='" . escape_string($ordtransid) . "'";
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result)){
						$sSQL="UPDATE orders SET ordAuthStatus='' WHERE ordID='" . escape_string($rs['ordID']) . "'";
						ect_query($sSQL) or ect_error();
					}
					ect_free_result($result);
				break;
				case 'PAYMENT.CAPTURE.DENIED':
				break;
				case 'PAYMENT.CAPTURE.REVERSED':
				case 'PAYMENT.CAPTURE.REFUNDED':
					$tlinks=@$jsarray->{'resource'}->{'links'};
					$amount=@$jsarray->{'resource'}->{'amount'}->{'value'};
					if(is_array($tlinks)){
						for($index=0;$index<count($tlinks);$index++){
							if($tlinks[$index]->{'rel'}=='up') $tcapture=$tlinks[$index]->{'href'};
						}
						if($access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
							$GLOBALS['xmlfnheaders']=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
							if(callcurlfunction($tcapture,'',$jres,'',$errormsg, FALSE)){
								$jsarray=json_decode($jres);
								$ordtransid=@$jsarray->{'resource'}->{'supplementary_data'}->{'related_ids'}->{'order_id'};
								if($ordtransid=='') $ordtransid=@$jsarray->{'supplementary_data'}->{'related_ids'}->{'order_id'};
								if($ordtransid!=''){
									$sSQL="SELECT ordID FROM orders WHERE ordDate>'" . date('Y-m-d',time()-(365*24*60*60)) . "' AND ordTransID='" . escape_string($ordtransid) . "'";
									$result=ect_query($sSQL) or ect_error();
									if($rs=ect_fetch_assoc($result)){
										$sSQL="UPDATE orders SET ordStatus=0,ordAuthStatus='' WHERE ordID='" . escape_string($rs['ordID']) . "' AND '" . escape_string($amount) . "'>=((ordShipping+ordStateTax+ordCountryTax+ordHSTTax+ordTotal+ordHandling)-ordDiscount)";
										ect_query($sSQL) or ect_error();
									}
									ect_free_result($result);
								}
							}
						}
					}
				break;
				case 'PAYMENT.CAPTURE.PENDING':
				break;
				case 'CHECKOUT.ORDER.COMPLETED':
				break;
				case 'CHECKOUT.ORDER.APPROVED':
				break;
				case 'CHECKOUT.ORDER.PROCESSED':
				break;
				case 'PAYMENT.AUTHORIZATION.CREATED':
				break;
				case 'PAYMENT.AUTHORIZATION.VOIDED':
				break;
				}
			}
		}
	}
}

?>