<?php
/**
 * Donation Form Shortcode
 *
 * Renders a donation form via shortcode [suredonation_form id="123"]
 *
 * @package SureDonation
 * @since 0.0.1
 */

namespace SureDonation\Inc\Shortcodes;

use SureDonation\Inc\Helper;
use SureDonation\Inc\Post_Types\Donation_Form as Donation_Form_CPT;
use SureDonation\Inc\Traits\Get_Instance;

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

/**
 * Donation_Form shortcode class.
 *
 * @since 0.0.1
 */
class Donation_Form {
	use Get_Instance;

	/**
	 * Constructor.
	 *
	 * @since 0.0.1
	 */
	public function __construct() {
		add_shortcode( 'suredonation_form', [ $this, 'render_shortcode' ] );
	}

	/**
	 * Render the donation form shortcode.
	 *
	 * @param array<string, mixed> $atts Shortcode attributes.
	 * @return string Form HTML.
	 * @since 0.0.1
	 */
	public function render_shortcode( $atts ) {
		$atts = shortcode_atts(
			[
				'id' => 0,
			],
			$atts,
			'suredonation_form'
		);

		$form_id = absint( $atts['id'] );

		if ( ! $form_id ) {
			if ( current_user_can( 'edit_posts' ) ) {
				return '<p class="suredonation-error">' . esc_html__( 'Please specify a form ID: [suredonation_form id="123"]', 'suredonation' ) . '</p>';
			}
			return '';
		}

		// Get the form post.
		$form = get_post( $form_id );

		if ( ! $form || Donation_Form_CPT::POST_TYPE !== $form->post_type ) {
			if ( current_user_can( 'edit_posts' ) ) {
				return '<p class="suredonation-error">' . esc_html__( 'Invalid donation form ID.', 'suredonation' ) . '</p>';
			}
			return '';
		}

		if ( 'publish' !== $form->post_status && ! current_user_can( 'edit_posts' ) ) {
			return '';
		}

		// Enqueue frontend assets.
		$this->enqueue_assets();

		// Render the form.
		return $this->render_form( $form );
	}

	/**
	 * Render the form HTML.
	 *
	 * @param \WP_Post $form Form post object.
	 * @return string Form HTML.
	 * @since 0.0.1
	 */
	private function render_form( $form ) {
		$form_id     = $form->ID;
		$campaign_id = Donation_Form_CPT::get_form_campaign_id( $form_id );

		// Parse the form content (blocks).
		$blocks = parse_blocks( $form->post_content );

		// Render blocks.
		$blocks_html = '';
		foreach ( $blocks as $block ) {
			if ( ! empty( $block['blockName'] ) ) {
				// Add form ID to block attributes.
				$block['attrs']['formId'] = $form_id;
				$blocks_html             .= render_block( $block );
			}
		}

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

		// Nonce action based on campaign.
		$nonce_action = $campaign_id ? 'suredonation_donation_' . $campaign_id : 'suredonation_donation_standalone';

		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 ); ?>">
			<form class="sd-form" method="post">
				<?php 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
				echo wp_kses( $blocks_html, Helper::get_allowed_form_html() );
				?>
			</form>

			<!-- Success message container (hidden by default, shown after successful donation) -->
			<div class="sd-success-box" style="display: none;">
				<div class="sd-success-box-description"></div>
			</div>
		</div>
		<?php
		return (string) ob_get_clean();
	}

	/**
	 * Enqueue frontend assets.
	 *
	 * @return void
	 * @since 0.0.1
	 */
	private function enqueue_assets() {
		// Enqueue frontend styles.
		wp_enqueue_style(
			'suredonation-form',
			SUREDONATION_URL . 'assets/css/form.css',
			[],
			SUREDONATION_VER
		);

		// Enqueue frontend scripts.
		wp_enqueue_script(
			'suredonation-form',
			SUREDONATION_URL . 'assets/build/form-frontend.js',
			[],
			SUREDONATION_VER,
			true
		);

		// Localize script with payment and success message configuration.
		wp_localize_script(
			'suredonation-form',
			'suredonationPayment',
			[
				'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
				'nonce'            => wp_create_nonce( 'suredonation_payment_nonce' ),
				'confirmationType' => 'message', // Default to showing message. Could be 'redirect' in future.
				'redirectUrl'      => '',
				'successTitle'     => __( 'Thank You!', 'suredonation' ),
				'successMessage'   => __( 'Your donation has been processed successfully. A confirmation email will be sent to you shortly.', 'suredonation' ),
			]
		);

		// Enqueue Stripe.js if Stripe is configured.
		$this->maybe_enqueue_stripe();
	}

	/**
	 * Enqueue Stripe.js if Stripe is configured.
	 *
	 * @return void
	 * @since 0.0.1
	 */
	private function maybe_enqueue_stripe() {
		if ( ! class_exists( 'SureDonation\Inc\Payments\Stripe\Stripe_Helper' ) ) {
			return;
		}

		$publishable_key = \SureDonation\Inc\Payments\Stripe\Stripe_Helper::get_stripe_publishable_key();

		if ( ! empty( $publishable_key ) ) {
			wp_enqueue_script(
				'stripe-js',
				'https://js.stripe.com/v3/',
				[],
				null, // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- External script.
				true
			);
		}
	}
}
