<?php
declare(strict_types=1);

// Requires PHP 8.1+ and: composer require lcobucci/jwt lcobucci/clock

use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Encoding\CannotDecodeContent;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Token\InvalidTokenStructure;
use Lcobucci\JWT\Token\Parser;
use Lcobucci\JWT\Token\UnsupportedHeaderFound;
use Lcobucci\JWT\Validation\Constraint\IssuedBy;
use Lcobucci\JWT\Validation\Constraint\LooseValidAt;
use Lcobucci\JWT\Validation\Constraint\PermittedFor;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Lcobucci\JWT\Validation\Validator;

require 'vendor/autoload.php';
require_once 'formsmarts_webhook_example_auth_v2_config.php';

function reject(string $reason): never
{
    http_response_code(401);
    error_log("FormSmarts webhook rejected: $reason");
    exit;
}

// Get the bearer token from the Authorization header
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$parts = explode(' ', $header, 2);
if (count($parts) !== 2 || strcasecmp($parts[0], 'Bearer') !== 0) {
    reject('Authorization header missing or invalid.');
}

// Verify the request was sent by FormSmarts: the token must be signed with your Webhook Key,
// issued by FormSmarts for a webhook, and not expired.
try {
    $token = (new Parser(new JoseEncoder()))->parse($parts[1]);
    (new Validator())->assert(
        $token,
        new SignedWith(new Sha256(), InMemory::plainText(FORMSMARTS_WEBHOOK_KEY)),
        new IssuedBy('formsmarts.com'),
        new PermittedFor('webhook'),
        new LooseValidAt(SystemClock::fromSystemTimezone(), new DateInterval('PT5S'))
    );
} catch (CannotDecodeContent | InvalidTokenStructure | UnsupportedHeaderFound | RequiredConstraintsViolated $e) {
    reject($e->getMessage());
}

// The request is from FormSmarts: process the form response.
// Note: don't use the request's data before this line!
$form = json_decode(file_get_contents('php://input'));

// Log file for demonstration & debugging
$fh = fopen('/tmp/formsmarts_webhook_call.log', 'a');
fwrite($fh, "{$form->form_name} ({$form->form_id}): {$form->fs_ref_num}, {$form->api_date}\n");

// Iterate over the fields, in the order they appear on the form
foreach ($form->fields as $field) {
    fwrite($fh, "{$field->field_name} ({$field->field_datatype}): {$field->field_value}\n");
    // Form attachments have additional properties (field_value is empty)
    if ($field->field_datatype === 'attachment') {
        fwrite($fh, "{$field->attachment_filename}: {$field->attachment_url}\n");
    }
}

// Payment information, if applicable
if (isset($form->payment)) {
    $pay = $form->payment;
    fwrite($fh, "Paid {$pay->amount} {$pay->currency} with {$pay->processor_name}: {$pay->transaction_id}\n");
}

// Form context, if available
if (isset($form->context)) {
    fwrite($fh, "Context {$form->context->label}: {$form->context->value}\n");
}

fclose($fh);
