<?php
/**
 * Meta Description Meta Box for AgenticWP plugin.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

/**
 * Handles the meta description meta box for post/page editors.
 * Only displays when a meta description exists and allows editing.
 */
class Meta_Box_Meta_Description {

	/**
	 * Initialize meta box and register hooks.
	 */
	public function __construct() {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
		add_action( 'save_post', array( $this, 'save_meta_description' ), 10, 2 );
	}

	/**
	 * Add meta description meta box to post and page screens.
	 *
	 * @return void
	 */
	public function add_meta_box() {
		$screens = array( 'post', 'page' );

		foreach ( $screens as $screen ) {
			add_meta_box(
				'agenticwp_meta_description',
				__( 'AgenticWP Meta Description', 'agenticwp' ),
				array( $this, 'meta_box_callback' ),
				$screen,
				'normal',
				'default'
			);
		}
	}

	/**
	 * Meta box callback - renders the meta box content.
	 *
	 * @param \WP_Post $post Current post object.
	 */
	public function meta_box_callback( $post ) {
		wp_nonce_field( 'agenticwp_meta_description_nonce', 'agenticwp_meta_description_nonce' );

		$meta_description = get_post_meta( $post->ID, '_agenticwp_meta_description', true );
		$char_count       = strlen( $meta_description );

		$count_class = 'good';
		if ( $char_count > 160 ) {
			$count_class = 'over';
		} elseif ( $char_count < 120 ) {
			$count_class = 'under';
		}

		?>
		<div class="agenticwp-meta-description-meta-box">
			<p class="description">
				<?php esc_html_e( 'Edit the meta description for this post. This will appear in search engine results.', 'agenticwp' ); ?>
			</p>

			<div class="agenticwp-meta-description-field">
				<textarea
					id="agenticwp_meta_description"
					name="agenticwp_meta_description"
					rows="3"
					class="large-text"
					placeholder="<?php esc_attr_e( 'Enter meta description...', 'agenticwp' ); ?>"
				><?php echo esc_textarea( $meta_description ); ?></textarea>

				<div class="agenticwp-meta-description-counter">
					<span class="counter <?php echo esc_attr( $count_class ); ?>" id="meta-description-count">
						<?php echo esc_html( $char_count ); ?>
					</span>
					<span class="counter-label"><?php esc_html_e( 'characters', 'agenticwp' ); ?></span>
					<span class="counter-guidance">
						<?php esc_html_e( '(Recommended: 120-160 characters)', 'agenticwp' ); ?>
					</span>
				</div>
			</div>

		</div>

		<script type="text/javascript">
		document.addEventListener('DOMContentLoaded', function() {
			const textarea = document.getElementById('agenticwp_meta_description');
			const counter = document.getElementById('meta-description-count');

			if (textarea && counter) {
				textarea.addEventListener('input', function() {
					const length = this.value.length;
					counter.textContent = length;

					counter.className = 'counter';
					if (length > 160) {
						counter.classList.add('over');
					} else if (length < 120) {
						counter.classList.add('under');
					} else {
						counter.classList.add('good');
					}
				});
			}
		});
		</script>
		<?php
	}

	/**
	 * Save meta description when post is saved.
	 *
	 * @param int      $post_id Post ID.
	 * @param \WP_Post $post    Post object.
	 */
	public function save_meta_description( $post_id, $post ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
		if ( ! isset( $_POST['agenticwp_meta_description_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['agenticwp_meta_description_nonce'] ) ), 'agenticwp_meta_description_nonce' ) ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! isset( $_POST['agenticwp_meta_description'] ) ) {
			return;
		}

		$meta_description = sanitize_textarea_field( wp_unslash( $_POST['agenticwp_meta_description'] ) );

		if ( ! empty( $meta_description ) ) {
			update_post_meta( $post_id, '_agenticwp_meta_description', $meta_description );
		} else {
			delete_post_meta( $post_id, '_agenticwp_meta_description' );
		}
	}
}