<?php
/**
 * SEO Dashboard Enhancement for Easy AI Blog Generator
 *
 * This file adds enhanced SEO visualization and metrics to the plugin
 * without modifying the core functionality of existing files.
 *
 * @package EasyAIBlogGenerator
 */

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

/**
 * Register and enqueue the SEO Dashboard assets.
 */
function easyaibloggen_seo_dashboard_assets() {
	// Only load on post edit screen.
	$screen = get_current_screen();
	if ( ! $screen || 'post' !== $screen->base ) {
		return;
	}

	// Enqueue styles.
	wp_enqueue_style(
		'easyaibloggen-seo-dashboard',
		plugin_dir_url( __FILE__ ) . 'css/easyaibloggen-seo-dashboard.css',
		array(),
		'1.0.0'
	);

	// Enqueue scripts.
	wp_enqueue_script(
		'easyaibloggen-seo-dashboard',
		plugin_dir_url( __FILE__ ) . 'js/easyaibloggen-seo-dashboard.js',
		array( 'jquery' ),
		'1.0.0',
		true
	);

	// Localize script with necessary data.
	wp_localize_script(
		'easyaibloggen-seo-dashboard',
		'easySEODashboard',
		array(
			'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
			'nonce'     => wp_create_nonce( 'easyaibloggen_seo_nonce' ),
			'postId'    => get_the_ID(),
			'pluginUrl' => plugin_dir_url( __FILE__ ),
			'strings'   => array(
				'analyzing'      => __( 'Analyzing content...', 'easy-ai-blog-generator' ),
				'errorMessage'   => __( 'An error occurred. Please try again.', 'easy-ai-blog-generator' ),
				'noKeyword'      => __( 'Please enter a focus keyword to analyze.', 'easy-ai-blog-generator' ),
				'applyChanges'   => __( 'Apply Changes', 'easy-ai-blog-generator' ),
				'appliedChanges' => __( 'Changes Applied', 'easy-ai-blog-generator' ),
			),
		)
	);

	// Enqueue the visualizations CSS.
	wp_enqueue_style(
		'easyaibloggen-seo-visualizations',
		plugin_dir_url( __FILE__ ) . 'css/easyaibloggen-seo-visualizations.css',
		array(),
		'1.0.0'
	);
}
add_action( 'admin_enqueue_scripts', 'easyaibloggen_seo_dashboard_assets' );

/**
 * Add the SEO Dashboard metabox to the post editor.
 */
function easyaibloggen_add_seo_dashboard_metabox() {
	add_meta_box(
		'easyaibloggen-seo-dashboard',
		__( 'SEO Content Optimization Dashboard', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_seo_dashboard',
		'post',
		'normal',
		'high'
	);
}
add_action( 'add_meta_boxes', 'easyaibloggen_add_seo_dashboard_metabox' );

/**
 * Render the SEO Dashboard.
 *
 * @param WP_Post $post The post object.
 */
function easyaibloggen_render_seo_dashboard( $post ) {
	// Get the focus keyword.
	$focus_keyword = get_post_meta( $post->ID, '_easyaibloggen_focus_keyword', true );
	if ( empty( $focus_keyword ) ) {
		$focus_keyword = get_post_meta( $post->ID, '_easyaibloggen_preferred_keyword', true );
	}

	// Determine the appropriate message based on whether a keyword exists
	$message = empty($focus_keyword) 
		? __( 'No preferred keyword found for this post. Please set one to enable SEO analysis.', 'easy-ai-blog-generator' )
		: sprintf( __( 'Current preferred keyword is "%s". You can change it below if needed.', 'easy-ai-blog-generator' ), esc_html($focus_keyword) );

	?>
	<div class="easyai-seo-dashboard-wrapper">
		<div class="easyai-preferred-keyword-form" style="background: #fff; padding: 15px; margin-bottom: 20px; border: 1px solid #ccd0d4; border-left: 4px solid #007cba;">
			<h3 style="margin-top: 0;"><?php esc_html_e( 'Preferred Keyword', 'easy-ai-blog-generator' ); ?></h3>
			<p><?php echo $message; ?></p>
			<div style="display: flex; gap: 10px; align-items: center;">
				<input type="text" 
					id="easyai-new-preferred-keyword" 
					class="regular-text" 
					placeholder="<?php esc_attr_e( 'Enter preferred keyword', 'easy-ai-blog-generator' ); ?>" 
					value="<?php echo esc_attr($focus_keyword); ?>" 
					style="flex: 1;">
				<button type="button" 
					id="easyai-save-preferred-keyword" 
					class="button button-primary">
					<?php echo empty($focus_keyword) 
						? esc_html__( 'Save Keyword', 'easy-ai-blog-generator' ) 
						: esc_html__( 'Update Keyword', 'easy-ai-blog-generator' ); 
					?>
				</button>
			</div>
			<div id="easyai-keyword-save-status" style="margin-top: 10px;"></div>
		</div>
		<!-- At-a-Glance Summary -->
		<div class="easyai-seo-summary-panel">
			<h3><?php esc_html_e( 'SEO At-a-Glance', 'easy-ai-blog-generator' ); ?></h3>
			<div class="easyai-seo-summary-grid">
				<div class="easyai-seo-summary-item">
					<span class="easyai-seo-label"><?php esc_html_e( 'Current Keyword:', 'easy-ai-blog-generator' ); ?></span>
					<span class="easyai-seo-value" id="easyai-current-keyword"><?php echo esc_html( $focus_keyword ); ?></span>
				</div>
				<div class="easyai-seo-summary-item">
					<span class="easyai-seo-label"><?php esc_html_e( 'Density:', 'easy-ai-blog-generator' ); ?></span>
					<span class="easyai-seo-value" id="easyai-keyword-density">--</span>
				</div>
				<div class="easyai-seo-summary-item">
					<span class="easyai-seo-label"><?php esc_html_e( 'Occurrences:', 'easy-ai-blog-generator' ); ?></span>
					<span class="easyai-seo-value" id="easyai-keyword-occurrences">--</span>
				</div>
				<div class="easyai-seo-summary-item">
					<span class="easyai-seo-label"><?php esc_html_e( 'Word Count:', 'easy-ai-blog-generator' ); ?></span>
					<span class="easyai-seo-value" id="easyai-word-count">--</span>
				</div>
				<div class="easyai-seo-summary-item easyai-overall-score">
					<span class="easyai-seo-label"><?php esc_html_e( 'Overall Score:', 'easy-ai-blog-generator' ); ?></span>
					<span class="easyai-seo-value" id="easyai-overall-score">--</span>
				</div>
			</div>
			<button type="button" id="easyai-analyze-content" class="button button-primary"><?php esc_html_e( 'Analyze Content', 'easy-ai-blog-generator' ); ?></button>
			<span id="easyai-analysis-status" class="easyai-spinner-text"></span>
		</div>

		<div class="easyai-seo-tabs">
			<div class="easyai-seo-tab-nav">
				<button type="button" class="easyai-tab-button active" data-tab="checklist"><?php esc_html_e( 'SEO Checklist', 'easy-ai-blog-generator' ); ?></button>
				<button type="button" class="easyai-tab-button" data-tab="keywords"><?php esc_html_e( 'Keyword Suggestions', 'easy-ai-blog-generator' ); ?></button>
				<button type="button" class="easyai-tab-button" data-tab="overused"><?php esc_html_e( 'Overused Keywords', 'easy-ai-blog-generator' ); ?></button>
				<button type="button" class="easyai-tab-button" data-tab="actions"><?php esc_html_e( 'Improvement Actions', 'easy-ai-blog-generator' ); ?></button>
			</div>

			<!-- SEO Best Practices Checklist -->
			<div class="easyai-tab-content active" id="easyai-tab-checklist">
				<h3><?php esc_html_e( 'SEO Best Practices Checklist', 'easy-ai-blog-generator' ); ?></h3>
				<div class="easyai-checklist">
					<div class="easyai-checklist-item" id="check-title">
						<span class="easyai-checkbox"></span>
						<span class="easyai-checklist-text"><?php esc_html_e( 'Focus keyword in title', 'easy-ai-blog-generator' ); ?></span>
					</div>
					<div class="easyai-checklist-item" id="check-first-paragraph">
						<span class="easyai-checkbox"></span>
						<span class="easyai-checklist-text"><?php esc_html_e( 'Focus keyword in first 100 words', 'easy-ai-blog-generator' ); ?></span>
					</div>
					<div class="easyai-checklist-item" id="check-h2">
						<span class="easyai-checkbox"></span>
						<span class="easyai-checklist-text"><?php esc_html_e( 'Focus keyword in at least one H2 heading', 'easy-ai-blog-generator' ); ?></span>
					</div>
					<div class="easyai-checklist-item" id="check-meta">
						<span class="easyai-checkbox"></span>
						<span class="easyai-checklist-text"><?php esc_html_e( 'Focus keyword in meta description', 'easy-ai-blog-generator' ); ?></span>
					</div>
					<div class="easyai-checklist-item" id="check-variants">
						<span class="easyai-checkbox"></span>
						<span class="easyai-checklist-text"><?php esc_html_e( 'Natural keyword variations included', 'easy-ai-blog-generator' ); ?></span>
					</div>
					<div class="easyai-checklist-item" id="check-density">
						<span class="easyai-checkbox"></span>
						<span class="easyai-checklist-text"><?php esc_html_e( 'Optimal keyword density (1-3%)', 'easy-ai-blog-generator' ); ?></span>
					</div>
				</div>
			</div>

			<!-- Keyword Variant Suggestions -->
			<div class="easyai-tab-content" id="easyai-tab-keywords">
				<h3><?php esc_html_e( 'Keyword Variant Suggestions', 'easy-ai-blog-generator' ); ?></h3>
				<div id="easyai-variant-container">
					<p class="easyai-placeholder-text"><?php esc_html_e( 'Click "Analyze Content" to generate keyword variants and their usage count.', 'easy-ai-blog-generator' ); ?></p>
				</div>
			</div>

			<!-- Overused Keyword Sections -->
			<div class="easyai-tab-content" id="easyai-tab-overused">
				<h3><?php esc_html_e( 'Overused Keyword Sections', 'easy-ai-blog-generator' ); ?></h3>
				<div id="easyai-overused-container">
					<p class="easyai-placeholder-text"><?php esc_html_e( 'Click "Analyze Content" to identify sections with too many keyword mentions.', 'easy-ai-blog-generator' ); ?></p>
				</div>
			</div>

			<!-- Actionable Improvement Metrics -->
			<div class="easyai-tab-content" id="easyai-tab-actions">
				<h3><?php esc_html_e( 'Recommended Improvement Actions', 'easy-ai-blog-generator' ); ?></h3>
				<div id="easyai-actions-container">
					<p class="easyai-placeholder-text"><?php esc_html_e( 'Click "Analyze Content" to get specific improvement suggestions.', 'easy-ai-blog-generator' ); ?></p>
				</div>
			</div>
		</div>
	</div>

	<?php wp_nonce_field( 'easyaibloggen_seo_nonce', 'easyaibloggen_seo_nonce' ); ?>
	<?php
}

/**
 * AJAX handler for analyzing SEO content.
 */
function easyaibloggen_analyze_seo_content() {
	// Check 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;
	}

	// Get post ID.
	$post_id = isset( $_POST['postId'] ) ? intval( wp_unslash( $_POST['postId'] ) ) : 0;
	if ( ! $post_id ) {
		wp_send_json_error( 'Invalid post ID' );
		return;
	}

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

	$title   = $post->post_title;
	$content = $post->post_content;
	$excerpt = $post->post_excerpt;

	// Get meta description if using an SEO plugin.
	$meta_description = '';
	// Try to get meta description from Yoast SEO.
	$meta_description = get_post_meta( $post_id, '_yoast_wpseo_metadesc', true );

	// If no Yoast meta, try All in One SEO Pack.
	if ( empty( $meta_description ) ) {
		$meta_description = get_post_meta( $post_id, '_aioseop_description', true );
	}

	// If still empty, use excerpt as fallback.
	if ( empty( $meta_description ) ) {
		$meta_description = $excerpt;
	}

	// Get focus keyword.
	$keyword = get_post_meta( $post_id, '_easyaibloggen_focus_keyword', true );
	if ( empty( $keyword ) ) {
		$keyword = get_post_meta( $post_id, '_easyaibloggen_preferred_keyword', true );
	}

	if ( empty( $keyword ) ) {
		wp_send_json_error( 'No focus keyword found' );
		return;
	}

	// Prepare content for analysis (strip HTML).
	$clean_content = wp_strip_all_tags( $content );
	$word_count    = str_word_count( $clean_content );

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

	// Check for focus keyword in title.
	$title_check = ( strpos( strtolower( $title ), strtolower( $keyword ) ) !== false );

	// Check for focus keyword in first 100 words.
	$first_100_words       = implode( ' ', array_slice( explode( ' ', $clean_content ), 0, 100 ) );
	$first_paragraph_check = ( strpos( strtolower( $first_100_words ), strtolower( $keyword ) ) !== false );

	// Check for focus keyword in H2.
	$h2_check = ( preg_match( '/<h2[^>]*>.*' . preg_quote( $keyword, '/' ) . '.*<\/h2>/i', $content ) > 0 );

	// Check for focus keyword in meta description.
	$meta_check = ( ! empty( $meta_description ) && strpos( strtolower( $meta_description ), strtolower( $keyword ) ) !== false );

	// Generate LSI keyword suggestions.
	$lsi_keywords = easyaibloggen_generate_lsi_keywords( $keyword, $clean_content );

	// Identify overused sections.
	$overused_sections = easyaibloggen_identify_overused_sections( $content, $keyword );

	// Generate improvement actions.
	$improvement_actions = easyaibloggen_generate_improvement_actions( $title_check, $first_paragraph_check, $h2_check, $meta_check, $is_optimal_density, $density, $word_count );

	// Calculate overall score.
	$score_components = array(
		$title_check ? 15 : 0,
		$first_paragraph_check ? 15 : 0,
		$h2_check ? 15 : 0,
		$meta_check ? 15 : 0,
		$is_optimal_density ? 25 : max( 0, 25 - abs( $density - 2 ) * 10 ),
		! empty( $lsi_keywords ) ? 15 : 0,
	);
	$overall_score    = min( 100, array_sum( $score_components ) );

	// Prepare response.
	$response = array(
		'keyword'            => $keyword,
		'density'            => $density,
		'wordCount'          => $word_count,
		'keywordCount'       => $keyword_count,
		'overallScore'       => $overall_score,
		'checksStatus'       => array(
			'title'          => $title_check,
			'firstParagraph' => $first_paragraph_check,
			'h2'             => $h2_check,
			'meta'           => $meta_check,
			'variants'       => ! empty( $lsi_keywords ),
			'density'        => $is_optimal_density,
		),
		'lsiKeywords'        => $lsi_keywords,
		'overusedSections'   => $overused_sections,
		'improvementActions' => $improvement_actions,
	);

	wp_send_json_success( $response );
}
add_action( 'wp_ajax_easyaibloggen_analyze_seo_content', 'easyaibloggen_analyze_seo_content' );

/**
 * Generate LSI keyword suggestions based on the focus keyword.
 *
 * @param string $keyword The focus keyword.
 * @param string $content The post content.
 * @return array LSI keywords with usage counts.
 */
function easyaibloggen_generate_lsi_keywords( $keyword, $content ) {
	// This function would typically use an API call to get LSI keywords.
	// For demonstration, we'll use a simple algorithm to generate variants.

	$keywords = array();

	// 1. Word combinations
	$keyword_parts = explode( ' ', $keyword );
	if ( count( $keyword_parts ) > 1 ) {
		$keywords[] = array(
			'keyword'    => $keyword_parts[1] . ' ' . $keyword_parts[0],
			'count'      => substr_count( strtolower( $content ), strtolower( $keyword_parts[1] . ' ' . $keyword_parts[0] ) ),
			'suggestion' => 'Try using this variant in your content for better keyword diversity.',
		);
	}

	// 2. Add common prefixes/suffixes
	$common_prefixes = array( 'best', 'top', 'how to', 'guide to', 'ways to' );
	$common_suffixes = array( 'guide', 'tutorial', 'tips', 'examples', 'techniques' );

	foreach ( $common_prefixes as $prefix ) {
		$variant    = $prefix . ' ' . $keyword;
		$keywords[] = array(
			'keyword'    => $variant,
			'count'      => substr_count( strtolower( $content ), strtolower( $variant ) ),
			'suggestion' => 'Consider adding this variant to your H2 headings.',
		);
	}

	foreach ( $common_suffixes as $suffix ) {
		$variant    = $keyword . ' ' . $suffix;
		$keywords[] = array(
			'keyword'    => $variant,
			'count'      => substr_count( strtolower( $content ), strtolower( $variant ) ),
			'suggestion' => 'This variant would work well in a subheading or conclusion.',
		);
	}

	// 3. Add some synonyms (in a real implementation, these would come from a thesaurus API)
	if ( strpos( $keyword, 'how to' ) !== false ) {
		$variant    = str_replace( 'how to', 'guide for', $keyword );
		$keywords[] = array(
			'keyword'    => $variant,
			'count'      => substr_count( strtolower( $content ), strtolower( $variant ) ),
			'suggestion' => 'Use this alternative phrasing to avoid repetition.',
		);
	}

	// This is a simplistic implementation. In a real-world scenario,
	// you would use natural language processing APIs or third-party
	// services to generate more sophisticated keyword variants.

	return $keywords;
}

/**
 * Identify sections of content with too many keyword mentions.
 *
 * @param string $content The post content.
 * @param string $keyword The focus keyword.
 * @return array Overused sections with analysis.
 */
function easyaibloggen_identify_overused_sections( $content, $keyword ) {
	$overused_sections = array();

	// Extract paragraphs from content.
	preg_match_all( '/<p>(.*?)<\/p>/s', $content, $paragraphs );

	if ( ! empty( $paragraphs[1] ) ) {
		foreach ( $paragraphs[1] as $index => $paragraph ) {
			$clean_paragraph = wp_strip_all_tags( $paragraph );
			$word_count      = str_word_count( $clean_paragraph );

			// Skip very short paragraphs.
			if ( $word_count < 20 ) {
				continue;
			}

			$keyword_count     = substr_count( strtolower( $clean_paragraph ), strtolower( $keyword ) );
			$paragraph_density = ( $word_count > 0 ) ? ( $keyword_count / $word_count ) * 100 : 0;

			// If density is over 5% and has at least 2 occurrences, flag it.
			if ( $paragraph_density > 5 && $keyword_count >= 2 ) {
				// Truncate paragraph for display if it's too long.
				$display_paragraph = ( strlen( $clean_paragraph ) > 150 )
					? substr( $clean_paragraph, 0, 150 ) . '...'
					: $clean_paragraph;

				// Calculate recommended maximum based on 3% density.
				$recommended_max = ceil( $word_count * 0.03 );

				$overused_sections[] = array(
					'paragraph'      => $display_paragraph,
					'keywordCount'   => $keyword_count,
					'wordCount'      => $word_count,
					'density'        => round( $paragraph_density, 2 ),
					'recommendedMax' => $recommended_max,
					'suggestion'     => 'Try reducing keyword usage in this paragraph to ' . $recommended_max . ' occurrence(s), or use synonyms and variations.',
				);
			}
		}
	}

	return $overused_sections;
}

/**
 * Generate improvement actions based on analysis results.
 *
 * @param bool  $title_check Whether the keyword is in the title.
 * @param bool  $first_paragraph_check Whether the keyword is in the first paragraph.
 * @param bool  $h2_check Whether the keyword is in H2 headings.
 * @param bool  $meta_check Whether the keyword is in the meta description.
 * @param bool  $is_optimal_density Whether the keyword density is optimal.
 * @param float $density The current keyword density.
 * @param int   $word_count The total word count.
 * @return array Improvement actions.
 */
function easyaibloggen_generate_improvement_actions( $title_check, $first_paragraph_check, $h2_check, $meta_check, $is_optimal_density, $density, $word_count ) {
	$actions = array();

	if ( ! $title_check ) {
		$actions[] = array(
			'action'      => 'Add your focus keyword to the title',
			'impact'      => '+15 points',
			'priority'    => 'High',
			'description' => 'Including your focus keyword in the title is critical for SEO and helps search engines understand your content.',
		);
	}

	if ( ! $first_paragraph_check ) {
		$actions[] = array(
			'action'      => 'Add your focus keyword to the first paragraph',
			'impact'      => '+15 points',
			'priority'    => 'High',
			'description' => 'Search engines give more weight to keywords that appear early in the content.',
		);
	}

	if ( ! $h2_check ) {
		$actions[] = array(
			'action'      => 'Include your focus keyword in at least one H2 heading',
			'impact'      => '+15 points',
			'priority'    => 'Medium',
			'description' => 'Using your keyword in headings helps structure your content and signals relevance to search engines.',
		);
	}

	if ( ! $meta_check ) {
		$actions[] = array(
			'action'      => 'Add your focus keyword to the meta description',
			'impact'      => '+15 points',
			'priority'    => 'Medium',
			'description' => 'Meta descriptions are often displayed in search results, and including your keyword can improve click-through rates.',
		);
	}

	if ( ! $is_optimal_density ) {
		if ( $density < 1 ) {
			$actions[] = array(
				'action'      => 'Increase keyword density from ' . $density . '% to between 1-3%',
				'impact'      => '+' . ceil( 25 - abs( $density - 2 ) * 10 ) . ' points',
				'priority'    => 'Medium',
				'description' => 'Your keyword density is too low. Add more instances of your keyword naturally throughout the text.',
			);
		} elseif ( $density > 3 ) {
			$actions[] = array(
				'action'      => 'Decrease keyword density from ' . $density . '% to between 1-3%',
				'impact'      => '+' . ceil( 25 - abs( $density - 2 ) * 10 ) . ' points',
				'priority'    => 'Medium',
				'description' => 'Your keyword density is too high, which might appear as keyword stuffing. Replace some instances with synonyms or rephrase sentences.',
			);
		}
	}

	if ( $word_count < 300 ) {
		$target_word_count = 300;
		$words_needed      = $target_word_count - $word_count;
		$actions[]         = array(
			'action'      => 'Add at least ' . $words_needed . ' more words to reach a minimum length of 300 words',
			'impact'      => '+10 points',
			'priority'    => 'High',
			'description' => 'Content that is too short may not be considered valuable by search engines. Aim for at least 300 words.',
		);
	} elseif ( $word_count < 600 ) {
		$target_word_count = 600;
		$words_needed      = $target_word_count - $word_count;
		$actions[]         = array(
			'action'      => 'Add about ' . $words_needed . ' more words to reach at least 600 words',
			'impact'      => '+5 points',
			'priority'    => 'Medium',
			'description' => 'Longer content (600+ words) tends to rank better for competitive keywords. Consider expanding your content with more valuable information.',
		);
	}

	return $actions;
}

/**
 * Include the SEO Dashboard in WordPress init.
 */
function easyaibloggen_include_seo_dashboard() {
	// No direct initialization needed, hooks are already set up.
}
add_action( 'init', 'easyaibloggen_include_seo_dashboard' );

/**
 * AJAX handler for saving the preferred keyword.
 */
function easyaibloggen_save_preferred_keyword() {
	// Check 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;
	}

	// Get post ID and keyword
	$post_id = isset( $_POST['postId'] ) ? intval( wp_unslash( $_POST['postId'] ) ) : 0;
	$keyword = isset( $_POST['keyword'] ) ? sanitize_text_field( wp_unslash( $_POST['keyword'] ) ) : '';

	// Validate input
	if ( ! $post_id || empty( $keyword ) ) {
		wp_send_json_error( 'Invalid input parameters' );
		return;
	}

	// Check if post exists
	if ( ! get_post( $post_id ) ) {
		wp_send_json_error( 'Post not found' );
		return;
	}

	// Save the preferred keyword
	update_post_meta( $post_id, '_easyaibloggen_preferred_keyword', $keyword );
	update_post_meta( $post_id, '_easyaibloggen_focus_keyword', $keyword );

	wp_send_json_success( array(
		'message' => 'Keyword saved successfully',
		'keyword' => $keyword
	) );
}
add_action( 'wp_ajax_easyaibloggen_save_preferred_keyword', 'easyaibloggen_save_preferred_keyword' );
