<?php
/**
 * Meta Box Gateway Webhook Log
 *
 * @author Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license GPL-3.0-or-later
 * @package Wpayme\WordPress\Pay
 * @var string                               $gateway_id Gateway ID.
 * @var int                                  $config_id  Configuration ID.
 * @var \Wpayme\WordPress\Pay\Core\Gateway $gateway    Gateway.
 */

use Wpayme\WordPress\Pay\Plugin;
use Wpayme\WordPress\Pay\Webhooks\WebhookRequestInfo;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$wpayme_integration = wpayme_pay_plugin()->gateway_integrations->get_integration( $gateway_id );

if ( ! $wpayme_integration || ! $wpayme_integration->supports( 'webhook_log' ) ) {
	esc_html_e( 'This gateway does not support webhook logging.', 'wpayme' );

	return;
}

$wpayme_webhook_log_json_string = get_post_meta( $config_id, '_wpayme_gateway_webhook_log', true );

$wpayme_config_gateway_id = get_post_meta( $config_id, '_wpayme_gateway_id', true );

if ( empty( $wpayme_webhook_log_json_string ) || $wpayme_config_gateway_id !== $gateway_id ) {
	esc_html_e( 'No webhook request processed yet.', 'wpayme' );

	return;
}

$wpayme_object = json_decode( $wpayme_webhook_log_json_string );

try {
	$wpayme_webhook_log_request_info = WebhookRequestInfo::from_json( $wpayme_object );
} catch ( InvalidArgumentException $e ) {
	printf(
		/* translators: %s: Exception message. */
		esc_html__( 'The following error occurred when reading the webhook request information: "%s".', 'wpayme' ),
		esc_html( $e->getMessage() )
	);

	return;
}

$wpayme_payment = $wpayme_webhook_log_request_info->get_payment();

$wpayme_payment_id = ( null === $wpayme_payment ) ? null : $wpayme_payment->get_id();

if ( null !== $wpayme_payment_id ) {
	echo wp_kses(
		sprintf(
			/* translators: 1: formatted date, 2: payment edit url, 3: payment id */
			__(
				'Last webhook request processed on %1$s for <a href="%2$s" title="Payment %3$s">payment #%3$s</a>.',
				'wpayme'
			),
			$wpayme_webhook_log_request_info->get_request_date()->format_i18n( _x( 'l j F Y \a\t H:i', 'full datetime format', 'wpayme' ) ),
			esc_url( (string) get_edit_post_link( $wpayme_payment_id ) ),
			(string) $wpayme_payment_id
		),
		[
			'a' => [
				'href'  => true,
				'title' => true,
			],
		]
	);
} else {
	echo esc_html(
		sprintf(
			/* translators: %s: formatted date */
			__(
				'Last webhook request processed on %s.',
				'wpayme'
			),
			$wpayme_webhook_log_request_info->get_request_date()->format_i18n( _x( 'l j F Y \a\t H:i', 'full datetime format', 'wpayme' ) )
		)
	);
}
