<?php
/**
 * Post Generation
 *
 * This file contains all post generation functionality.
 *
 * @package Simple_Ai_Auto_Post
 * @since 1.0.0
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// Make sure this file is being included by a parent file.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Get custom fields for a specific post type
 *
 * @param string $post_type The post type to get custom fields for
 * @return array Array of custom fields with keys and labels
 */
function saiap_get_custom_fields_for_post_type( $post_type ) {
	$custom_fields = array();

	// Check if ACF is active
	if ( function_exists( 'acf_get_field_groups' ) ) {
		// Get all field groups
		$field_groups = acf_get_field_groups( array( 'post_type' => $post_type ) );

		// Loop through each field group
		foreach ( $field_groups as $field_group ) {
			// Get fields for this group
			$fields = acf_get_fields( $field_group );

			// Loop through each field
			foreach ( $fields as $field ) {
				$field_info = array(
					'key'       => $field['name'],
					'label'     => $field['label'],
					'type'      => $field['type'],
					'subfields' => array(),
				);

				// Handle repeater fields
				if ( $field['type'] == 'repeater' && isset( $field['sub_fields'] ) ) {
					foreach ( $field['sub_fields'] as $sub_field ) {
						$field_info['subfields'][ $sub_field['name'] ] = array(
							'label' => $sub_field['label'],
							'type'  => $sub_field['type'],
						);
					}
				}

				$custom_fields[ $field['name'] ] = $field_info;
			}
		}
	}

	// Allow other plugins to add their custom fields
	return apply_filters( 'saiap_custom_fields', $custom_fields, $post_type );
}

/**
 * Orchestrates the entire post creation process from prompt to published draft.
 *
 * @param array $args Array of arguments for post creation.
 * @return array|WP_Error The created post data including the edit link, or WP_Error on failure.
 */
function saiap_orchestrate_post_creation( $args ) {
	// 1. Generate content
	try {
		$generated = saiap_generate_post_content(
			$args['prompt'],
			$args['model'],
			$args['provider'],
			isset( $args['type_key'] ) ? $args['type_key'] : '',
			isset( $args['content_brief'] ) ? $args['content_brief'] : ''
		);
	} catch ( Exception $e ) {
		return new WP_Error( 'content_generation_failed', $e->getMessage() );
	}

	// 2. Prepare content (for logging and post data)
	$prepared_content = saiap_prepare_post_content( $generated['content'] );

	// 3. Create post
	// Check "Review first" setting to determine post status
	$review_first = get_option( 'saiap_review_before_publish', false );
	$post_status  = $review_first ? 'draft' : 'publish';

	$post_data = array(
		'post_title'   => ! empty( $args['title'] ) ? $args['title'] : $generated['title'],
		'post_content' => $prepared_content,
		'post_status'  => $post_status,
		'post_type'    => $args['post_type'],
		'post_author'  => get_option( 'saiap_post_author', get_current_user_id() ),
	);

	$post_id = wp_insert_post( $post_data );

	if ( is_wp_error( $post_id ) ) {
		return $post_id; // Return the WP_Error object instead of throwing
	}

	// Mark post as generated by ClearPost for dashboard metrics.
	update_post_meta( $post_id, '_saiap_generated', true );
	update_post_meta( $post_id, '_saiap_generated_at', current_time( 'mysql' ) );

	// 3. Track post generation
	saiap_track_post_generation( $args['provider'], $args['model'], $args['post_type'], $args['custom_fields'] );

	// 4. Save the prompt to history
	saiap_save_prompt( $args['prompt'], saiap_get_system_prompt(), $args['model'], $post_id );

	// 5. Handle custom fields
	if ( ! empty( $generated['link'] ) && function_exists( 'update_field' ) ) {
		// Get the selected link field
		$link_field_name_from_options = get_option( 'saiap_link_field_name', '' );

		if ( ! empty( $link_field_name_from_options ) ) {
			// For repeater fields
			if ( strpos( $link_field_name_from_options, '|' ) !== false ) {
				list($repeater_name, $subfield_name) = explode( '|', $link_field_name_from_options );

				// Get current repeater rows
				$rows = get_field( $repeater_name, $post_id ) ?: array();

				// Add new row with the generated link, formatted for ACF Link field type
				$rows[] = array(
					$subfield_name => array(
						'title'  => $generated['linkTitle'],
						'url'    => $generated['link'],
						'target' => '', // Default to no target
					),
				);

				update_field( $repeater_name, $rows, $post_id );
			} else {
				// For regular fields
				update_field( $link_field_name_from_options, $generated['link'], $post_id );
			}
		}
	}

	// 6. Apply automatic taxonomy if taxonomy settings exist
	saiap_edit_post_taxonomy( $post_id );

	// Ensure manually generated posts also get a short per-post SEO title
	// instead of inheriting long site-name title templates from SEO plugins.
	if ( function_exists( 'saiap_apply_seo_meta' ) ) {
		saiap_apply_seo_meta( $post_id, '', '', null, '' );
	}

	// 7. Image handling: use agentic pipeline if session_id available
	$session_id = isset( $generated['session_id'] ) ? $generated['session_id'] : null;
	$image_agent_status = 'none';

	if ( $session_id && function_exists( 'saiap_trigger_image_agent' ) ) {
		// Agentic image pipeline - call image agent with session continuation
		update_post_meta( $post_id, '_saiap_image_agent_status', 'queued' );
		$image_agent_status = 'queued';
		saiap_trigger_image_agent( $post_id, $session_id );
	} else {
		// No session: try auto-attach feature image as fallback
		try {
			$has_thumbnail = has_post_thumbnail( $post_id );

			if ( ! $has_thumbnail && function_exists( 'saiap_attach_first_image_result' ) ) {
				$search_query = get_the_title( $post_id );
				$attach_res   = saiap_attach_first_image_result( $post_id, $search_query );

				if ( is_int( $attach_res ) && $attach_res > 0 ) {
					do_action( 'saiap_auto_image_attached', $post_id, $attach_res );
					$image_agent_status = 'auto_attached';
				} elseif ( is_wp_error( $attach_res ) ) {
					do_action( 'saiap_auto_image_failed', $post_id, $attach_res );
				}
			}
		} catch ( Exception $e ) {
			do_action( 'saiap_auto_image_failed', $post_id, new WP_Error( 'auto_image_exception', $e->getMessage() ) );
		}
	}

	// Return success data
	return array(
		'message'              => 'Post generated successfully!',
		'post_id'              => $post_id,
		'post_status'          => $post_status,
		'edit_url'             => get_edit_post_link( $post_id, '' ),
		'inline_images_status' => $image_agent_status,
	);
}

/**
 * Strip images from AI-generated content.
 *
 * Removes <img> tags and wp:image blocks that the AI may have included.
 * Images should be added via the controlled inline images feature, not by the AI.
 *
 * @param string $content The content to process.
 * @return string Content with images removed.
 */
function saiap_strip_ai_images( $content ) {
	if ( ! is_string( $content ) || empty( $content ) ) {
		return $content;
	}

	$original_len = strlen( $content );

	// Remove standalone <img> tags (not inside figure or other wrappers).
	$content = preg_replace( '/<img\s+[^>]*>/i', '', $content );

	// Remove wp:image blocks (including the figure wrapper).
	// Pattern: <!-- wp:image ... --> ... <!-- /wp:image -->
	$content = preg_replace(
		'/<!--\s*wp:image[^>]*-->.*?<!--\s*\/wp:image\s*-->/is',
		'',
		$content
	);

	// Remove any orphaned <figure> tags that contained images.
	$content = preg_replace(
		'/<figure\s+[^>]*class\s*=\s*["\'][^"\']*wp-block-image[^"\']*["\'][^>]*>.*?<\/figure>/is',
		'',
		$content
	);

	// Clean up any resulting empty paragraphs or double line breaks.
	$content = preg_replace( '/<p>\s*<\/p>/i', '', $content );
	$content = preg_replace( '/\n{3,}/', "\n\n", $content );

	return $content;
}

/**
 * Normalize generated content for WordPress/Gutenberg display.
 * - If content already contains blocks or <p> tags, return as-is.
 * - Otherwise, convert plaintext newlines to paragraphs using wpautop and sanitize.
 *
 * @param string $raw Raw generated content
 * @return string Normalized HTML content
 */
function saiap_prepare_post_content( $raw ) {
	// First, strip any AI-inserted images. Images will be added via inline images feature.
	$raw = saiap_strip_ai_images( $raw );

	// Normalize any Markdown-style inline links to HTML anchors, e.g. [Label](https://example.com)
	// so they render correctly in WordPress content.
	if ( is_string( $raw ) && $raw !== '' ) {
		$raw = preg_replace_callback(
			'/\[(.+?)\]\((https?:\/\/[^\s)]+)\)/',
			function ( $matches ) {
				$text = $matches[1];
				$url  = $matches[2];

				// Keep this as raw HTML; WordPress will apply appropriate sanitization via kses.
				return '<a href="' . $url . '">' . $text . '</a>';
			},
			$raw
		);
	}

	if ( ! is_string( $raw ) || $raw === '' ) {
		return '';
	}
	// If the content already contains block delimiters or existing paragraph tags, keep it
	if ( ( function_exists( 'has_blocks' ) && has_blocks( $raw ) ) ||
		 strpos( $raw, '<!-- wp:' ) !== false ||
		 strpos( $raw, '<p' ) !== false ) {
		return $raw;
	}

	// Normalize line endings and convert to paragraphs
	$normalized = str_replace( array( "\r\n", "\r" ), "\n", $raw );
	$html       = wpautop( $normalized );

	// Sanitize to allowed post HTML
	$out = wp_kses_post( $html );

	return $out;
}

/**
 * AJAX handler for getting custom fields for a post type
 */
function saiap_ajax_get_custom_fields() {
	// Check nonce
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'saiap_get_custom_fields' ) ) {
		wp_send_json_error( 'Invalid nonce' );
	}

	// Get post type
	$post_type = isset( $_POST['post_type'] ) ? sanitize_text_field( wp_unslash( $_POST['post_type'] ) ) : 'post';

	// Get custom fields
	$custom_fields = saiap_get_custom_fields_for_post_type( $post_type );

	// Get current link field
	$current_link_field = get_option( 'saiap_link_field_name', '' );

	// Build options HTML
	$options_html = '<option value="">' . esc_html__( 'Select a field', 'clearpost-simple-ai-auto-post' ) . '</option>';

	foreach ( $custom_fields as $field_name => $field ) {
		// Only include text, textarea, and wysiwyg fields in the dropdown
		if ( in_array( $field['type'], array( 'text', 'textarea', 'wysiwyg' ) ) ) {
			$options_html .= '<option value="' . esc_attr( $field_name ) . '"' . selected( $current_link_field, $field_name, false ) . '>' . esc_html( $field['label'] ) . '</option>';
		}

		// Include repeater subfields
		if ( $field['type'] == 'repeater' && ! empty( $field['subfields'] ) ) {
			foreach ( $field['subfields'] as $subfield_name => $subfield ) {
				if ( in_array( $subfield['type'], array( 'text', 'textarea', 'wysiwyg', 'link' ) ) ) {
					$field_key     = $field_name . '|' . $subfield_name;
					$options_html .= '<option value="' . esc_attr( $field_key ) . '"' . selected( $current_link_field, $field_key, false ) . '>' .
						esc_html( $field['label'] . ' - ' . $subfield['label'] ) . '</option>';
				}
			}
		}
	}

	// Send response
	wp_send_json_success( $options_html );
}
add_action( 'wp_ajax_saiap_get_custom_fields', 'saiap_ajax_get_custom_fields' );

/**
 * AJAX handler for getting custom fields HTML for a post type
 */
function saiap_ajax_get_custom_fields_html() {
	// Check nonce
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'saiap_get_custom_fields' ) ) {
		wp_send_json_error( 'Invalid nonce' );
	}

	// Get post type
	$post_type = isset( $_POST['post_type'] ) ? sanitize_text_field( wp_unslash( $_POST['post_type'] ) ) : 'post';

	// Get custom fields
	$custom_fields = saiap_get_custom_fields_for_post_type( $post_type );

	// Build HTML
	ob_start();

	if ( ! empty( $custom_fields ) ) {
		?>
		<h3 class="spacing-8"><?php esc_html_e( 'Custom Fields', 'clearpost-simple-ai-auto-post' ); ?></h3>
		<?php
		foreach ( $custom_fields as $field_name => $field ) {
			// Only show text, textarea, and wysiwyg fields
			if ( in_array( $field['type'], array( 'text', 'textarea', 'wysiwyg' ) ) ) {
				?>
				<div class="spacing-8">
					<label for="saiap-cf-<?php echo esc_attr( $field_name ); ?>" class="body-text"><?php echo esc_html( $field['label'] ); ?>:</label>
					<input type="checkbox" name="custom_fields[<?php echo esc_attr( $field_name ); ?>]" id="saiap-cf-<?php echo esc_attr( $field_name ); ?>" value="1">
					<span class="small-text"><?php esc_html_e( 'Generate content for this field', 'clearpost-simple-ai-auto-post' ); ?></span>
				</div>
				<?php
			}

			// Handle repeater fields
			if ( $field['type'] == 'repeater' && ! empty( $field['subfields'] ) ) {
				?>
				<div class="spacing-8">
					<label class="body-text"><?php echo esc_html( $field['label'] ); ?> (<?php esc_html_e( 'Repeater', 'clearpost-simple-ai-auto-post' ); ?>):</label>
					<div class="spacing-8" style="margin-left: 20px;">
						<?php
						foreach ( $field['subfields'] as $subfield_name => $subfield ) {
							// Only show text, textarea, and wysiwyg subfields
							if ( in_array( $subfield['type'], array( 'text', 'textarea', 'wysiwyg' ) ) ) {
								?>
								<div class="spacing-8">
									<label for="saiap-cf-<?php echo esc_attr( $field_name . '_' . $subfield_name ); ?>" class="body-text"><?php echo esc_html( $subfield['label'] ); ?>:</label>
									<input type="checkbox" name="custom_fields[<?php echo esc_attr( $field_name . '|' . $subfield_name ); ?>]" id="saiap-cf-<?php echo esc_attr( $field_name . '_' . $subfield_name ); ?>" value="1">
									<span class="small-text"><?php esc_html_e( 'Generate content for this subfield', 'clearpost-simple-ai-auto-post' ); ?></span>
								</div>
								<?php
							}
						}
						?>
					</div>
				</div>
				<?php
			}
		}
	} else {
		?>
		<p class="small-text"><?php esc_html_e( 'No custom fields found for this post type.', 'clearpost-simple-ai-auto-post' ); ?></p>
		<?php
	}

	$html = ob_get_clean();

	// Send response
	wp_send_json_success( $html );
}
add_action( 'wp_ajax_saiap_get_custom_fields_html', 'saiap_ajax_get_custom_fields_html' );

/**
 * AJAX handler to save post authoring defaults.
 */
function saiap_save_defaults_callback() {
	check_ajax_referer( 'saiap_form_action', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => 'Unauthorized' ) );
	}

	$post_type   = isset( $_POST['post_type'] ) ? sanitize_text_field( wp_unslash( $_POST['post_type'] ) ) : 'post';
	$post_author = isset( $_POST['post_author'] ) ? absint( $_POST['post_author'] ) : get_current_user_id();
	$link_field  = isset( $_POST['link_field_name'] ) ? sanitize_text_field( wp_unslash( $_POST['link_field_name'] ) ) : '';

	update_option( 'saiap_post_type', $post_type );
	update_option( 'saiap_post_author', $post_author );
	update_option( 'saiap_link_field_name', $link_field );

	wp_send_json_success( array( 'message' => __( 'Defaults saved', 'clearpost-simple-ai-auto-post' ) ) );
}
add_action( 'wp_ajax_saiap_save_defaults', 'saiap_save_defaults_callback' );

/**
 * Render the Generate tab
 */
function saiap_render_generate_tab( $post_types, $models, $current_post_type, $custom_fields, $license_key ) {
	// Get current settings
	$current_provider        = get_option( 'saiap_default_provider', 'openai' );
	$current_openai_model    = get_option( 'saiap_openai_model', 'gpt-5.4' );
	$current_anthropic_model = get_option( 'saiap_anthropic_model', 'claude-opus-4-5' );
	$current_gemini_model    = get_option( 'saiap_gemini_model', 'gemini-3-pro-preview' );

	// Trial CTA is handled by Dashboard - no need for duplicate CTA here.
	?>
	<div class="container">
		<div class="row">
			<div class="col col-8">
				<div class="card">
					<h2 class="spacing-16-row"><?php esc_html_e( 'Generate', 'clearpost-simple-ai-auto-post' ); ?></h2>
					
					<form id="saiap-generate-form" method="post">
						<?php saiap_render_nonce_field(); ?>
						
						<div class="spacing-16-row">
							<label for="saiap-prompt" class="body-text"><?php esc_html_e( 'Prompt:', 'clearpost-simple-ai-auto-post' ); ?></label>
							<textarea name="saiap_ai_prompt" id="saiap-prompt" class="large-text" rows="5" placeholder="<?php esc_attr_e( 'Enter your prompt here...', 'clearpost-simple-ai-auto-post' ); ?>"><?php echo esc_textarea( get_option( 'saiap_ai_prompt' ) ); ?></textarea>
							<p class="small-text"><?php esc_html_e( 'Describe what you want the AI to write about.', 'clearpost-simple-ai-auto-post' ); ?></p>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=saiap&tab=dashboard' ) ); ?>" class="button-secondary" style="margin-top: 10px;">
								<?php esc_html_e( 'View your SEO content calendar on the Dashboard', 'clearpost-simple-ai-auto-post' ); ?>
							</a>
						</div>
						
						<div class="row spacing-16-row">
							<div class="col col-6">
								<label for="saiap-provider" class="body-text"><?php esc_html_e( 'AI Provider:', 'clearpost-simple-ai-auto-post' ); ?></label>
								<select name="saiap_default_provider" id="saiap-provider" class="regular-text">
									<option value="openai" <?php selected( $current_provider, 'openai' ); ?>><?php esc_html_e( 'OpenAI', 'clearpost-simple-ai-auto-post' ); ?></option>
									<option value="anthropic" <?php selected( $current_provider, 'anthropic' ); ?>><?php esc_html_e( 'Anthropic', 'clearpost-simple-ai-auto-post' ); ?></option>
									<option value="gemini" <?php selected( $current_provider, 'gemini' ); ?>><?php esc_html_e( 'Gemini', 'clearpost-simple-ai-auto-post' ); ?></option>
								</select>
							</div>
							<div class="col col-6">
								<div class="openai-settings" <?php echo ( $current_provider !== 'openai' ) ? 'style="display:none;"' : ''; ?>>
									<label for="saiap-model" class="body-text"><?php esc_html_e( 'OpenAI Model:', 'clearpost-simple-ai-auto-post' ); ?></label>
									<select name="saiap_openai_model" id="saiap-model" class="regular-text">
										<?php
										if ( ! array_key_exists( $current_openai_model, $models['openai'] ) ) {
											$current_openai_model = 'gpt-5.4';
										}
										foreach ( $models['openai'] as $model_id => $model_name ) :
											?>
											<option 
												value="<?php echo esc_attr( $model_id ); ?>" 
												<?php selected( $current_openai_model, $model_id ); ?>
											>
												<?php echo esc_html( $model_name ); ?>
											</option>
										<?php endforeach; ?>
									</select>
								</div>
								<div class="anthropic-settings" <?php echo ( $current_provider !== 'anthropic' ) ? 'style="display:none;"' : ''; ?>>
									<label for="saiap-anthropic-model" class="body-text"><?php esc_html_e( 'Anthropic Model:', 'clearpost-simple-ai-auto-post' ); ?></label>
									<select name="saiap_anthropic_model" id="saiap-anthropic-model" class="regular-text">
										<?php
										if ( ! array_key_exists( $current_anthropic_model, $models['anthropic'] ) ) {
											$current_anthropic_model = 'claude-opus-4-5';
										}
										foreach ( $models['anthropic'] as $model_id => $model_name ) :
											?>
											<option 
												value="<?php echo esc_attr( $model_id ); ?>" 
												<?php selected( $current_anthropic_model, $model_id ); ?>
											>
												<?php echo esc_html( $model_name ); ?>
											</option>
										<?php endforeach; ?>
									</select>
								</div>
								<div class="gemini-settings" <?php echo ( $current_provider !== 'gemini' ) ? 'style="display:none;"' : ''; ?>>
									<label for="saiap-gemini-model" class="body-text"><?php esc_html_e( 'Gemini Model:', 'clearpost-simple-ai-auto-post' ); ?></label>
									<select name="saiap_gemini_model" id="saiap-gemini-model" class="regular-text">
										<?php
										$current_gemini_model = get_option( 'saiap_gemini_model', 'gemini-3-pro-preview' );
										if ( ! array_key_exists( $current_gemini_model, $models['gemini'] ) ) {
											$current_gemini_model = 'gemini-3-pro-preview';
										}
										foreach ( $models['gemini'] as $model_id => $model_name ) :
											?>
											<option 
												value="<?php echo esc_attr( $model_id ); ?>" 
												<?php selected( $current_gemini_model, $model_id ); ?>
											>
												<?php echo esc_html( $model_name ); ?>
											</option>
										<?php endforeach; ?>
									</select>
								</div>
							</div>
						</div>

						<div class="spacing-16-row">
							<label for="saiap-type-key" class="body-text"><?php esc_html_e( 'Post Type Example:', 'clearpost-simple-ai-auto-post' ); ?></label>
							<select name="type_key" id="saiap-type-key" class="regular-text">
								<option value=""><?php esc_html_e( 'Auto-infer', 'clearpost-simple-ai-auto-post' ); ?></option>
							</select>
							<p class="small-text"><?php esc_html_e( 'Choose a post type map to guide structure and style, or leave as Auto-infer.', 'clearpost-simple-ai-auto-post' ); ?></p>
						</div>
						
						<div class="row spacing-16-row">
							<div class="col col-4">
								<label for="saiap-post-type" class="body-text"><?php esc_html_e( 'Post Type:', 'clearpost-simple-ai-auto-post' ); ?></label>
								<select name="post_type" id="saiap-post-type" class="regular-text">
									<?php foreach ( $post_types as $post_type ) : ?>
										<option value="<?php echo esc_attr( $post_type->name ); ?>" <?php selected( $current_post_type, $post_type->name ); ?>>
											<?php echo esc_html( $post_type->labels->singular_name ); ?>
										</option>
									<?php endforeach; ?>
								</select>
							</div>
							<div class="col col-4">
								<label for="saiap-post-author" class="body-text"><?php esc_html_e( 'Author:', 'clearpost-simple-ai-auto-post' ); ?></label>
								<select name="post_author" id="saiap-post-author" class="regular-text">
									<?php
									$authors        = get_users( array( 'capability' => 'publish_posts' ) );
									$current_author = get_option( 'saiap_post_author', get_current_user_id() );
									foreach ( $authors as $author ) :
										?>
										<option value="<?php echo esc_attr( $author->ID ); ?>" <?php selected( $current_author, $author->ID ); ?>>
											<?php echo esc_html( $author->display_name ); ?>
										</option>
									<?php endforeach; ?>
								</select>
							</div>
							<div class="col col-4">
								<label for="saiap_link_field_name" class="body-text"><?php esc_html_e( 'Link Field:', 'clearpost-simple-ai-auto-post' ); ?></label>
								<select name="saiap_link_field_name" id="saiap_link_field_name" class="regular-text">
									<option value=""><?php esc_html_e( 'Select a field', 'clearpost-simple-ai-auto-post' ); ?></option>
									<?php
									$current_link_field = get_option( 'saiap_link_field_name', '' );
									foreach ( $custom_fields as $field_name => $field ) {
										if ( in_array( $field['type'], array( 'text', 'textarea', 'wysiwyg' ) ) ) {
											?>
											<option value="<?php echo esc_attr( $field_name ); ?>" <?php selected( $current_link_field, $field_name ); ?>>
												<?php echo esc_html( $field['label'] ); ?>
											</option>
											<?php
										}
										if ( $field['type'] == 'repeater' && ! empty( $field['subfields'] ) ) {
											foreach ( $field['subfields'] as $subfield_name => $subfield ) {
												if ( in_array( $subfield['type'], array( 'text', 'textarea', 'wysiwyg', 'link' ) ) ) {
													$field_key = $field_name . '|' . $subfield_name;
													?>
													<option value="<?php echo esc_attr( $field_key ); ?>" <?php selected( $current_link_field, $field_key ); ?>>
														<?php echo esc_html( $field['label'] . ' - ' . $subfield['label'] ); ?>
													</option>
													<?php
												}
											}
										}
									}
									?>
								</select>
								<p class="small-text"><?php esc_html_e( 'Select which field to put the AI-selected link into.', 'clearpost-simple-ai-auto-post' ); ?></p>
							</div>
						</div>

						<div class="spacing-24 text-align-center display-grid" style="gap: 12px;">
							<button type="submit" id="saiap-generate-button" class="primary-button">
								<?php esc_html_e( 'Generate Post', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
							<button type="button" id="saiap-save-defaults" class="secondary-button">
								<?php esc_html_e( 'Save as defaults', 'clearpost-simple-ai-auto-post' ); ?>
							</button>
						</div>
					</form>

					<?php
					// Show Post Map CTA for licensed users with no post maps
					if ( function_exists( 'saiap_render_post_map_cta' ) ) {
						saiap_render_post_map_cta( 'generate' );
					}
					?>
					
					<!-- Loader -->
					<div id="saiap-loader" class="spacing-24">
						<div class="spinner"></div>
						<div class="loader-content">
							<p class="body-text"><?php esc_html_e( 'Generating content...', 'clearpost-simple-ai-auto-post' ); ?></p>
							<p class="small-text"><?php esc_html_e( 'This may take a minute or two depending on the complexity of your prompt.', 'clearpost-simple-ai-auto-post' ); ?></p>
						</div>
					</div>

					<?php
						// Show a small Premium CTA when no license and no API keys are configured
						$openai_key    = get_option( 'saiap_openai_api_key', '' );
						$anthropic_key = get_option( 'saiap_anthropic_api_key', '' );
						$gemini_key    = get_option( 'saiap_gemini_api_key', '' );
						if ( empty( $license_key ) && empty( $openai_key ) && empty( $anthropic_key ) && empty( $gemini_key ) ) :
					?>
					<div id="saiap-generate-cta" class="spacing-8-row" style="display: none;">
						<div class="notice notice-info inline">
							<p class="small-text" style="margin: 8px 0;">
								<?php esc_html_e( 'Grow organic traffic on autopilot while you sleep - with ClearPost Premium.', 'clearpost-simple-ai-auto-post' ); ?>
								<a href="https://clearpostplugin.com/" target="_blank"><?php esc_html_e( 'Generate traffic on autopilot', 'clearpost-simple-ai-auto-post' ); ?></a>
							</p>
							<p style="margin: 8px 0;">
								<button type="button" class="button-secondary" id="saiap-generate-cta-dismiss"><?php esc_html_e( 'Dismiss', 'clearpost-simple-ai-auto-post' ); ?></button>
							</p>
						</div>
					</div>
					<?php endif; ?>
				</div>
			</div>
			
			<div class="col col-4">
				<div class="card">
					<h2 class="spacing-16-row"><?php esc_html_e( 'History', 'clearpost-simple-ai-auto-post' ); ?></h2>
					<?php saiap_render_prompt_history(); ?>
				</div>
			</div>
		</div>
		
		
	</div>
	<?php
}

/**
 * Get the system prompt for content generation
 *
 * @return string The system prompt
 */
function saiap_get_system_prompt() {
	$prompt = 'Provide your response in EXACTLY this format. Do not include any extra sections or commentary.
Title: [Your generated title here]

Content: [Your generated content here, which MUST be serialized as valid Gutenberg blocks. For paragraphs, you MUST wrap text with both block comments and a <p> tag, like this:
<!-- wp:paragraph --><p>Your first paragraph text here.</p><!-- /wp:paragraph -->
<!-- wp:paragraph --><p>Your second paragraph text here.</p><!-- /wp:paragraph -->

For headings, use:
<!-- wp:heading {"level":2} --><h2>Your H2 here</h2><!-- /wp:heading -->
<!-- wp:heading {"level":3} --><h3>Your H3 here</h3><!-- /wp:heading -->

For tables, you MUST serialize as a Gutenberg core/table block (do NOT output a bare <table>). Use exactly this shape:
<!-- wp:table -->
<figure class="wp-block-table">
  <table>
    <thead><tr><th>Header 1</th><th>Header 2</th></tr></thead>
    <tbody><tr><td>Cell 1</td><td>Cell 2</td></tr></tbody>
  </table>
</figure>
<!-- /wp:table -->
If you set {"hasFixedLayout":true}, you MUST mirror it with <table class="has-fixed-layout"> and with the attribute in the opening block comment, e.g.:
<!-- wp:table {"hasFixedLayout":true} -->
<figure class="wp-block-table">
  <table class="has-fixed-layout">
    <thead>...</thead><tbody>...</tbody>
  </table>
</figure>
<!-- /wp:table -->

Claims and Sourcing Policy (STRICT):
- Only include specific factual claims (numbers, dates, named entities, rankings, prices, availability, capacities, addresses, certifications, “best/most” style claims) if they are clearly supported by the provided Site Context or your verified knowledge from a source on the web. Do NOT invent or guess.
- If you cannot confidently support a specific claim:
  - Omit the unsupported subsection/row entirely, OR
  - In tables, use N/A or “Contact for current details” instead of a fabricated value.
- Do NOT add citations in the output unless explicitly requested. Verify silently; the rendered content must remain professional and self-contained.
- Never fabricate content to satisfy a structural slot; structure is secondary to accuracy.

Opening quality rules:
- Never start the first paragraph with the phrase "At ClearPost, we".
- Do not use formulaic brand-first openers such as "At ClearPost" or "Here at ClearPost". Start with the reader\'s problem, a concrete benefit, or the topic itself.

Rules:
- Do NOT use Markdown (no **bold**, *italics*, backticks, or lists).
- For ALL inline links inside the Content section, you MUST use standard HTML anchor tags only, e.g. <a href="https://example.com">Descriptive text</a>. Never use Markdown link syntax like [label](https://example.com) anywhere in the response.
- Do NOT output any blocks without html tags like <p>…</p> inside.
- Do NOT output any text outside the Title/Content/Link/Link Title sections.
]

Link: [Your generated link here. MUST be a valid URL, structured as a URL with protocol (e.g. https://www.google.com) and NOT in markdown format]
Link Title: [Your generated link title here, MUST be different from the title of the post]';

	// Allow plugins to modify the system prompt
	return apply_filters( 'saiap_system_prompt', $prompt );
}

/**
 * Save settings and generate a new post
 */
function saiap_save_settings_and_generate_post() {
	try {
		// Verify nonce
		if ( ! isset( $_POST['saiap_form_nonce'] ) && ! isset( $_POST['nonce'] ) ) {
			throw new Exception( __( 'Invalid nonce verification', 'clearpost-simple-ai-auto-post' ) );
		}

		$nonce = isset( $_POST['saiap_form_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_form_nonce'] ) ) : sanitize_text_field( wp_unslash( $_POST['nonce'] ) );
		if ( ! wp_verify_nonce( $nonce, 'saiap_form_action' ) ) {
			throw new Exception( __( 'Invalid nonce verification', 'clearpost-simple-ai-auto-post' ) );
		}

		// Get and sanitize form data for settings updates
		update_option( 'saiap_ai_prompt', isset( $_POST['prompt'] ) ? sanitize_textarea_field( wp_unslash( $_POST['prompt'] ) ) : '' );
		update_option( 'saiap_model', isset( $_POST['model'] ) ? sanitize_text_field( wp_unslash( $_POST['model'] ) ) : 'gpt-5.4' );
		update_option( 'saiap_default_provider', isset( $_POST['saiap_default_provider'] ) ? sanitize_text_field( wp_unslash( $_POST['saiap_default_provider'] ) ) : 'openai' );
		update_option( 'saiap_post_type', isset( $_POST['post_type'] ) ? sanitize_text_field( wp_unslash( $_POST['post_type'] ) ) : 'post' );
		if ( isset( $_POST['saiap_link_field_name'] ) ) {
			update_option( 'saiap_link_field_name', sanitize_text_field( wp_unslash( $_POST['saiap_link_field_name'] ) ) );
		}

		// Prepare args for the orchestrator
		$prompt = isset( $_POST['prompt'] ) ? sanitize_textarea_field( wp_unslash( $_POST['prompt'] ) ) : '';
		if ( empty( $prompt ) ) {
			throw new Exception( __( 'Please enter a prompt', 'clearpost-simple-ai-auto-post' ) );
		}
        
		$provider = isset( $_POST['provider'] ) ? sanitize_text_field( wp_unslash( $_POST['provider'] ) ) : get_option('saiap_default_provider', 'openai');
		
		$model = isset( $_POST['model'] ) ? sanitize_text_field( wp_unslash( $_POST['model'] ) ) : 'gpt-5.4';

		$custom_fields = array();
		if ( isset( $_POST['custom_fields'] ) && is_array( $_POST['custom_fields'] ) ) {
			$custom_fields = array_map( 'sanitize_text_field', wp_unslash( $_POST['custom_fields'] ) );
		}

		$type_key = '';
		if ( isset( $_POST['type_key'] ) ) {
			$type_key = sanitize_text_field( wp_unslash( $_POST['type_key'] ) );
		}

		$args = array(
			'prompt'        => $prompt,
			'provider'      => $provider,
			'model'         => $model,
			'post_type'     => get_option('saiap_post_type'),
			'title'         => isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '',
			'custom_fields' => $custom_fields,
			'type_key'      => $type_key,
		);

		// Call the orchestrator
		$result = saiap_orchestrate_post_creation( $args );

		// Check if the result is a WP_Error
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		// Return success response
		wp_send_json_success( $result );

	} catch ( Exception $e ) {
		wp_send_json_error( array( 'message' => $e->getMessage() ) );
	}
}
add_action( 'wp_ajax_saiap_generate_post', 'saiap_save_settings_and_generate_post' );

/**
 * Extracts the title from the AI response.
 *
 * @param string $response The full AI response.
 * @return string The extracted title.
 */
function saiap_extract_title( $response ) {
	$title_match = array();
	if ( preg_match( '/Title:\s*(.*?)\s*$/', $response, $title_match ) ) {
		return trim( $title_match[1] );
	}
	return '';
}

/**
 * Extracts the content from the AI response.
 *
 * @param string $response The full AI response.
 * @return string The extracted content.
 */
function saiap_extract_content( $response ) {
	$content_match = array();
	if ( preg_match( '/Content:\s*(.*?)\s*$/', $response, $content_match ) ) {
		return trim( $content_match[1] );
	}
	return '';
}

/**
 * Extracts the link from the AI response.
 *
 * @param string $response The full AI response.
 * @return string The extracted link.
 */
function saiap_extract_link( $response ) {
	$link_match = array();
	if ( preg_match( '/Link:\s*(.*?)\s*$/', $response, $link_match ) ) {
		return trim( $link_match[1] );
	}
	return '';
}

/**
 * Extracts the link title from the AI response.
 *
 * @param string $response The full AI response.
 * @return string The extracted link title.
 */
function saiap_extract_link_title( $response ) {
	$link_title_match = array();
	if ( preg_match( '/Link Title:\s*(.*?)\s*$/', $response, $link_title_match ) ) {
		return trim( $link_title_match[1] );
	}
	return '';
}
