<?php

	// SendGrid Webhooks
	// https://sendgrid.com/docs/for-developers/tracking-events/getting-started-event-webhook/
	// https://sendgrid.com/docs/for-developers/tracking-events/event/


	// use with the FileMaker Data API
	// requires FileMaker Server v17 or later with the Data API enabled


	// modify error reporting to not generate deprecated warnings if using PHP 5.3 or higher
	if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
	error_reporting(E_ALL & ~ E_DEPRECATED & ~ E_USER_DEPRECATED & ~E_NOTICE & ~E_STRICT);
	} else {
	error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
	}


	// replace with FileMaker Server DNS name
	//$hostname = $_GET["sdns"];
	//$database = $_GET["db"];
	//$hostname = 'developer.littleman.com.au';
	//$database = 'Webhook';
	$username = 'LMWebhook';
	$password = 'W3bH00kRul32019';
	//$layout = 'Webhooks';
	$layout = '_JSONdata';
	// Set the default timezone
	date_default_timezone_set('Australia/Sydney');

	$event = null;

	$payload = @file_get_contents('php://input');
	$event= json_decode( $payload, FALSE ); //convert JSON into array


	$hostname = $event->hostname;
	$database = $event->databasename;
	$scriptname = $event->scriptname;


	//LOGIN

	$url = "https://" . $hostname . "/fmi/data/v1/databases/" . rawurlencode($database) . '/sessions';
			//echo $url;
	$ch = curl_init();
	//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);         //follow redirects
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);         //return the transfer as a string
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);         //don't verify SSL CERT
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);         //don't verify SSL CERT
	curl_setopt($ch, CURLOPT_VERBOSE, 1);
	curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); 		 //Don'T use cache
	curl_setopt ($ch, CURLOPT_HTTPHEADER, array (
						'Content-Type: '. 'application/json',
				 		'Authorization: Basic ' . base64_encode ($username . ':' . $password)
				 	));
	curl_setopt($ch, CURLOPT_POSTFIELDS, '{}');
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
	curl_setopt($ch, CURLOPT_URL, $url);


	$result = curl_exec ($ch);
	$error = curl_error ($ch);
	$info = curl_getinfo($ch);

	curl_close($ch);

	$loginResultArray = json_decode ($result, true);

	//echo $loginResultArray;

	//echo '<pre>';print_r ($loginResultArray);echo '</pre>';

	// Check for Error Message
	$errorCode = $loginResultArray['messages'][0]['code'];
	$errorMessage = $loginResultArray['messages'][0]['message'];

	//echo '$errorCode: '.$errorCode.'<br>';
	//echo '$errorMessage: '.$errorMessage.'<br>';

	if ($errorCode !== '0') {
		// Login Error
		$errorResult = 'Login Error: '. $errorMessage. ' (' . $errorCode . ')';
		echo $errorResult;
		die;
	} else {
		$errorResult = '';
		$token = $loginResultArray['response']['token'];
		// echo '$token: '.$token.'<br>';
	}

	$event = null;

	$payload = @file_get_contents('php://input');
	$event= json_decode( $payload, FALSE ); //convert JSON into array

	echo $payload;
	// error_log('$payload', 0);
	// error_log($event, 0);


	// Generate UUID
	$uuid = uniqid();
	$uuid = md5($uuid);

	// CREATE RECORD IN WEBHOOKS TABLE WITH JSON DATA
	//$record['WebhookJSON'] = $payload;
	$record['JSONdata'] = $payload;
	$record['_ID JSON'] = $uuid;

	$data['fieldData'] =  $record;

	echo $data;

	// FileMaker Script data
	$arr = array('script' => $scriptname , 'script.param' => $uuid);
	//$arr = array('script' => 'createEventsFromWebhook', 'script.param' => $uuid);
	$data_json = json_encode (array_merge($data, $arr));


	/*
	function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}
*/
//$data_json = json_encode (get_client_ip());

//echo '<p>'$data_json'</p>';

	//print_r($data_json);


	$url = "https://" . $hostname . "/fmi/data/v1/databases/" . rawurlencode($database) . '/layouts/'. rawurlencode($layout) . '/records';

	$ch = curl_init();
	//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);         //follow redirects
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);         //return the transfer as a string
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);         //don't verify SSL CERT
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);         //don't verify SSL CERT
	curl_setopt($ch, CURLOPT_VERBOSE, 1);
	curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); 		 //Don't use cache
	curl_setopt ($ch, CURLOPT_HTTPHEADER, array (
						'Content-Type: '. 'application/json',
				 		'Authorization: Bearer '. $token
				 	));
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
	curl_setopt($ch, CURLOPT_URL, $url);


	$createRecordResult = curl_exec ($ch);
	$error = curl_error ($ch);
	$info = curl_getinfo ($ch);

	curl_close($ch);



	$createRecordResultArray = json_decode ($createRecordResult, true);

	//echo '<p><pre>'.print_r($createRecordResultArray).'</pre></p>';

	// Check for Error Message
	$errorCode = $createRecordResultArray['messages'][0]['code'];
	$errorMessage = $createRecordResultArray['messages'][0]['message'];

	echo '$errorCode: '.$errorCode.'<br>';
	echo '$errorMessage: '.$errorMessage.'<br>';

	if ($errorCode !== '0') {
		// Login Error
		$errorResult = 'Create Record Error: '. $errorMessage. ' (' . $errorCode . ')';
		echo $errorResult;
		die;
	} else {
		$errorResult = '';
		$newRecordID = $createRecordResultArray['response']['recordId'];
		// echo '$newRecordID: '.$newRecordID.'<br>';
	}


	// LOGOUT

	$url = "https://" . $hostname . "/fmi/data/v1/databases/" . rawurlencode($database) . '/sessions/'. $token;

	$ch = curl_init();
	//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);         //follow redirects
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);         //return the transfer as a string
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);         //don't verify SSL CERT
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);         //don't verify SSL CERT
	curl_setopt($ch, CURLOPT_VERBOSE, 1);
	curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); 		 //Don'T use cache
	curl_setopt ($ch, CURLOPT_HTTPHEADER, array (
						'Content-Type: '. 'application/json'
									 	));
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
	curl_setopt($ch, CURLOPT_URL, $url);


	$logoutResult = curl_exec ($ch);
	$error = curl_error ($ch);
	$info = curl_getinfo ($ch);

	curl_close($ch);



	$logoutResultArray = json_decode ($logoutResult, true);


	//echo '<p><pre>'.print_r($logoutResultArray).'</pre></p>';

	// Check for Error Message
	$errorCode = $logoutResultArray['messages'][0]['code'];
	$errorMessage = $logoutResultArray['messages'][0]['message'];

	//echo '$errorCode: '.$errorCode.'<br>';
	//echo '$errorMessage: '.$errorMessage.'<br>';

	if ($errorCode !== '0') {
		// Login Error
		$errorResult = 'Logout Error: '. $errorMessage. ' (' . $errorCode . ')';
		echo $errorResult;
		die;
	} else {
		$errorResult = '';
	}


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <title>
            Stripe Event Received
        </title>

</head>
    <body>

    <?php echo $displayResult ;?>

    </body>
</html>
