<?php
/**
 * PHP render for Donation Form Block.
 *
 * @package SureDonation
 * @since 0.0.1
 */

namespace SureDonation\Inc\Blocks\Donation_Form;

use SureDonation\Inc\Blocks\Base;
use SureDonation\Inc\Helper;
use SureDonation\Inc\Post_Types\Donation_Form;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Donation Form Block.
 *
 * @since 0.0.1
 */
class Block extends Base {
	/**
	 * Render the block
	 *
	 * @param array<string, mixed> $attributes Block attributes.
	 * @param string               $content    Block content.
	 * @return string
	 * @since 0.0.1
	 */
	public function render( $attributes, $content = '' ) {
		unset( $content ); // Unused parameter.

		if ( empty( $attributes ) ) {
			return '';
		}

		// A custom form is required.
		$form_id = isset( $attributes['formId'] ) ? absint( Helper::get_string_value( $attributes['formId'] ) ) : 0;

		if ( ! $form_id ) {
			// Show message only to users who can edit posts.
			if ( current_user_can( 'edit_posts' ) ) {
				return '<div class="suredonation-notice">' . esc_html__( 'Please select a donation form in the block settings.', 'suredonation' ) . '</div>';
			}
			return '';
		}

		return $this->render_custom_form( $form_id, $attributes );
	}

	/**
	 * Render a custom donation form.
	 *
	 * @param int                  $form_id    Form post ID.
	 * @param array<string, mixed> $attributes Block attributes.
	 * @return string
	 * @since 0.0.1
	 */
	private function render_custom_form( $form_id, $attributes ) {
		// Get the form post.
		$form = get_post( $form_id );
		if ( ! $form instanceof \WP_Post || Donation_Form::POST_TYPE !== $form->post_type ) {
			return '<div class="suredonation-notice">' . esc_html__( 'Invalid form selected.', 'suredonation' ) . '</div>';
		}

		// Check if form is published.
		if ( 'publish' !== $form->post_status ) {
			return '<div class="suredonation-notice">' . esc_html__( 'This form is not available.', 'suredonation' ) . '</div>';
		}

		// Get the campaign ID from block attributes or form meta.
		$campaign_id = isset( $attributes['campaignId'] ) ? absint( Helper::get_string_value( $attributes['campaignId'] ) ) : 0;
		if ( ! $campaign_id ) {
			$campaign_id = Donation_Form::get_form_campaign_id( $form_id );
		}

		// Validate campaign if set.
		if ( $campaign_id ) {
			$campaign = get_post( $campaign_id );
			if ( ! $campaign instanceof \WP_Post || SUREDONATION_POST_TYPE !== $campaign->post_type ) {
				return '<div class="suredonation-notice">' . esc_html__( 'Invalid campaign selected.', 'suredonation' ) . '</div>';
			}

			// Check campaign status.
			$campaign_status = Helper::get_campaign_meta_value( $campaign_id, 'campaign_status', 'active' );
			if ( 'paused' === $campaign_status || 'completed' === $campaign_status ) {
				return '<div class="suredonation-notice">' . esc_html__( 'This campaign is not currently accepting donations.', 'suredonation' ) . '</div>';
			}
		}

		// Enqueue frontend styles for custom form blocks.
		// Note: Frontend JS is handled by the payment block (form-frontend.js).
		wp_enqueue_style( 'suredonation-donation-form' );

		// Get form settings from post meta.
		$confirmation_type = get_post_meta( $form_id, '_suredonation_form_confirmationType', true );
		$success_message   = get_post_meta( $form_id, '_suredonation_form_successMessage', true );
		$redirect_url      = get_post_meta( $form_id, '_suredonation_form_redirectUrl', true );

		// Set defaults.
		$confirmation_type = ! empty( $confirmation_type ) ? $confirmation_type : 'message';
		$success_message   = ! empty( $success_message ) ? $success_message : esc_html__( 'Thank you for your donation!', 'suredonation' );

		// Pass form settings to frontend via inline script.
		// Using wp_add_inline_script to ensure settings are available.
		$form_settings = wp_json_encode(
			[
				'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
				'nonce'            => wp_create_nonce( 'suredonation_payment_nonce' ),
				'confirmationType' => $confirmation_type,
				'successTitle'     => esc_html__( 'Thank You!', 'suredonation' ),
				'successMessage'   => wp_kses_post( Helper::get_string_value( $success_message ) ),
				'redirectUrl'      => ! empty( $redirect_url ) ? esc_url( Helper::get_string_value( $redirect_url ) ) : '',
			]
		);
		wp_add_inline_script( 'suredonation-form-frontend', "window.suredonationPayment = {$form_settings};", 'before' );

		// Get the form content (blocks).
		$form_content = $form->post_content;

		// Generate unique form ID.
		$unique_form_id = 'suredonation-form-' . $form_id . '-' . wp_rand();

		// Get primary color from block attributes.
		$primary_color = isset( $attributes['primaryColor'] ) && is_string( $attributes['primaryColor'] )
			? $attributes['primaryColor']
			: '#10b981';

		// Parse blocks from form content.
		$blocks = parse_blocks( $form_content );

		// Render form wrapper with blocks.
		ob_start();
		?>
		<div id="<?php echo esc_attr( $unique_form_id ); ?>" class="sd-form-container" data-form-id="<?php echo esc_attr( (string) $form_id ); ?>" data-campaign-id="<?php echo esc_attr( (string) $campaign_id ); ?>" style="--sd-primary-color: <?php echo esc_attr( $primary_color ); ?>">
			<form class="sd-form" method="post">
				<?php
				$nonce_action = $campaign_id ? 'suredonation_donation_' . $campaign_id : 'suredonation_donation_standalone';
				wp_nonce_field( $nonce_action, 'suredonation_nonce' );
				?>
				<input type="hidden" name="form_id" value="<?php echo esc_attr( (string) $form_id ); ?>">
				<input type="hidden" name="campaign_id" value="<?php echo esc_attr( (string) $campaign_id ); ?>">
				<input type="hidden" name="action" value="suredonation_submit_donation">

				<?php
				// Render each block.
				foreach ( $blocks as $block ) {
					if ( ! empty( $block['blockName'] ) ) {
						echo wp_kses( render_block( $block ), self::get_allowed_form_html() );
					}
				}
				?>
			</form>
			<!-- Success Message Container -->
			<div class="sd-single-form sd-success-box">
				<div aria-live="polite" aria-atomic="true" role="alert" id="sd-success-message-<?php echo esc_attr( (string) $form_id ); ?>" class="sd-success-box-description"></div>
			</div>
		</div>
		<?php
		$output = ob_get_clean();
		return false !== $output ? $output : '';
	}
}
