<?php
/**
 * Remove Keyword Density Analysis from Blog Posts
 *
 * This file removes the keyword density analysis section that appears in published blog posts
 * while preserving the functionality in the WordPress admin metabox.
 *
 * @package EasyAIBlogGenerator
 */

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

/**
 * Remove the front-end keyword analysis.
 */
function easyaibloggen_remove_frontend_keyword_analysis() {
	// Remove the filter that adds the keyword density button to post content.
	remove_filter( 'the_content', 'easyaibloggen_add_keyword_density_button' );

	// Remove shortcodes from being processed.
	remove_shortcode( 'seo_button' );
	remove_shortcode( 'basic_button' );
	remove_shortcode( 'form_test' );

	// If the content has already been filtered, we need to remove the HTML.
	add_filter( 'the_content', 'easyaibloggen_clean_post_content', 999 );
}
add_action( 'init', 'easyaibloggen_remove_frontend_keyword_analysis' );

/**
 * Clean the post content by removing any keyword analysis HTML.
 *
 * @param string $content The post content.
 * @return string Cleaned content.
 */
function easyaibloggen_clean_post_content( $content ) {
	// Remove the keyword analysis box if it exists.
	$pattern = '/<div[^>]*>\s*<h3>\s*Keyword Density Analysis.*?<\/div>\s*<\/div>/s';
	$content = preg_replace( $pattern, '', $content );

	// Remove the test button if it exists.
	$pattern = '/<div[^>]*>\s*<h3>\s*AJAX Test Button.*?<\/div>\s*<\/div>/s';
	$content = preg_replace( $pattern, '', $content );

	// Remove any shortcode output that might be in the content.
	$pattern = '/<div[^>]*>\s*<h3>\s*Direct Shortcode Button.*?<\/div>/s';
	$content = preg_replace( $pattern, '', $content );

	$pattern = '/<div[^>]*>\s*<h3>\s*Basic HTML Only Button.*?<\/div>/s';
	$content = preg_replace( $pattern, '', $content );

	$pattern = '/<div[^>]*>\s*<h3>\s*Keyword Analysis Form.*?<\/div>/s';
	$content = preg_replace( $pattern, '', $content );

	return $content;
}

/**
 * Also remove the AJAX actions from being accessible to non-admin users.
 */
function easyaibloggen_remove_public_ajax_handlers() {
	// Remove the nopriv AJAX handlers to prevent public access.
	remove_action( 'wp_ajax_nopriv_easyaibloggen_analyze_keyword_density', 'easyaibloggen_analyze_keyword_density_ajax' );
	remove_action( 'wp_ajax_nopriv_easyaibloggen_log_button_click', 'easyaibloggen_log_button_click' );
}
add_action( 'init', 'easyaibloggen_remove_public_ajax_handlers' );
