<?php

declare(strict_types=1);

use Lcobucci\JWT\Encoding\CannotDecodeContent;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Token\InvalidTokenStructure;
use Lcobucci\JWT\Token\Parser;
use Lcobucci\JWT\Token\UnsupportedHeaderFound;
use Lcobucci\JWT\UnencryptedToken;

require 'vendor/autoload.php';
require_once("formsmarts_webhook_example_auth_v2_config.php");

$parser = new Parser(new JoseEncoder());

// Get Authorization header

if (! isset($_SERVER["HTTP_AUTHORIZATION"])) {
     header("HTTP/1.1 401 Unauthorized");
     fwrite("Authorization header missing.");
     die();  
}
list($scheme, $token) = explode(" ", $_SERVER["HTTP_AUTHORIZATION"], 2);
if (strcasecmp($type, "Bearer") != 0) {
     header("HTTP/1.1 401 Unauthorized");
     fwrite("Invalid Authorization header: missing Bearer token.");
     die();     
}

// Verify webhook request was sent by FormSmarts

try {
    $token = $parser->parse($token);
} catch (CannotDecodeContent | InvalidTokenStructure | UnsupportedHeaderFound $e) {
     header("HTTP/1.1 401 Unauthorized");
     fwrite("Invalid Authorization header: invalid Bearer token.");
     die();
}

// We've established the request is really originating from FormSmarts.
// We can now start to do something useful...
// Note: Do NOT insert your own code before this line!

// Log file for demonstration & debugging
$fh = fopen('/tmp/formsmarts_webhook_call.log', 'a');

$form = json_decode(file_get_contents("php://input"));
fwrite($fh, $form->{'api_version'});
fwrite($fh, $form->{'form_name'});
fwrite($fh, $form->{'fs_ref_num'});
fwrite($fh, $form->{'api_date'});

$fields = $form->{'fields'};

// iterate over all fields

foreach($fields as $field) {
  fwrite($fh, $field->{'field_name'});
  fwrite($fh, $field->{'field_value'});
  if($field->{'field_datatype'} == 'attachment') {
    fwrite($fh, $field->{'attachment_url'});
    fwrite($fh, $field->{'attachment_filename'});
  }
}

// print value ID of first field

fwrite($fh, $fields[2]->{'field_datatype'});


// print payment information, if applicable
if(array_key_exists('payment', $form)) {
  $payment = $form->{'payment'};
  fwrite($fh, $payment->{'currency'});
  fwrite($fh, $payment->{'amount'});
  fwrite($fh, $payment->{'processor_name'});
  fwrite($fh, $payment->{'processor_txn_id'});
}


// print context info, if available.

if(array_key_exists('form_context', $form)) {
fwrite($fh, $form->{'form_context'}->{'formsmarts_ctx_label'});
fwrite($fh, $form->{'form_context'}->{'formsmarts_ctx_value'});
}

fclose($fh);
?>
