<?php
/**
 * Donation Confirmation Block
 *
 * Renders a thank-you message and a back link to the fundraiser after a PSP
 * payment flow completes. Place this block on the page configured as the
 * "Post-payment redirect page" in AmbassadorHub → Settings → General.
 *
 * The block reads ?donation_id=X from the URL, resolves the linked fundraiser,
 * and outputs the confirmation UI. It renders nothing when no valid donation_id
 * is present so it is safe to leave on a generic page.
 *
 * @package AmbassadorHub\Fundraisers\Blocks\DonationConfirmation
 */

namespace AmbassadorHub\Fundraisers\Blocks\DonationConfirmation;

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

use AmbassadorHub\Donations\DonationsModule;
use AmbassadorHub\Tracking\DataLayerQueue;

/**
 * Donation Confirmation block registration and rendering.
 */
final class Block {

	/**
	 * Initialize the block.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'init', array( self::class, 'register_block' ) );
	}

	/**
	 * Register the block.
	 *
	 * @return void
	 */
	public static function register_block(): void {
		$block_dir = AMBASSADOR_HUB_PATH . 'src/Fundraisers/Blocks/DonationConfirmation/';
		$block_url = AMBASSADOR_HUB_URL . 'src/Fundraisers/Blocks/DonationConfirmation/';

		// Register editor script.
		$handle      = 'ambh-donation-confirmation-block';
		$script_file = $block_dir . 'index.js';
		if ( file_exists( $script_file ) ) {
			wp_register_script(
				$handle,
				$block_url . 'index.js',
				array( 'wp-blocks', 'wp-element' ),
				filemtime( $script_file ),
				true
			);
		}

		// Register frontend styles.
		wp_register_style(
			'ambh-donation-confirmation',
			$block_url . 'style.css',
			array(),
			AMBASSADOR_HUB_VERSION
		);

		$block_args = array(
			'style'           => 'ambh-donation-confirmation',
			'render_callback' => array( self::class, 'render_block' ),
		);

		if ( file_exists( $script_file ) ) {
			$block_args['editor_script'] = $handle;
		}

		register_block_type( $block_dir, $block_args );

		// Shortcode alias so the admin can also paste [donation_confirmation].
		add_shortcode( 'ambh_donation_confirmation', array( self::class, 'render_shortcode' ) );
	}

	/**
	 * Render the block.
	 *
	 * @param array $attributes Block attributes (unused — block has no settings).
	 * @return string Block HTML.
	 */
	public static function render_block( array $attributes = array() ): string { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found -- required by block render_callback signature.
		// Editor / server-side preview placeholder.
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return '<div style="padding: 20px; background: #f0f0f1; border: 1px solid #ddd; text-align: center;">'
				. esc_html__( 'Donation confirmation', 'ambassadorhub' )
				. '</div>';
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only, public GET param.
		$donation_id = isset( $_GET['donation_id'] ) ? absint( $_GET['donation_id'] ) : 0;

		if ( ! $donation_id ) {
			return '';
		}

		$donation = DonationsModule::get( $donation_id );

		if ( ! $donation ) {
			return '';
		}

		// Flush any queued dataLayer events for this donation (e.g. ambh_purchase
		// stored during an async PSP webhook when no browser session was present).
		DataLayerQueue::flush_for_donation( $donation_id );

		$fundraiser_id   = (int) $donation->fundraiser_id;
		$fundraiser_url  = get_permalink( $fundraiser_id );
		$fundraiser_name = get_the_title( $fundraiser_id );

		$donor_first = (string) ( $donation->donor_first_name ?? '' );

		$wrapper_attrs = get_block_wrapper_attributes( array( 'class' => 'ambh-donation-confirmation' ) );

		ob_start();
		?>
		<div <?php echo $wrapper_attrs; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- sanitized by get_block_wrapper_attributes(). ?>>
			<div class="ambh-donation-confirmation__icon" aria-hidden="true">&#10003;</div>

			<h2 class="ambh-donation-confirmation__title">
				<?php
				if ( $donor_first ) {
					echo esc_html(
						sprintf(
							/* translators: %s: donor first name */
							__( 'Thank you, %s!', 'ambassadorhub' ),
							$donor_first
						)
					);
				} else {
					esc_html_e( 'Thank you for your donation!', 'ambassadorhub' );
				}
				?>
			</h2>

			<p class="ambh-donation-confirmation__message">
				<?php esc_html_e( 'Your donation has been received and is being processed. You will receive a confirmation by email.', 'ambassadorhub' ); ?>
			</p>

			<?php if ( $fundraiser_url && $fundraiser_name ) : ?>
				<p class="ambh-donation-confirmation__back">
					<a href="<?php echo esc_url( $fundraiser_url ); ?>" class="ambh-donation-confirmation__back-link">
						&larr; 
						<?php
						echo esc_html(
							sprintf(
								/* translators: %s: fundraiser name */
								__( 'Back to %s', 'ambassadorhub' ),
								$fundraiser_name
							)
						);
						?>
					</a>
				</p>
			<?php endif; ?>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Render shortcode alias.
	 *
	 * @return string
	 */
	public static function render_shortcode(): string {
		return self::render_block( array() );
	}
}
