<?php
/**
 * Update Comment Tool.
 *
 * Update and moderate existing comments using wp_update_comment() with support
 * for content, author info, and status changes (approve/hold/spam/trash).
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://agenistrator.com/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Update_Comment_Tool class.
 */
class Update_Comment_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'update_comment';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Update Comment', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update or moderate an existing comment.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'USER ATTRIBUTION:
- user_id=0: Convert to anonymous comment. You should also provide author and author_email.
- user_id=N (N>0): Reassign to registered user. Author name, email, and URL are auto-populated from the user record.
- Providing author/author_email/author_url without user_id updates those fields directly (for anonymous comments).

STATUS CHANGES:
- approve: Publish the comment (visible on site).
- hold: Set to pending moderation.
- spam: Mark as spam.
- trash: Move to trash.

COMMON PATTERNS:
- Approve pending comment: { id, status: "approve" }
- Edit comment content: { id, content: "new text" }
- Reassign to user: { id, user_id: 5 }
- Convert to anonymous: { id, user_id: 0, author: "Name", author_email: "email@example.com" }';
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'id'           => array(
					'type'        => 'integer',
					'description' => 'The ID of the comment to update',
				),
				'content'      => array(
					'type'        => 'string',
					'description' => 'New comment content in plain text or limited HTML format',
				),
				'user_id'      => array(
					'type'        => 'integer',
					'description' => 'Change the user attribution. Use 0 for anonymous.',
				),
				'author'       => array(
					'type'        => 'string',
					'description' => 'New author name (for anonymous comments)',
				),
				'author_email' => array(
					'type'        => 'string',
					'description' => 'New author email (for anonymous comments)',
					'format'      => 'email',
				),
				'author_url'   => array(
					'type'        => 'string',
					'description' => 'New author URL',
				),
				'status'       => array(
					'type'        => 'string',
					'description' => 'New comment status',
					'enum'        => array( 'approve', 'hold', 'spam', 'trash' ),
				),
			),
			'required'   => array( 'id' ),
		);
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'moderate_comments' );
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		$comment_id = intval( $args['id'] ?? 0 );

		if ( ! $comment_id ) {
			return $this->error_response( 'Comment ID is required.' );
		}

		$comment = get_comment( $comment_id );
		if ( ! $comment ) {
			return $this->error_response(
				'Comment not found.',
				array(
					'comment_id' => $comment_id,
					'hint'       => 'Verify the comment ID exists using the list_comments tool.',
				)
			);
		}

		$comment_data = array( 'comment_ID' => $comment_id );

		// Handle user_id change
		if ( isset( $args['user_id'] ) ) {
			$user_id                 = intval( $args['user_id'] );
			$comment_data['user_id'] = $user_id;

			// If changing to a registered user, update author info from user data
			if ( $user_id > 0 ) {
				$user = get_userdata( $user_id );
				if ( ! $user ) {
					return $this->error_response(
						"Invalid user_id: user {$user_id} does not exist.",
						array( 'hint' => 'Use user_id=0 for anonymous comments, or provide a valid user ID. Use list_users tool to find valid user IDs.' )
					);
				}
				$comment_data['comment_author']       = $user->display_name;
				$comment_data['comment_author_email'] = $user->user_email;
				$comment_data['comment_author_url']   = $user->user_url ?? '';
			}
		}

		if ( isset( $args['content'] ) && ! empty( $args['content'] ) ) {
			$comment_data['comment_content'] = $args['content'];
		}

		// Author fields (only apply if not already set by user_id change)
		if ( isset( $args['author'] ) && ! isset( $comment_data['comment_author'] ) ) {
			$comment_data['comment_author'] = sanitize_text_field( $args['author'] );
		}

		if ( isset( $args['author_email'] ) && ! isset( $comment_data['comment_author_email'] ) ) {
			$comment_data['comment_author_email'] = sanitize_email( $args['author_email'] );
		}

		if ( isset( $args['author_url'] ) && ! isset( $comment_data['comment_author_url'] ) ) {
			$comment_data['comment_author_url'] = esc_url_raw( $args['author_url'] );
		}

		if ( isset( $args['status'] ) && ! empty( $args['status'] ) ) {
			$comment_data['comment_approved'] = Create_Comment_Tool::status_to_approved( $args['status'] );
		}

		$updated = wp_update_comment( $comment_data, true );

		if ( is_wp_error( $updated ) ) {
			return $this->error_response(
				$updated->get_error_message(),
				array( 'error_code' => $updated->get_error_code() )
			);
		}

		if ( ! $updated ) {
			return $this->error_response( 'Failed to update comment or no changes detected.' );
		}

		$updated_comment = get_comment( $comment_id );

		return $this->success_response(
			'Comment updated successfully.',
			array(
				'comment_id' => $comment_id,
				'status'     => Create_Comment_Tool::approved_to_status( wp_get_comment_status( $updated_comment ) ),
				'post_id'    => intval( $updated_comment->comment_post_ID ),
				'user_id'    => intval( $updated_comment->user_id ),
				'author'     => $updated_comment->comment_author,
			)
		);
	}
}
