<?php
/**
 * AEO Tools — Custom head code injection.
 *
 * Stores arbitrary code (schema markup, meta tags, analytics, etc.) in a WP
 * option and outputs it in wp_head. Exposed via the clearpost/set-head-code
 * MCP ability.
 *
 * @package Simple_Ai_Auto_Post
 * @since 1.9.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Output custom head code stored by the set-head-code ability.
 */
function saiap_output_custom_head_code() {
	$code = get_option( 'saiap_custom_head_code', '' );
	if ( ! empty( $code ) ) {
		echo "\n" . $code . "\n";
	}
}
add_action( 'wp_head', 'saiap_output_custom_head_code', 1 );

/**
 * MCP handler: clearpost/set-head-code
 *
 * Stores arbitrary code to be output in wp_head. Supports append/replace modes.
 */
function saiap_mcp_set_head_code( $input = array() ) {
	$code = isset( $input['code'] ) ? (string) $input['code'] : '';
	$mode = isset( $input['mode'] ) ? (string) $input['mode'] : 'replace';

	if ( 'clear' === $mode ) {
		update_option( 'saiap_custom_head_code', '' );
		return array(
			'message' => __( 'Custom head code cleared.', 'clearpost-simple-ai-auto-post' ),
			'code'    => '',
		);
	}

	if ( '' === $code ) {
		return new WP_Error( 'missing_code', __( 'code is required when mode is not "clear".', 'clearpost-simple-ai-auto-post' ) );
	}

	if ( 'append' === $mode ) {
		$existing = get_option( 'saiap_custom_head_code', '' );
		$code     = $existing . "\n" . $code;
	}

	update_option( 'saiap_custom_head_code', $code );

	return array(
		'message' => __( 'Custom head code saved. It will appear in the <head> of every page.', 'clearpost-simple-ai-auto-post' ),
		'code'    => $code,
	);
}

/**
 * MCP handler: clearpost/get-head-code
 *
 * Returns the current custom head code.
 */
function saiap_mcp_get_head_code( $input = array() ) {
	return array(
		'code' => get_option( 'saiap_custom_head_code', '' ),
	);
}
