<?php
/**
 * Shortcode to display the form
 */

function gti_forms_shortcode( $atts ) {
	$atts = shortcode_atts( array(
		'id' => 0,
	), $atts );

	$form_id = intval( $atts['id'] );
	if ( ! $form_id ) {
		return __( 'フォームIDを指定してください。', 'gti-forms' );
	}

	$post = get_post( $form_id );
	if ( ! $post || $post->post_type !== 'gti-form' ) {
		return __( 'フォームが見つかりません。', 'gti-forms' );
	}

	// Handle completion screen via URL
	if ( isset($_GET['gti_step']) && $_GET['gti_step'] === 'thanks' ) {
		$thanks_msg = get_post_meta( $form_id, '_gti_thanks_message', true );
		if ( ! $thanks_msg ) {
			$thanks_msg = __( 'お問い合わせありがとうございました。送信が完了いたしました。', 'gti-forms' );
		}
		$thanks_msg = apply_filters( 'gti_forms_thanks_message', $thanks_msg, $form_id );
		return '<div class="gti-form-container gti-thanks-screen"><div class="gti-form-response success" style="display:block;">' . wp_kses_post( nl2br( $thanks_msg ) ) . '</div></div>';
	}

	wp_enqueue_script( 'jquery' ); // Ensure jQuery is loaded

	$blocks = parse_blocks( $post->post_content );
	
	ob_start();
	?>
	<div class="gti-form-container" id="gti-form-<?php echo $form_id; ?>">
		<form class="gti-ajax-form" action="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>" method="post">
			<input type="hidden" name="action" value="gti_forms_submit">
			<input type="hidden" name="form_id" value="<?php echo $form_id; ?>">
			<input type="hidden" name="mode" id="gti-form-mode" value="confirm"> <!-- Default to confirm mode -->
			<?php wp_nonce_field( 'gti_forms_action', 'gti_forms_nonce' ); ?>
			<?php do_action( 'gti_forms_extra_hidden_fields', $form_id ); ?>

			<div class="gti-form-inputs-wrapper">
				<?php 
				do_action( 'gti_forms_before_fields', $form_id );
				do_action( 'gti_forms_extra_form_fields', $form_id );
				foreach ( $blocks as $block ) {
					if ( isset($block['blockName']) && ($block['blockName'] === 'gti/form-submit' || $block['blockName'] === 'gti/form-stripe') ) {
						continue;
					}
					echo gti_forms_render_block( $block, $form_id );
				}
				?>
			</div>
			<div class="gti-form-actions-wrapper">
				<?php 
				foreach ( $blocks as $block ) {
					if ( isset($block['blockName']) && ($block['blockName'] !== 'gti/form-submit' && $block['blockName'] !== 'gti/form-stripe') ) {
						continue;
					}
					echo gti_forms_render_block( $block, $form_id );
				}
				do_action( 'gti_forms_after_fields', $form_id );
				?>
			</div>
			<div class="gti-form-response"></div>
		</form>
	</div>
	<?php
	return ob_get_clean();
}
add_shortcode( 'gti_form', 'gti_forms_shortcode' );

/**
 * Add footer scripts for GTI Forms.
 */
function gti_forms_add_footer_scripts() {
	// Only output script if a form is present on the page.
	// This is a simple check, a more robust solution might involve a global flag set by the shortcode.
	if ( ! has_shortcode( get_the_content(), 'gti_form' ) && ! is_singular( 'gti-form' ) ) {
		return;
	}
	?>
	<script>
	(function($) {
		// Ensure Stripe is loaded before trying to use it
		if (typeof Stripe === 'undefined' && gtiForms.stripePubKey) {
			console.warn('Stripe.js not loaded. Payment functionality may not work.');
			return;
		}

		var stripe = gtiForms.stripePubKey ? Stripe(gtiForms.stripePubKey) : null;

		$(document).on('submit', '.gti-ajax-form', function(e) {
			e.preventDefault();
			var $form = $(this);
			var $inputsWrapper = $form.find('.gti-form-inputs-wrapper');
			var $response = $form.find('.gti-form-response');
			var $btn = $form.find('button[type="submit"]');
			var mode = $form.find('input[name="mode"]').val();
			
			$btn.prop('disabled', true);
			$response.removeClass('success error').empty();
			
			$.ajax({
				url: gtiForms.ajaxUrl,
				type: 'post',
				data: $form.serialize(),
				success: function(res) {
					if(res.success) {
						if (res.data.screen === 'confirmation') {
							// Show confirmation screen
							$inputsWrapper.hide();
							$form.find('.gti-form-confirmation').remove();
							$inputsWrapper.after('<div class="gti-form-confirmation">' + res.data.html + '</div>');
							$form.find('input[name="mode"]').val('final');
							$btn.text(res.data.button_text).prop('disabled', false).show();
							
							// Change URL to confirm
							var confirmUrl = window.location.pathname + window.location.search + (window.location.search ? '&' : '?') + 'gti_step=confirm';
							history.pushState({step: 'confirm'}, '', confirmUrl);

							// Add back button
							if (!$form.find('.gti-back-btn').length) {
								$btn.before('<button type="button" class="gti-back-btn">' + gtiForms.i18n.back + '</button>');
							}
						} else if (res.data.requires_payment && stripe) {
							// Trigger Stripe
							stripe.redirectToCheckout({
								sessionId: res.data.checkout_session_id
							}).then(function (result) {
								if (result.error) {
									$response.addClass('error').text(result.error.message);
									$btn.prop('disabled', false);
								}
							});
						} else {
							// Completion - Redirect to thanks page
							window.location.href = res.data.redirect_url || (window.location.protocol + '//' + window.location.host + window.location.pathname + '?gti_step=thanks');
						}
					} else {
						$response.addClass('error').removeClass('success').text(res.data.message);
						$btn.prop('disabled', false);
					}
				},
				error: function() {
					$response.addClass('error').removeClass('success').text(gtiForms.i18n.error);
					$btn.prop('disabled', false);
				}
			});
		});

		$(document).on('click', '.gti-back-btn', function() {
			var $form = $(this).closest('form');
			$form.find('.gti-form-confirmation').remove();
			$(this).remove();
			$form.find('.gti-form-inputs-wrapper').show();
			$form.find('input[name="mode"]').val('confirm');
			$form.find('button[type="submit"]').text($form.find('button[type="submit"]').data('original-text') || gtiForms.i18n.submit);
			
			// Remove confirm from URL
			var originalUrl = window.location.pathname + window.location.search.replace(/[&?]gti_step=confirm/, '');
			history.pushState(null, '', originalUrl);
		});

		// Handle browser back button
		window.onpopstate = function(event) {
			if (!event.state || event.state.step !== 'confirm') {
				$('.gti-back-btn').trigger('click');
			}
		};

		// Store original text
		$(function() {
			$('.gti-ajax-form button[type="submit"]').each(function(){
				$(this).data('original-text', $(this).text());
			});
		});
	})(jQuery);
	</script>
	<?php
}
add_action( 'wp_footer', 'gti_forms_add_footer_scripts' );

/**
 * Render individual blocks
 */
function gti_forms_render_block( $block, $form_id ) {
	$output = '';
	$attrs = isset( $block['attrs'] ) ? $block['attrs'] : array();
	
	// Hook to allow custom field rendering
	$custom_render = apply_filters( 'gti_forms_pre_render_field', null, $block, $form_id );
	if ( $custom_render !== null ) {
		return $custom_render;
	}

	switch ( $block['blockName'] ) {
		case 'gti/form-text':
		case 'gti/form-email':
			$type = ( $block['blockName'] === 'gti/form-email' ) ? 'email' : 'text';
			$output .= '<div class="gti-form-group">';
			$output .= '<label>' . esc_html( $attrs['label'] ) . ( $attrs['required'] ? ' <span class="required">*</span>' : '' ) . '</label>';
			$output .= '<input type="' . $type . '" name="' . esc_attr( $attrs['name'] ) . '" placeholder="' . esc_attr( $attrs['placeholder'] ) . '" ' . ( $attrs['required'] ? 'required' : '' ) . '>';
			$output .= '</div>';
			break;
		case 'gti/form-textarea':
			$output .= '<div class="gti-form-group">';
			$output .= '<label>' . esc_html( $attrs['label'] ) . ( $attrs['required'] ? ' <span class="required">*</span>' : '' ) . '</label>';
			$output .= '<textarea name="' . esc_attr( $attrs['name'] ) . '" ' . ( $attrs['required'] ? 'required' : '' ) . '></textarea>';
			$output .= '</div>';
			break;

		case 'gti/form-hidden':
			$val = isset($attrs['value']) ? $attrs['value'] : '';
			// Auto-fill from URL if parameter exists
			if ( isset($_REQUEST[$attrs['name']]) ) {
				$val = sanitize_text_field($_REQUEST[$attrs['name']]);
			}
			$output .= '<input type="hidden" name="' . esc_attr($attrs['name']) . '" value="' . esc_attr($val) . '">';
			break;

		case 'gti/form-submit':
		case 'gti/form-stripe':
			$output .= '<div class="gti-form-submit">';
			$text = isset($attrs['text']) ? $attrs['text'] : (isset($attrs['label']) ? $attrs['label'] : __( '送信する', 'gti-forms' ));
			$output .= '<button type="submit">' . esc_html( $text ) . '</button>';
			$output .= '</div>';
			break;
		
		case 'core/paragraph':
			$output .= render_block($block);
			break;
		
		case 'core/heading':
			$output .= render_block($block);
			break;
	}

	return apply_filters( 'gti_forms_render_field', $output, $block, $form_id );
}
