<?php
/**
 * SEO Enhancement Tools for Easy AI Blog Generator
 *
 * This file handles all SEO enhancement features for the plugin:
 * - Keyword density analyzer and optimizer
 * - Personalization-based keyword suggestion tool
 *
 * @package EasyAIBlogGenerator
 */

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

/**
 * Save the focus keyword when the post is saved.
 *
 * @param int $post_id The post ID.
 */
function easyaibloggen_save_focus_keyword( $post_id ) {
	// Verify nonce.
	if ( ! isset( $_POST['easyaibloggen_focus_keyword_nonce'] ) ||
		! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['easyaibloggen_focus_keyword_nonce'] ) ), 'easyaibloggen_focus_keyword_action' ) ) {
		return;
	}

	// Check if our nonce is set and verify it.
	if ( isset( $_POST['easyaibloggen_focus_keyword'] ) ) {
		update_post_meta(
			$post_id,
			'_easyaibloggen_focus_keyword',
			sanitize_text_field( wp_unslash( $_POST['easyaibloggen_focus_keyword'] ) )
		);
	}
}
add_action( 'save_post', 'easyaibloggen_save_focus_keyword' );

/**
 * Enqueue admin assets for keyword analysis.
 *
 * @param string $hook The current admin page hook.
 */
function easyaibloggen_enqueue_admin_assets( $hook ) {
	// Get the plugin's base directory and URL (using current file's location).
	$plugin_base_dir = plugin_dir_path( __FILE__ ); // Get the directory of current file.
	$plugin_base_url = plugin_dir_url( __FILE__ ); // Get the URL of current file.

	// Define CSS and JS paths.
	$css_url = $plugin_base_url . 'css/easyaibloggen-admin.css';
	$js_url  = $plugin_base_url . 'js/easyaibloggen-seo.js';

	// Set a static version to avoid caching issues.
	$version = '1.0.3';

	// Only add styles to admin pages.
	if ( is_admin() ) {
		wp_enqueue_style(
			'easyaibloggen-premium-styles',
			$css_url,
			array( 'dashicons' ),
			$version
		);
	}

	// Only load scripts on relevant pages.
	if ( in_array( $hook, array( 'post.php', 'post-new.php', 'tools_page_easyaibloggen-settings' ), true ) ) {
		// Enqueue the main script.
		wp_enqueue_script(
			'easyaibloggen-seo-scripts',
			$js_url,
			array( 'jquery', 'wp-i18n' ),
			$version,
			true
		);

		// Localize script with common data.
		wp_localize_script(
			'easyaibloggen-seo-scripts',
			'easyAiSeoData',
			array(
				'ajaxUrl'             => admin_url( 'admin-ajax.php' ),
				'nonce'               => wp_create_nonce( 'easyaibloggen_seo_ajax_nonce' ),
				'analyzing'           => __( 'Analyzing...', 'easy-ai-blog-generator' ),
				'applyingSuggestions' => __( 'Applying suggestions...', 'easy-ai-blog-generator' ),
				'errorMessage'        => __( 'An error occurred. Please try again.', 'easy-ai-blog-generator' ),
				'noKeywordMessage'    => __( 'Please enter a focus keyword to analyze.', 'easy-ai-blog-generator' ),
			)
		);

		wp_set_script_translations( 'easyaibloggen-seo-scripts', 'easy-ai-blog-generator' );
	}
}
add_action( 'admin_enqueue_scripts', 'easyaibloggen_enqueue_admin_assets' );

/**
 * AJAX handler for analyzing keyword density.
 */
function easyaibloggen_analyze_keyword_density_ajax() {
	// Verify nonce.
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'easyaibloggen_seo_ajax_nonce' ) ) {
		wp_send_json_error( 'Security check failed' );
		return;
	}

	// Create a custom log file for guaranteed logging.
	$log_file = plugin_dir_path( __FILE__ ) . 'ajax-debug.log';

	// Initialize WP_Filesystem.
	global $wp_filesystem;
	if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
	}

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "AJAX handler called\n", FILE_APPEND );

	// Log the POST data - Only in debug mode.
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
		// Use json_encode instead of print_r for structured logging.
		$sanitized_data = array_map( 'sanitize_text_field', wp_unslash( $_POST ) );
		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . 'POST data: ' . wp_json_encode( $sanitized_data ) . "\n", FILE_APPEND );
	}

	// For very basic debugging, just return a simple response if test param is set.
	if ( isset( $_POST['test'] ) && 'true' === sanitize_text_field( wp_unslash( $_POST['test'] ) ) ) {
		wp_send_json_success(
			array(
				'message'  => 'Test successful',
				'received' => array_map( 'sanitize_text_field', wp_unslash( $_POST ) ),
			)
		);
		return;
	}

	// For demonstration, let's mimic the OpenAI process.
	$post_id = isset( $_POST['postId'] ) ? intval( wp_unslash( $_POST['postId'] ) ) : 0;
	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Processing post ID: {$post_id}\n", FILE_APPEND );

	if ( ! $post_id ) {
		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Error: No valid post ID\n", FILE_APPEND );
		wp_send_json_error( 'No valid post ID provided' );
		return;
	}

	// Get post data.
	$post = get_post( $post_id );
	if ( ! $post ) {
		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Error: Post not found\n", FILE_APPEND );
		wp_send_json_error( 'Post not found' );
		return;
	}

	$title   = $post->post_title;
	$content = $post->post_content;
	$keyword = isset( $_POST['keyword'] ) ? sanitize_text_field( wp_unslash( $_POST['keyword'] ) ) : '';

	// If auto_get_keyword is true, get the keyword from post meta.
	if ( isset( $_POST['auto_get_keyword'] ) && sanitize_text_field( wp_unslash( $_POST['auto_get_keyword'] ) ) ) {
		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Auto-getting keyword from meta\n", FILE_APPEND );
		$keyword = get_post_meta( $post_id, '_easyaibloggen_preferred_keyword', true );
		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Preferred keyword: {$keyword}\n", FILE_APPEND );

		if ( empty( $keyword ) ) {
			$keyword = get_post_meta( $post_id, '_easyaibloggen_focus_keyword', true );
			$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Focus keyword (fallback): {$keyword}\n", FILE_APPEND );
		}
	}

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Final keyword: {$keyword}\n", FILE_APPEND );

	if ( empty( $keyword ) ) {
		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Error: Empty keyword\n", FILE_APPEND );
		wp_send_json_error( 'Please enter a focus keyword to analyze.' );
		return;
	}

	// Calculate basic metrics.
	$clean_content = wp_strip_all_tags( $content );
	$word_count    = str_word_count( $clean_content );
	$keyword_count = substr_count( strtolower( $clean_content ), strtolower( $keyword ) );
	$density       = ( $word_count > 0 ) ? round( ( $keyword_count / $word_count ) * 100, 2 ) : 0;
	$is_optimal    = ( $density >= 1 && $density <= 3 );

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Word count: {$word_count}, Keyword count: {$keyword_count}, Density: {$density}%\n", FILE_APPEND );

	// Log what would be sent to OpenAI.
	$prompt = "I need to analyze the keyword density of a blog post and provide specific, actionable sentence suggestions. Here are the details:
    
Title: {$title}
Focus Keyword: {$keyword}
Current Keyword Density: {$density}%
Total Words: {$word_count}
Keyword Occurrences: {$keyword_count}

Content: {$clean_content}

Please analyze if this keyword density is optimal for SEO. Ideally, keyword density should be between 1% and 3%.

If the density is too low (below 1%), provide 3-5 specific sentences from the content with suggestions on how to naturally incorporate the keyword.

If the density is too high (above 3%), identify 3-5 specific sentences that contain the keyword and suggest how they could be rewritten to reduce keyword usage while maintaining meaning.

Include both the original sentences and your suggested revisions in your response.";

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . 'OpenAI prompt would be: ' . substr( $prompt, 0, 200 ) . "...\n", FILE_APPEND );
	// Make the actual OpenAI API call.
	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Making real API call to OpenAI\n", FILE_APPEND );

	$api_response = easyaibloggen_unified_api_call( $prompt, 'text' );

	// Create the instructions content to display in the first panel.
	$instructions = '<div style="margin-bottom: 15px; padding: 10px; background: #e7f7e3; border-left: 4px solid #46b450;">
						<h3>Keyword Density Analysis</h3>
						<p>Here are the results of your keyword density analysis for: <strong>' . esc_html( $keyword ) . '</strong></p>
					</div>';

	if ( $api_response ) {
		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . 'API call successful, response length: ' . strlen( $api_response ) . " chars\n", FILE_APPEND );

		// Process the API response and format it nicely.
		$api_response = wpautop( $api_response ); // Convert newlines to paragraphs.

		// Use the real API response for the analysis with better formatting.
		$ai_response = '<div class="suggestions-section">
	<div class="summary-assessment">
		<h3>Summary Assessment</h3>
		<p>The keyword density for "' . esc_html( $keyword ) . '" is currently ' . $density . '%, which is ' .
		( $is_optimal ? 'optimal' : ( $density < 1 ? 'below the recommended range' : 'above the recommended range' ) ) . ' for SEO purposes.</p>
		<p>Keyword density is ' . ( $is_optimal ? 'optimal' : 'not optimal' ) . ' - the ideal range is between 1% and 3%.</p>
		
		<table class="keyword-metrics-table">
			<tr>
				<th>Metric</th>
				<th>Value</th>
			</tr>
			<tr>
				<td>Keyword</td>
				<td class="metric-value">' . esc_html( $keyword ) . '</td>
			</tr>
			<tr>
				<td>Total Words</td>
				<td class="metric-value">' . $word_count . '</td>
			</tr>
			<tr>
				<td>Keyword Count</td>
				<td class="metric-value">' . $keyword_count . '</td>
			</tr>
			<tr>
				<td>Density</td>
				<td class="metric-value">' . $density . '%</td>
			</tr>
			<tr>
				<td>Status</td>
				<td class="metric-value ' . ( $is_optimal ? 'optimal' : 'needs-improvement' ) . '">
					' . ( $is_optimal ? 'Optimal' : 'Needs Improvement' ) . '
				</td>
			</tr>
		</table>
	</div>
	<div class="recommendations-section">' . wp_kses_post( $api_response ) . '</div>
</div>';

		// Create a proper result structure.
		$result = array(
			'keyword'             => $keyword,
			'totalWords'          => $word_count,
			'keywordCount'        => $keyword_count,
			'density'             => $density,
			'isOptimal'           => $is_optimal,
			'instructions'        => $instructions,
			'analysisHtml'        => $ai_response,
			'canApplySuggestions' => false,
		);

		// Check if the hide_apply_button parameter is set.
		if ( isset( $_POST['hide_apply_button'] ) && 'true' === sanitize_text_field( wp_unslash( $_POST['hide_apply_button'] ) ) ) {
			$result['hideApplyButton'] = true;
		}

		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Sending JSON response with analysis results\n", FILE_APPEND );
		wp_send_json_success( $result );
		return;
	} else {
		// Fallback to simulated response if API call fails.
		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "API call failed, using fallback response\n", FILE_APPEND );

		// Get potential API error from the log file.
		$api_error_log = plugin_dir_path( __FILE__ ) . 'api-call-debug.log';
		$api_error     = 'Unknown API error. Please check your API key and try again.';

		if ( file_exists( $api_error_log ) && $wp_filesystem->exists( $api_error_log ) ) {
			$log_content = $wp_filesystem->get_contents( $api_error_log );
			if ( preg_match( '/API Error: (.+)/', $log_content, $matches ) ) {
				$api_error = $matches[1];
			}
		}

		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "API Error details: $api_error\n", FILE_APPEND );

		// Return a clear error message that includes the API error.
		wp_send_json_error( 'API call failed: ' . $api_error );
		return;
	}
}
// Make sure we're hooking to both logged-in and non-logged-in AJAX actions.
add_action( 'wp_ajax_easyaibloggen_analyze_keyword_density', 'easyaibloggen_analyze_keyword_density_ajax' );
add_action( 'wp_ajax_nopriv_easyaibloggen_analyze_keyword_density', 'easyaibloggen_analyze_keyword_density_ajax' );

/**
 * AJAX handler for applying SEO suggestions to the post content.
 */
function easyaibloggen_apply_seo_suggestions_ajax() {
	// Check nonce.
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'easyaibloggen_seo_ajax_nonce' ) ) {
		wp_send_json_error( 'Security check failed.' );
	}

	// Check for required data.
	if ( ! isset( $_POST['postId'] ) || ! isset( $_POST['suggestions'] ) ) {
		wp_send_json_error( 'Missing required data.' );
	}

	$post_id     = intval( wp_unslash( $_POST['postId'] ) );
	$suggestions = sanitize_textarea_field( wp_unslash( $_POST['suggestions'] ) );

	// Get the post.
	$post = get_post( $post_id );
	if ( ! $post ) {
		wp_send_json_error( 'Post not found' );
	}

	// Generate optimized content with OpenAI.
	$prompt = "I have a blog post that needs to be optimized for better keyword density. Here's the original content:

{$post->post_content}

Based on SEO analysis, I received these suggestions:

{$suggestions}

Please apply these suggestions to the content. Keep the HTML formatting intact, including headings, lists, and other HTML elements. Keep all existing images and links. Only change what's necessary based on the suggestions. Return the complete optimized content.";

	// Call the OpenAI API.
	$optimized_content = easyaibloggen_unified_api_call( $prompt, 'text' );

	// Update the post with the optimized content.
	$updated_post = array(
		'ID'           => $post_id,
		'post_content' => $optimized_content,
	);

	$updated = wp_update_post( $updated_post );

	if ( is_wp_error( $updated ) ) {
		wp_send_json_error( $updated->get_error_message() );
	} else {
		wp_send_json_success(
			array(
				'message'      => __( 'Content has been optimized successfully.', 'easy-ai-blog-generator' ),
				'instructions' => '<div class="easyaibloggen-feature-wrapper">
					<div class="easyaibloggen-feature-instructions premium-feature">
						<strong>' . esc_html__( 'Content Updated', 'easy-ai-blog-generator' ) . '</strong>
						<p class="easyaibloggen-feature-instructions-text">' .
							esc_html__( 'Your content has been automatically optimized based on the AI recommendations. The changes have been applied while maintaining your original formatting and structure.', 'easy-ai-blog-generator' ) .
						'</p>
					</div>
				</div>',
			)
		);
	}
}
add_action( 'wp_ajax_easyaibloggen_apply_seo_suggestions', 'easyaibloggen_apply_seo_suggestions_ajax' );

/**
 * Add the keyword suggestions feature to the personalization section.
 */
function easyaibloggen_add_keyword_suggestions_field() {
	// Register the setting for the keywords.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_suggested_keywords',
		'easyaibloggen_sanitize_keywords'
	);

	// Add the field to the personalization section.
	add_settings_field(
		'easyaibloggen_keyword_suggestions',
		__( 'Keyword Suggestions', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_keyword_suggestions_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_suggested_keywords',
			'description' => __( 'Generate keyword suggestions based on your personalization data.', 'easy-ai-blog-generator' ),
		)
	);
}
add_action( 'admin_init', 'easyaibloggen_add_keyword_suggestions_field' );

/**
 * Sanitize keywords for storage.
 *
 * @param string $input The input to sanitize.
 * @return string The sanitized input.
 */
function easyaibloggen_sanitize_keywords( $input ) {
	return sanitize_textarea_field( $input );
}

/**
 * Render the keyword suggestions field.
 *
 * @param array $args Field arguments.
 */
function easyaibloggen_render_keyword_suggestions_field( $args ) {
	$option_name  = $args['label_for'];
	$option_value = get_option( $option_name, '' );
	$description  = isset( $args['description'] ) ? $args['description'] : '';

	?>
	<div class="easyaibloggen-feature-wrapper">
	<p class="easyaibloggen-feature-instructions premium-feature">
			<span class="premium-badge">+</span>
			<strong>Keyword Suggestions</strong>
			<span class="easyaibloggen-feature-instructions-text">: Generates targeted keyword ideas based on your business profile and personalization settings. Find high-value keywords with different search volumes and competition levels.</span>
	</p>
	<button type="button" id="easyaibloggen-generate-keywords" class="button">
		<?php esc_html_e( 'Generate Keyword Suggestions', 'easy-ai-blog-generator' ); ?>
	</button>
		<div id="easyaibloggen-keywords-loader" class="easyaibloggen-keywords-loader hidden">
		<?php esc_html_e( 'Generating keywords...', 'easy-ai-blog-generator' ); ?>
	</div>
		<div id="easyaibloggen-keywords-container" class="easyaibloggen-keywords-container<?php echo empty( $option_value ) ? ' hidden' : ''; ?>">
			<textarea id="<?php echo esc_attr( $option_name ); ?>" name="<?php echo esc_attr( $option_name ); ?>" class="large-text" readonly><?php echo esc_textarea( $option_value ); ?></textarea>
		</div>
		<?php if ( ! empty( $description ) ) : ?>
			<p class="easyaibloggen-description"><?php echo esc_html( $description ); ?></p>
		<?php endif; ?>
	</div>
	<?php
}

/**
 * AJAX handler for generating keyword suggestions.
 */
function easyaibloggen_generate_keywords_ajax() {
	// Check nonce.
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'easyaibloggen_seo_ajax_nonce' ) ) {
		wp_send_json_error( 'Security check failed.' );
		return;
	}

	// Get personalization data.
	$company_name      = get_option( 'easyaibloggen_company_name', '' );
	$website_purpose   = get_option( 'easyaibloggen_website_purpose', '' );
	$target_audience   = get_option( 'easyaibloggen_target_audience', '' );
	$products_services = get_option( 'easyaibloggen_products_services', '' );
	$brand_voice       = get_option( 'easyaibloggen_brand_voice', '' );
	$differentiators   = get_option( 'easyaibloggen_differentiators', '' );

	// Build the prompt for OpenAI.
	$prompt = "I need keyword suggestions for my website based on the following information:

Company/Website Name: {$company_name}
Website Purpose: {$website_purpose}
Target Audience: {$target_audience}
Products/Services: {$products_services}
Brand Voice: {$brand_voice}
Key Differentiators: {$differentiators}

Please generate keyword suggestions organized into the following categories:

1. Single Keywords:
   - High search/high competition
   - High search/medium competition
   - High search/low competition
   - Medium search/high competition
   - Medium search/medium competition
   - Medium search/low competition
   - Low search/high competition
   - Low search/medium competition
   - Low search/low competition

2. Niche Keywords (2-3 words):
   - High search/high competition
   - High search/medium competition
   - High search/low competition
   - Medium search/high competition
   - Medium search/medium competition
   - Medium search/low competition
   - Low search/high competition
   - Low search/medium competition
   - Low search/low competition

3. Long-tail Keywords (4+ words):
   - High search/high competition
   - High search/medium competition
   - High search/low competition
   - Medium search/high competition
   - Medium search/medium competition
   - Medium search/low competition
   - Low search/high competition
   - Low search/medium competition
   - Low search/low competition

For each category and sub-category, provide 3-5 keyword suggestions.
Format the output clearly with headings for each category and sub-category.";

	// Call the OpenAI API.
	$keywords = easyaibloggen_unified_api_call( $prompt, 'text' );

	// Save the generated keywords.
	update_option( 'easyaibloggen_suggested_keywords', $keywords );

	wp_send_json_success(
		array(
			'keywords' => $keywords,
		)
	);
}
add_action( 'wp_ajax_easyaibloggen_generate_keywords', 'easyaibloggen_generate_keywords_ajax' );

/**
 * Modify main plugin file to include instructions for keyword field.
 *
 * Adds a keyword density analysis button and instructions to the post editor.
 *
 * @param string $content The content to modify.
 * @return string Modified content with keyword density button and instructions.
 */
function easyaibloggen_add_keyword_density_button( $content ) {
	global $post;

	// Check if post exists.
	if ( ! $post ) {
		return $content;
	}

	// Get the current post ID.
	$post_id = $post->ID;

	// Get the preferred keyword from post meta.
	$preferred_keyword = get_post_meta( $post_id, '_easyaibloggen_preferred_keyword', true );

	// Log button creation for debugging.
	$log_file = plugin_dir_path( __FILE__ ) . 'button-debug.log';

	// Initialize WP_Filesystem if not already initialized.
	global $wp_filesystem;
	if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
	}

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Creating button for post ID: {$post_id}, Keyword: {$preferred_keyword}\n", FILE_APPEND );

	// Super simple test button first.
	$test_html = '<div style="margin: 20px 0; padding: 15px; background: #e9f7e9; border: 1px solid #4CAF50;">
		<h3>AJAX Test Button</h3>
		<p>This is a minimal test button that just tests the AJAX functionality.</p>
		<button 
			type="button" 
			onclick="
				console.log(\'Test button clicked\');
				document.getElementById(\'ajax-test-result\').textContent = \'Sending request...\';
				
				fetch(\'' . admin_url( 'admin-ajax.php' ) . '\', {
					method: \'POST\',
					headers: {
						\'Content-Type\': \'application/x-www-form-urlencoded\'
					},
					body: \'action=easyaibloggen_analyze_keyword_density&test=true&post_id=' . esc_js( $post_id ) . '\'
				})
				.then(response => response.json())
				.then(data => {
					console.log(\'Response:\', data);
					document.getElementById(\'ajax-test-result\').textContent = \'Success! Check console for details.\';
				})
				.catch(error => {
					console.error(\'Error:\', error);
					document.getElementById(\'ajax-test-result\').textContent = \'Error: \' + error;
				});
			"
			class="button button-primary">
			Test AJAX Connection
		</button>
		<p id="ajax-test-result" style="margin-top: 10px; font-family: monospace;"></p>
	</div>';

	// The main button with comprehensive debugging.
	$html = '<div style="margin: 20px 0; padding: 15px; background: #f9f9f9; border: 1px solid #ddd;">
		<h3>Keyword Density Analysis</h3>
		<p>Focus Keyword: <strong>' . esc_html( $preferred_keyword ) . '</strong></p>
		<p>Post ID: <strong>' . esc_html( $post_id ) . '</strong></p>
		<button 
			type="button" 
			onclick="
				var btn = this;
				var results = document.getElementById(\'keyword-results\');
				var loading = document.getElementById(\'keyword-loading\');
				var debug = document.getElementById(\'keyword-debug\');
				var rawresponse = document.getElementById(\'keyword-raw\');
				
				// Log to button debug file.
				fetch(\'' . admin_url( 'admin-ajax.php' ) . '\', {
					method: \'POST\',
					headers: {
						\'Content-Type\': \'application/x-www-form-urlencoded\'
					},
					body: \'action=easyaibloggen_log_button_click&post_id=' . esc_js( $post_id ) . '\'
				});
				
				// Clear previous results
				results.innerHTML = \'\';
				debug.innerHTML = \'\';
				rawresponse.innerHTML = \'\';
				
				btn.disabled = true;
				results.style.display = \'none\';
				loading.style.display = \'block\';
				debug.style.display = \'block\';
				rawresponse.style.display = \'block\';
				
				debug.innerHTML += \'<p>Sending AJAX request...</p>\';
				
				var xhr = new XMLHttpRequest();
				xhr.open(\'POST\', \'' . esc_js( admin_url( 'admin-ajax.php' ) ) . '\', true);
				xhr.setRequestHeader(\'Content-Type\', \'application/x-www-form-urlencoded\');
				
				xhr.onreadystatechange = function() {
					if (xhr.readyState === 4) {
						loading.style.display = \'none\';
						btn.disabled = false;
						
						debug.innerHTML += \'<p>Response received: Status \' + xhr.status + \'</p>\';
						debug.innerHTML += \'<p>Response text length: \' + xhr.responseText.length + \' characters</p>\';
						
						// Show the raw response text for debugging
						rawresponse.innerHTML = \'<h4>Raw Response</h4><pre>\' + 
							xhr.responseText.replace(/&/g, \'&amp;\').replace(/</g, \'&lt;\').replace(/>/g, \'&gt;\') + 
							\'</pre>\';
						
						if (xhr.status === 200) {
							try {
								debug.innerHTML += \'<p>Trying to parse JSON response...</p>\';
								var response = JSON.parse(xhr.responseText);
								debug.innerHTML += \'<p>JSON parsed successfully</p>\';
								
								if (response) {
									debug.innerHTML += \'<p>Response object exists</p>\';
									debug.innerHTML += \'<p>Full response object:</p>\';
									debug.innerHTML += \'<pre>\' + JSON.stringify(response, null, 2) + \'</pre>\';
									
									if (response.success) {
										debug.innerHTML += \'<p>Response indicates success</p>\';
										
										if (response.data) {
											debug.innerHTML += \'<p>Response contains data object</p>\';
											
											if (response.data.instructions && response.data.analysisHtml) {
												debug.innerHTML += \'<p>Response contains required fields</p>\';
												results.innerHTML = response.data.instructions + response.data.analysisHtml;
												results.style.display = \'block\';
											} else {
												debug.innerHTML += \'<p>ERROR: Missing instructions or analysisHtml</p>\';
												debug.innerHTML += \'<pre>\' + JSON.stringify(response.data, null, 2) + \'</pre>\';
											}
										} else {
											debug.innerHTML += \'<p>ERROR: No data object in response</p>\';
										}
									} else {
										debug.innerHTML += \'<p>ERROR: Response indicates failure</p>\';
										
										if (response.data) {
											debug.innerHTML += \'<pre>\' + JSON.stringify(response.data, null, 2) + \'</pre>\';
										}
									}
								} else {
									debug.innerHTML += \'<p>ERROR: Empty response object</p>\';
								}
							} catch(e) {
								debug.innerHTML += \'<p>ERROR: Failed to parse JSON: \' + e.message + \'</p>\';
								debug.innerHTML += \'<p>Raw response (first 100 chars):</p>\';
								debug.innerHTML += \'<pre>\' + xhr.responseText.substring(0, 100) + \'...</pre>\';
							}
						} else {
							debug.innerHTML += \'<p>ERROR: HTTP status \' + xhr.status + \': \' + xhr.statusText + \'</p>\';
						}
					}
				};
				
				var data = \'action=easyaibloggen_analyze_keyword_density&nonce=' . esc_js( wp_create_nonce( 'easyaibloggen_seo_ajax_nonce' ) ) . '&postId=' . esc_js( $post_id ) . '&auto_get_keyword=true\';
				debug.innerHTML += \'<p>Request data: \' + data + \'</p>\';
				xhr.send(data);
				
				// Log actual AJAX call to console for debugging
				console.log(\'Sending AJAX request to: ' . esc_js( admin_url( 'admin-ajax.php' ) ) . '\');
				console.log(\'Data: \' + data);
			"
			class="button button-primary">
			Analyze Keyword Density
		</button>
		<div id="keyword-loading" style="display: none; margin-top: 10px;">
			<em>Analyzing...</em>
		</div>
		<div id="keyword-results" style="display: none; margin-top: 15px;">
		</div>
		<div id="keyword-debug" style="display: none; margin-top: 15px; padding: 10px; background: #f5f5f5; border: 1px solid #ddd; font-family: monospace; font-size: 12px;">
		</div>
		<div id="keyword-raw" style="display: none; margin-top: 15px; padding: 10px; background: #f8f0f0; border: 1px solid #ddd; overflow: auto; max-height: 200px; font-family: monospace; font-size: 11px;">
		</div>
	</div>';

	// Return the content with our HTML appended.
	return $content . $test_html . $html;
}
add_filter( 'easyaibloggen_metabox_after_content', 'easyaibloggen_add_keyword_density_button' );

// Also add to admin footer for testing.
add_action(
	'admin_enqueue_scripts',
	function () {
		// Enqueue a small admin debug script.
		wp_enqueue_script(
			'easyaibloggen-admin-debug',
			plugin_dir_url( __FILE__ ) . 'js/easyaibloggen-admin-debug.js',
			array( 'jquery' ),
			'1.0.0',
			true
		);
	}
);

// Add a test page to see if we can run AJAX independently.
add_action(
	'admin_menu',
	function () {
		add_submenu_page(
			'tools.php',
			'SEO Debug',
			'SEO Debug',
			'manage_options',
			'easyaibloggen-seo-debug',
			'easyaibloggen_seo_debug_page'
		);
	}
);

/**
 * Display debug information about the SEO plugin.
 *
 * Creates a page in the admin area that shows debugging information
 * about the SEO plugin's files, resources, and settings.
 */
function easyaibloggen_seo_debug_page() {
	// Use proper path detection.
	$plugin_base_dir = plugin_dir_path( __FILE__ );
	$plugin_base_url = plugin_dir_url( __FILE__ );
	$css_path        = $plugin_base_dir . 'css/easyaibloggen-admin.css';
	$js_path         = $plugin_base_dir . 'js/easyaibloggen-seo.js';
	$css_url         = $plugin_base_url . 'css/easyaibloggen-admin.css';
	$js_url          = $plugin_base_url . 'js/easyaibloggen-seo.js';
	?>
	<div class="wrap">
		<h1>SEO Debug Page</h1>
		<p>This page tests the AJAX functionality for keyword density analysis.</p>
		
		<div style="margin-bottom: 20px; padding: 15px; background: #f1f1f1; border-left: 4px solid #46b450;">
			<h2>Plugin Information</h2>
			<p><strong>Plugin Base Directory:</strong> <?php echo esc_html( $plugin_base_dir ); ?></p>
			<p><strong>Plugin Base URL:</strong> <?php echo esc_html( $plugin_base_url ); ?></p>
			<p><strong>CSS File Path:</strong> <?php echo esc_html( $css_path ); ?></p>
			<p><strong>CSS URL:</strong> <?php echo esc_html( $css_url ); ?></p>
			<p><strong>CSS File Exists:</strong> <?php echo file_exists( $css_path ) ? 'Yes' : 'No'; ?></p>
			<p><strong>JS File Path:</strong> <?php echo esc_html( $js_path ); ?></p>
			<p><strong>JS URL:</strong> <?php echo esc_html( $js_url ); ?></p>
			<p><strong>JS File Exists:</strong> <?php echo file_exists( $js_path ) ? 'Yes' : 'No'; ?></p>
			<p><strong>AJAX URL:</strong> <?php echo esc_html( admin_url( 'admin-ajax.php' ) ); ?></p>
			<p><strong>Current Nonce:</strong> <?php echo esc_html( wp_create_nonce( 'easyaibloggen_seo_ajax_nonce' ) ); ?></p>
		</div>
		
		<div style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-left: 4px solid #dc3232;">
			<h2>Test Resources</h2>
			<p>Try loading these resources directly to test if they exist:</p>
			<p><a href="<?php echo esc_url( $css_url ); ?>" target="_blank">Test CSS File</a></p>
			<p><a href="<?php echo esc_url( $js_url ); ?>" target="_blank">Test JS File</a></p>
			<?php if ( file_exists( $js_path ) ) : ?>
				<h3>JavaScript File Contents (first 50 lines):</h3>
				<pre style="max-height: 300px; overflow: auto; background: #f0f0f0; padding: 10px; font-size: 12px;">
				<?php
					// Initialize WP_Filesystem.
					global $wp_filesystem;
				if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
					if ( ! function_exists( 'WP_Filesystem' ) ) {
						require_once ABSPATH . 'wp-admin/includes/file.php';
					}
					WP_Filesystem();
				}

					$js_content     = $wp_filesystem->get_contents( $js_path );
					$lines          = explode( "\n", $js_content );
					$first_50_lines = array_slice( $lines, 0, 50 );
					echo esc_html( implode( "\n", $first_50_lines ) );
				?>
				</pre>
			<?php endif; ?>
		</div>
		
		<h2>Test Using Direct Vanilla JavaScript</h2>
		<p><button type="button" id="test-vanilla-button" class="button button-primary">Test AJAX with Vanilla JS</button></p>
		
		<div id="vanilla-results" style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-left: 4px solid #00a0d2;">
			Results will appear here...
		</div>
		
		<h2>Test Using jQuery</h2>
		<p><button type="button" id="test-ajax-button" class="button button-primary">Test AJAX with jQuery</button></p>
		
		<div id="test-results" style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-left: 4px solid #00a0d2;">
			Results will appear here...
		</div>
		
		<script>
		// Test with vanilla JavaScript
		document.getElementById('test-vanilla-button').addEventListener('click', function() {
			console.log('Vanilla JS button clicked');
			document.getElementById('vanilla-results').innerHTML = 'Sending AJAX request...';
			
			var xhr = new XMLHttpRequest();
			xhr.open('POST', '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', true);
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			
			xhr.onreadystatechange = function() {
				if (xhr.readyState === 4) {
					console.log('Response status:', xhr.status);
					console.log('Response text:', xhr.responseText);
					
					if (xhr.status === 200) {
						try {
							var response = JSON.parse(xhr.responseText);
							document.getElementById('vanilla-results').innerHTML = '<pre>' + JSON.stringify(response, null, 2) + '</pre>';
						} catch (e) {
							document.getElementById('vanilla-results').innerHTML = 'Error parsing response: ' + e.message + '<br>Raw response: ' + xhr.responseText;
						}
					} else {
						document.getElementById('vanilla-results').innerHTML = 'Error: ' + xhr.status + ' ' + xhr.statusText;
					}
				}
			};
			
			xhr.send('action=easyaibloggen_analyze_keyword_density&nonce=<?php echo esc_js( wp_create_nonce( 'easyaibloggen_seo_ajax_nonce' ) ); ?>&postId=1&auto_get_keyword=true');
		});
		
		// Test with jQuery if available
		jQuery(document).ready(function($) {
			console.log('jQuery ready');
			
			$('#test-ajax-button').on('click', function() {
				console.log('jQuery button clicked');
				$('#test-results').html('Sending AJAX request...');
				
				$.ajax({
					url: '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>',
					type: 'POST',
					data: {
						action: 'easyaibloggen_analyze_keyword_density',
						nonce: '<?php echo esc_js( wp_create_nonce( 'easyaibloggen_seo_ajax_nonce' ) ); ?>',
						postId: 1,
						auto_get_keyword: true
					},
					success: function(response) {
						console.log('AJAX success:', response);
						$('#test-results').html('<pre>' + JSON.stringify(response, null, 2) + '</pre>');
					},
					error: function(jqXHR, textStatus, errorThrown) {
						console.error('AJAX error:', textStatus, errorThrown);
						$('#test-results').html('Error: ' + textStatus + ' - ' + errorThrown);
					}
				});
			});
		});
		</script>
	</div>
	<?php
}

// Add a test action that will always log.
add_action(
	'init',
	function () {
		// Create a test log entry on every page load.
		$log_file = plugin_dir_path( __FILE__ ) . 'plugin-loaded.log';

		// Initialize WP_Filesystem if not already initialized.
		global $wp_filesystem;
		if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
			if ( ! function_exists( 'WP_Filesystem' ) ) {
				require_once ABSPATH . 'wp-admin/includes/file.php';
			}
			WP_Filesystem();
		}

		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Plugin initiated. AJAX hooks registered.\n", FILE_APPEND );
	}
);

/**
 * Log button click action (AJAX handler).
 */
function easyaibloggen_log_button_click() {
	// Verify nonce.
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'easyaibloggen_seo_nonce' ) ) {
		wp_send_json_error( 'Security check failed' );
		return;
	}

	$log_file = plugin_dir_path( __FILE__ ) . 'button-click.log';
	$post_id  = isset( $_POST['post_id'] ) ? intval( wp_unslash( $_POST['post_id'] ) ) : 0;

	// Initialize WP_Filesystem.
	global $wp_filesystem;
	if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
	}

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Button clicked for post ID: {$post_id}\n", FILE_APPEND );

	wp_send_json_success( 'Click logged' );
	exit;
}

/**
 * SEO Button Shortcode Handler.
 *
 * Creates a button that users can click to analyze keyword density.
 *
 * @param array $atts Shortcode attributes.
 * @return string HTML output for the shortcode.
 */
function easyaibloggen_seo_button_shortcode( $atts ) {
	// Merge provided attributes with defaults.
	$atts = shortcode_atts(
		array(
			'post_id' => get_the_ID(),
		),
		$atts,
		'easyaibloggen_seo_button'
	);

	global $post;

	// Check if post exists.
	if ( ! $post ) {
		return 'Error: No post context available.';
	}

	// Get the current post ID.
	$post_id = $post->ID;

	// Get the preferred keyword from post meta.
	$preferred_keyword = get_post_meta( $post_id, '_easyaibloggen_preferred_keyword', true );

	// Log shortcode usage.
	$log_file = plugin_dir_path( __FILE__ ) . 'shortcode-debug.log';

	// Initialize WP_Filesystem.
	global $wp_filesystem;
	if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
	}

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Shortcode used for post ID: {$post_id}, Keyword: {$preferred_keyword}\n", FILE_APPEND );

	// Super simple test HTML.
	?>
	<div style="margin: 20px 0; padding: 15px; background: #e9f7e9; border: 1px solid #4CAF50;">
		<h3>Direct Shortcode Button</h3>
		<p>This button was added via a direct shortcode.</p>
		<p>Post ID: <strong><?php echo esc_html( $post_id ); ?></strong></p>
		<p>Keyword: <strong><?php echo esc_html( $preferred_keyword ); ?></strong></p>
		<button 
			type="button" 
			onclick="
				console.log('Shortcode button clicked');
				document.getElementById('shortcode-result').textContent = 'Sending request...';
				
				fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					body: 'action=easyaibloggen_analyze_keyword_density&test=true&post_id=<?php echo esc_js( $post_id ); ?>'
				})
				.then(response => response.json())
				.then(data => {
					console.log('Response:', data);
					document.getElementById('shortcode-result').textContent = 'Success! Check console for details.';
				})
				.catch(error => {
					console.error('Error:', error);
					document.getElementById('shortcode-result').textContent = 'Error: ' + error;
				});
			"
			class="button button-primary">
			Shortcode Test Button
		</button>
		<p id="shortcode-result" style="margin-top: 10px; font-family: monospace;"></p>
		</div>
	<?php

	// Return the buffered content.
	return ob_get_clean();
}
add_shortcode( 'seo_button', 'easyaibloggen_seo_button_shortcode' );

// Add an admin notice to display our button on all admin pages.
add_action(
	'admin_notices',
	function () {
		global $post;

		// Only show on post edit screens.
		$screen = get_current_screen();
		if ( ! $screen || 'post' !== $screen->base || ! $post ) {
			return;
		}

		$post_id           = $post->ID;
		$preferred_keyword = get_post_meta( $post_id, '_easyaibloggen_preferred_keyword', true );

		// Log admin notice display.
		$log_file = plugin_dir_path( __FILE__ ) . 'admin-notice-debug.log';

		// Initialize WP_Filesystem.
		global $wp_filesystem;
		if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
			if ( ! function_exists( 'WP_Filesystem' ) ) {
				require_once ABSPATH . 'wp-admin/includes/file.php';
			}
			WP_Filesystem();
		}

		$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Admin notice displayed for post ID: {$post_id}\n", FILE_APPEND );

		// Output the notice.
		?>
	<div class="notice notice-info">
		<h3>SEO Keyword Density Analyzer</h3>
		<p>Post ID: <strong><?php echo esc_html( $post_id ); ?></strong></p>
		<p>Keyword: <strong><?php echo esc_html( $preferred_keyword ); ?></strong></p>
		<button 
			type="button" 
			onclick="
				console.log('Admin notice button clicked');
				document.getElementById('admin-notice-result').textContent = 'Sending request...';
				
				fetch('<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					body: 'action=easyaibloggen_analyze_keyword_density&test=true&post_id=<?php echo esc_js( $post_id ); ?>'
				})
				.then(response => response.json())
				.then(data => {
					console.log('Response:', data);
					document.getElementById('admin-notice-result').innerHTML = '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
				})
				.catch(error => {
					console.error('Error:', error);
					document.getElementById('admin-notice-result').textContent = 'Error: ' + error;
				});
			"
			class="button button-primary">
			Admin Notice Test Button
		</button>
		<div id="admin-notice-result" style="margin-top: 10px; padding: 10px; background: #f5f5f5; font-family: monospace; max-height: 200px; overflow: auto;"></div>
		</div>
		<?php
	}
);

/**
 * Basic Button Shortcode Handler.
 *
 * Creates a simple button without JavaScript dependencies.
 *
 * @param array $atts Shortcode attributes.
 * @return string HTML output for the shortcode.
 */
function easyaibloggen_basic_button_shortcode( $atts = array() ) {
	// Extract shortcode attributes with defaults.
	$attributes = shortcode_atts(
		array(
			'title' => 'Basic HTML Only Button',
		),
		$atts,
		'basic_button'
	);

	global $post;

	if ( ! $post ) {
		return 'Error: No post context available.';
	}

	$post_id           = $post->ID;
	$preferred_keyword = get_post_meta( $post_id, '_easyaibloggen_preferred_keyword', true );

	// Log shortcode usage.
	$log_file = plugin_dir_path( __FILE__ ) . 'basic-shortcode.log';

	// Initialize WP_Filesystem.
	global $wp_filesystem;
	if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
	}

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Basic shortcode used for post ID: {$post_id}\n", FILE_APPEND );

	// Return HTML directly - no PHP or JavaScript.
	return '
    <div style="margin: 20px 0; padding: 15px; background: #ffeeee; border: 1px solid #ff0000;">
        <h3>' . esc_html( $attributes['title'] ) . '</h3>
        <p>This is a simple HTML button with no JavaScript.</p>
        <p>Post ID: <strong>' . esc_html( $post_id ) . '</strong></p>
        <p>Keyword: <strong>' . esc_html( $preferred_keyword ) . '</strong></p>
        <a href="#" class="button button-primary">Plain HTML Button (No JS)</a>
        <p>Check if this button displays properly.</p>
    </div>
    ';
}
add_shortcode( 'basic_button', 'easyaibloggen_basic_button_shortcode' );

/**
 * Form Shortcode Handler.
 *
 * Creates a form that can be used to analyze keyword density.
 *
 * @param array $atts Shortcode attributes.
 * @return string HTML output for the shortcode.
 */
function easyaibloggen_form_shortcode( $atts = array() ) {
	// Extract shortcode attributes with defaults.
	$attributes = shortcode_atts(
		array(
			'title' => 'Keyword Analysis Form',
		),
		$atts,
		'form_shortcode'
	);

	global $post;

	if ( ! $post ) {
		return 'Error: No post context available.';
	}

	$post_id           = $post->ID;
	$preferred_keyword = get_post_meta( $post_id, '_easyaibloggen_preferred_keyword', true );

	// Log shortcode usage.
	$log_file = plugin_dir_path( __FILE__ ) . 'form-shortcode.log';

	// Initialize WP_Filesystem.
	global $wp_filesystem;
	if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		WP_Filesystem();
	}

	$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Form shortcode used for post ID: {$post_id}\n", FILE_APPEND );

	// Return a simple form that posts directly to admin-ajax.php.
	return '
    <div style="margin: 20px 0; padding: 15px; background: #ffe8e8; border: 1px solid #ff6b6b;">
        <h3>' . esc_html( $attributes['title'] ) . '</h3>
        <p>This is a simple form that posts directly to the AJAX endpoint.</p>
        <form action="' . esc_url( admin_url( 'admin-ajax.php' ) ) . '" method="post" target="_blank">
            <input type="hidden" name="action" value="easyaibloggen_analyze_keyword_density">
            <input type="hidden" name="nonce" value="' . wp_create_nonce( 'easyaibloggen_seo_ajax_nonce' ) . '">
            <input type="hidden" name="postId" value="' . esc_attr( $post_id ) . '">
            <input type="hidden" name="test" value="true">
            <input type="hidden" name="hide_apply_button" value="true">
            <p>Post ID: <strong>' . esc_html( $post_id ) . '</strong></p>
            <p>Keyword: <strong>' . esc_html( $preferred_keyword ) . '</strong></p>
            <button type="submit" class="button button-primary">Submit Form Test</button>
        </form>
    </div>
    ';
}
add_shortcode( 'form_test', 'easyaibloggen_form_shortcode' );

// Add filter debug logging.
add_action(
	'all',
	function ( $tag ) {
		if ( 'easyaibloggen_metabox_after_content' === $tag ) {
			$log_file = plugin_dir_path( __FILE__ ) . 'filter-debug.log';

			// Initialize WP_Filesystem.
			global $wp_filesystem;
			if ( ! isset( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
				if ( ! function_exists( 'WP_Filesystem' ) ) {
					require_once ABSPATH . 'wp-admin/includes/file.php';
				}
				WP_Filesystem();
			}

			$wp_filesystem->put_contents( $log_file, gmdate( '[Y-m-d H:i:s] ' ) . "Filter 'easyaibloggen_metabox_after_content' is firing\n", FILE_APPEND );
		}
	}
);

add_action( 'wp_ajax_easyaibloggen_log_button_click', 'easyaibloggen_log_button_click' );
add_action( 'wp_ajax_nopriv_easyaibloggen_log_button_click', 'easyaibloggen_log_button_click' );
