<?php
/**
 * A class for generating the retry url to check if the payment status has changed.
 *
 * @since 1.0
 */

declare( strict_types=1 );
namespace FeData\FastEvents\Hooks\Shortcodes;

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Logging\LoggerFactory;


/**
 * A class for generating the retry url to check if the payment status has changed.
 */
final class RetryUrlShortcode {

	/**
	 * OrderPageShortcode constructor.
	 *
	 * @since 3.0.0
	 *
	 * @param LoggerFactory $logger Logger.
	 */
	public function __construct( private readonly LoggerFactory $logger ) {
	}


	/**
	 * Generate the retry url to check if the payment status has changed
	 *
	 * @since 1.0
	 *
	 * @return string
	 */
	public function add_retry_url(): string {
		global $wpdb;
		global $wp_query;

		// Is the url-parameter 'redirect_uid' present?
		if ( ( ! isset( $wp_query->query_vars['redirect_uid'] ) && ! isset( $wp_query->query_vars['ticket_ids'] ) ) ||
			( isset( $wp_query->query_vars['ticket_ids'] ) && ! isset( $wp_query->query_vars['hash'] ) ) ) {
			return '';
		}

		$order = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT id FROM {$wpdb->prefix}fe_event_orders WHERE uid = %s",
				sanitize_text_field( $wp_query->query_vars['redirect_uid'] )
			)
		);

		if ( null === $order ) {
			return '';
		}

		// Generate the link.
		return '<a href="' . home_url() . '/wp-json/fast-events/v1/payment/redirect/' . sanitize_text_field( $wp_query->query_vars['redirect_uid'] ) . '">' . esc_html__( 'Check payment again', 'fast-events' ) . '</a>';
	}
}
