<?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);
	}
	
	$version = 'vLatest'; 
	$fmversion = 18;
	
	/* uncomment the following two lines when working with FileMaker 17 Server/FileMaker Cloud 17 */
	// $fm -> version = "v1";
	// $fm -> fmversion = 17;
		
	// replace with FileMaker Server DNS name
	
	$username = 'Webhook';
	$password = 'Webhook';
	$username = 'LMWebhook';
	$password = 'W3bH00kRul32019';
	$layout = '_JSONData';
	
	// Set the default timezone
	date_default_timezone_set('Australia/Sydney');
		
	$event = null;
	
	$payload = @file_get_contents('php://input');
	$events= json_decode( $payload, FALSE ); //convert JSON into array
	
	// error_log('$payload', 0);
	// error_log($events, 0);
	
	
	// Loop through each Event and make Data API Calls
	
	foreach($events as $event){
		
		$eventJSON = json_encode($event) ;
		
		$database = $event->databasename;
		$hostname = $event->hostname;
		$scriptname = $event->scriptname;
		
		//echo '$database: '.$databaseName.'<br>';
		//echo '$hostname: '.$hostname.'<br>';
		//echo '$scriptname: '.$scriptname.'<br>';
		
		// Check that all required parameters are set, and skip if not
		if (isset($database) && $database !== '' && isset($hostname) && $hostname == !'' && isset($scriptname) && $scriptname == !'')  {
		
		
			//LOGIN
			$url = 'https://' . $hostname . '/fmi/data/' . $version . '/databases/' . rawurlencode($database) . '/sessions';	
						 						
			$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 '<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>';
			}
			
			
			// Generate UUID
			$uuid = uniqid();
			$uuid = md5($uuid);
			
			// CREATE RECORD IN WEBHOOKS TABLE WITH JSON DATA
			$record['JSONdata'] = $eventJSON;
			$record['_ID JSON'] = $uuid;
			
			$data['fieldData'] =  $record;
			
			// FileMaker Script data
			$arr = array('script' => $scriptname, 'script.param' => $uuid);
			
			$data_json = json_encode (array_merge($data, $arr));
			
			//print_r($data_json);
			
			
			$url = 'https://' . $hostname . '/fmi/data/' . $version . '/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>';
			}

		} // end check for required parameters (database, hostname, scriptname)
				
			
	$recnum++; }
	
	
	
?>
<!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>
            Webhook Event Processing
        </title>

</head>
    <body>
    
    <?php echo $errorResult ;?>
    
    </body>
</html>