<?php
/**
 * Update Custom Post Tool.
 *
 * Allows the agent to update existing posts of any post type. Supports partial
 * updates for content, taxonomies, meta fields, and other attributes.
 *
 * @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_Custom_Post_Tool class.
 */
class Update_Custom_Post_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update an existing post of any post type.';
	}

	/**
	 * Get additional description instructions for the LLM.
	 *
	 * @return string Additional instructions appended to description.
	 * @since     1.0.0
	 */
	public function get_description_instructions() {
		return 'Use `get_custom_post` to see current values before updating.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'The `content` parameter MUST be valid HTML, NOT markdown. WordPress stores and renders post content as HTML. Use HTML tags like <p>, <h2>, <ul>, <li>, <a>, <strong>, <em>, etc.';
	}

	/**
	 * 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 post to update. Required.',
				),
				'title'              => array(
					'type'        => 'string',
					'description' => 'The new title of the post',
				),
				'content'            => array(
					'type'        => 'string',
					'description' => 'The new content of the post in HTML format (raw HTML, NOT markdown)',
				),
				'status'             => array(
					'type'        => 'string',
					'description' => 'The new status of the post',
					'enum'        => array( 'draft', 'publish', 'pending', 'private' ),
				),
				'excerpt'            => array(
					'type'        => 'string',
					'description' => 'The excerpt/summary of the post in plain text format',
				),
				'slug'               => array(
					'type'        => 'string',
					'description' => 'The URL slug (post_name) for the post',
				),
				'parent'             => array(
					'type'        => 'integer',
					'description' => 'Parent post ID (for hierarchical post types)',
				),
				'menu_order'         => array(
					'type'        => 'integer',
					'description' => 'Menu order for the post',
				),
				'taxonomies'         => array(
					'type'                 => 'object',
					'description'          => 'Taxonomy terms to assign. Keys are taxonomy slugs, values are arrays of term IDs or names. Replaces existing terms.',
					'additionalProperties' => array(
						'type'  => 'array',
						'items' => array( 'oneOf' => array( array( 'type' => 'string' ), array( 'type' => 'integer' ) ) ),
					),
				),
				'meta'               => array(
					'type'                 => 'object',
					'description'          => 'Meta fields to set/update. Keys are meta keys, values are meta values.',
					'additionalProperties' => true,
				),
				'featured_image_url' => array(
					'type'        => 'string',
					'description' => 'URL of an image to set as featured image',
				),
			),
			'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( 'edit_posts' );
	}

	/**
	 * 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 ) {
		if ( ! isset( $args['id'] ) || empty( $args['id'] ) ) {
			return $this->error_response( 'Post ID is required' );
		}

		$post_id = intval( $args['id'] );
		$post    = get_post( $post_id );

		if ( ! $post ) {
			return $this->error_response( 'Post not found' );
		}

		$post_type     = $post->post_type;
		$post_type_obj = get_post_type_object( $post_type );

		if ( ! $post_type_obj ) {
			return $this->error_response( 'Invalid post type' );
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return $this->error_response( 'You do not have permission to edit this post' );
		}

		$post_args = array( 'ID' => $post_id );

		if ( isset( $args['title'] ) && ! empty( $args['title'] ) ) {
			$post_args['post_title'] = wp_strip_all_tags( $args['title'] );
		}

		if ( isset( $args['content'] ) ) {
			$post_args['post_content'] = $args['content'];
		}

		if ( isset( $args['status'] ) && ! empty( $args['status'] ) ) {
			$allowed_statuses = array( 'draft', 'publish', 'pending', 'private' );
			if ( ! in_array( $args['status'], $allowed_statuses, true ) ) {
				return $this->error_response( 'Invalid status. Must be one of: ' . implode( ', ', $allowed_statuses ) );
			}
			if ( 'publish' === $args['status'] && ! current_user_can( $post_type_obj->cap->publish_posts ) ) {
				$args['status'] = 'pending';
			}
			$post_args['post_status'] = $args['status'];
		}

		if ( isset( $args['excerpt'] ) ) {
			$post_args['post_excerpt'] = wp_strip_all_tags( $args['excerpt'] );
		}

		if ( isset( $args['slug'] ) && ! empty( $args['slug'] ) ) {
			$post_args['post_name'] = sanitize_title( $args['slug'] );
		}

		if ( isset( $args['parent'] ) && is_numeric( $args['parent'] ) && $post_type_obj->hierarchical ) {
			$post_args['post_parent'] = intval( $args['parent'] );
		}

		if ( isset( $args['menu_order'] ) && is_numeric( $args['menu_order'] ) ) {
			$post_args['menu_order'] = intval( $args['menu_order'] );
		}

		$updated = wp_update_post( $post_args, true );

		if ( is_wp_error( $updated ) ) {
			return $this->error_response( 'Failed to update post: ' . $updated->get_error_message() );
		}

		// Handle taxonomies
		if ( isset( $args['taxonomies'] ) && is_array( $args['taxonomies'] ) ) {
			$valid_taxonomies = get_object_taxonomies( $post_type );

			foreach ( $args['taxonomies'] as $taxonomy => $terms ) {
				$taxonomy = sanitize_key( $taxonomy );
				if ( ! in_array( $taxonomy, $valid_taxonomies, true ) ) {
					continue;
				}

				$term_ids = array();
				$terms    = is_array( $terms ) ? $terms : array( $terms );

				foreach ( $terms as $term ) {
					if ( is_numeric( $term ) ) {
						$term_ids[] = intval( $term );
					} else {
						$existing = term_exists( $term, $taxonomy );
						if ( $existing ) {
							$term_ids[] = intval( $existing['term_id'] );
						} else {
							$new_term = wp_insert_term( $term, $taxonomy );
							if ( ! is_wp_error( $new_term ) ) {
								$term_ids[] = intval( $new_term['term_id'] );
							}
						}
					}
				}

				wp_set_object_terms( $post_id, $term_ids, $taxonomy );
			}
		}

		// Handle meta fields
		if ( isset( $args['meta'] ) && is_array( $args['meta'] ) ) {
			foreach ( $args['meta'] as $key => $value ) {
				$key = sanitize_key( $key );
				if ( ! empty( $key ) ) {
					// Use wp_slash() to prevent stripslashes corruption in update_post_meta.
					// See: https://developer.wordpress.org/reference/functions/update_post_meta/#workaround
					update_post_meta( $post_id, $key, wp_slash( $value ) );
				}
			}
		}

		// Handle featured image
		if ( isset( $args['featured_image_url'] ) && ! empty( $args['featured_image_url'] ) ) {
			WordPress_Utils::set_featured_image_from_url( $post_id, $args['featured_image_url'] );
		}

		$updated_post = get_post( $post_id );

		return $this->success_response(
			'Post updated successfully',
			array(
				'post_id'         => $post_id,
				'post_type'       => $post_type,
				'post_type_label' => $post_type_obj->labels->singular_name,
				'post_title'      => $updated_post->post_title,
				'post_status'     => $updated_post->post_status,
				'edit_link'       => get_edit_post_link( $post_id, 'raw' ),
				'view_link'       => get_permalink( $post_id ),
			)
		);
	}
}
