<?php
/**
 * Update Media Tool.
 *
 * Allows the agent to update media item metadata including title, caption,
 * alt text, and description.
 *
 * @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_Media_Tool class.
 */
class Update_Media_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update media item title, alt text, caption, or description.';
	}

	/**
	 * 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 media item to update',
				),
				'title'       => array(
					'type'        => 'string',
					'description' => 'New title for the media',
				),
				'alt'         => array(
					'type'        => 'string',
					'description' => 'New alt text for the media in plain text format',
				),
				'caption'     => array(
					'type'        => 'string',
					'description' => 'New caption for the media in plain text format',
				),
				'description' => array(
					'type'        => 'string',
					'description' => 'New description for the media in plain text format',
				),
			),
			'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( 'upload_files' );
	}

	/**
	 * 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( 'Media ID is required' );
		}

		$attachment_id = intval( $args['id'] );
		$attachment    = get_post( $attachment_id );

		if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
			return $this->error_response( 'Media item not found' );
		}

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

		$update_args = array( 'ID' => $attachment_id );
		$has_updates = false;

		if ( isset( $args['title'] ) && ! empty( $args['title'] ) ) {
			$update_args['post_title'] = sanitize_text_field( $args['title'] );
			$has_updates               = true;
		}

		if ( isset( $args['caption'] ) ) {
			$update_args['post_excerpt'] = sanitize_textarea_field( $args['caption'] );
			$has_updates                 = true;
		}

		if ( isset( $args['description'] ) ) {
			$update_args['post_content'] = sanitize_textarea_field( $args['description'] );
			$has_updates                 = true;
		}

		if ( $has_updates ) {
			$result = wp_update_post( $update_args, true );
			if ( is_wp_error( $result ) ) {
				return $this->error_response( 'Failed to update media: ' . $result->get_error_message() );
			}
		}

		if ( isset( $args['alt'] ) ) {
			// 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( $attachment_id, '_wp_attachment_image_alt', wp_slash( sanitize_text_field( $args['alt'] ) ) );
			$has_updates = true;
		}

		if ( ! $has_updates ) {
			return $this->error_response( 'No updates provided' );
		}

		$updated = get_post( $attachment_id );

		return $this->success_response(
			'Media updated successfully',
			array(
				'attachment_id' => $attachment_id,
				'title'         => $updated->post_title,
				'alt'           => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ),
				'caption'       => $updated->post_excerpt,
				'url'           => wp_get_attachment_url( $attachment_id ),
			)
		);
	}
}
