<?php
/**
 * Update Post Meta Tool.
 *
 * Update the value of a meta key for a post, page, or custom post type.
 * If the key doesn't exist, it will be created.
 *
 * @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_Post_Meta_Tool class.
 */
class Update_Post_Meta_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update the value of a meta key for a post, page, or custom post type. If the key does not exist, it will be created.';
	}

	/**
	 * 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;
	}

	/**
	 * 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(
				'post_id'    => array(
					'type'        => 'integer',
					'description' => 'The ID of the post to update meta for.',
				),
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Array key for tool parameter, not a database query.
				'meta_key'   => array(
					'type'        => 'string',
					'description' => 'The meta key to update.',
				),
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Array key for tool parameter, not a database query.
				'meta_value' => array(
					'description' => 'The new meta value. Can be a string, number, boolean, array, object, or null.',
					'anyOf'       => array(
						array( 'type' => 'string' ),
						array( 'type' => 'number' ),
						array( 'type' => 'integer' ),
						array( 'type' => 'boolean' ),
						array( 'type' => 'object' ),
						array(
							'type'  => 'array',
							'items' => array(),
						),
						array( 'type' => 'null' ),
					),
				),
				'prev_value' => array(
					'description' => 'Optional. Only update if the current value matches this. Useful when multiple entries exist for the same key.',
					'anyOf'       => array(
						array( 'type' => 'string' ),
						array( 'type' => 'number' ),
						array( 'type' => 'integer' ),
						array( 'type' => 'boolean' ),
						array( 'type' => 'object' ),
						array(
							'type'  => 'array',
							'items' => array(),
						),
						array( 'type' => 'null' ),
					),
				),
			),
			'required'   => array( 'post_id', 'meta_key', 'meta_value' ),
		);
	}

	/**
	 * 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' );
	}

	/**
	 * 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 ) {
		$post_id    = (int) $args['post_id'];
		$meta_key   = trim( $args['meta_key'] );
		$meta_value = $args['meta_value'];
		$prev_value = isset( $args['prev_value'] ) ? $args['prev_value'] : '';

		if ( '' === $meta_key ) {
			return $this->error_response( 'Meta key cannot be empty' );
		}

		$post = get_post( $post_id );

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

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

		// Get old value for response
		$old_value = get_post_meta( $post_id, $meta_key, false );

		if ( '' !== $prev_value ) {
			$result = update_post_meta( $post_id, $meta_key, $meta_value, $prev_value );
		} else {
			$result = update_post_meta( $post_id, $meta_key, $meta_value );
		}

		if ( false === $result ) {
			if ( '' !== $prev_value ) {
				return $this->error_response(
					'Failed to update post meta. The previous value may not match.',
					array(
						'post_id'       => $post_id,
						// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Array key for response data, not a database query.
						'meta_key'      => $meta_key,
						'current_value' => $old_value,
					)
				);
			}

			// update_post_meta returns false when the value is unchanged
			return $this->success_response(
				'Post meta value is already set to the specified value',
				array(
					'post_id'   => $post_id,
					'post_type' => $post->post_type,
					// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Array key for response data, not a database query.
					'meta_key'  => $meta_key,
					'value'     => $meta_value,
					'changed'   => false,
				)
			);
		}

		$created = empty( $old_value );

		return $this->success_response(
			$created ? 'Post meta created successfully' : 'Post meta updated successfully',
			array(
				'post_id'   => $post_id,
				'post_type' => $post->post_type,
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Array key for response data, not a database query.
				'meta_key'  => $meta_key,
				'old_value' => $old_value,
				'new_value' => $meta_value,
				'created'   => $created,
			)
		);
	}
}
