<?php
/**
 * Upload Media Tool.
 *
 * Allows the agent to upload media from a URL to the media library. Uses
 * WordPress media_sideload_image and related functions.
 *
 * @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://maximum.software/
 *
 * 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' ) ) {
	return;
}

/**
 * Upload_Media_Tool class.
 */
class Upload_Media_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Upload media from a URL to the WordPress media library.';
	}

	/**
	 * 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(
				'url'         => array(
					'type'        => 'string',
					'description' => 'The URL of the file to upload',
				),
				'title'       => array(
					'type'        => 'string',
					'description' => 'Title for the media item',
				),
				'alt'         => array(
					'type'        => 'string',
					'description' => 'Alt text for the media (images) in plain text format',
				),
				'caption'     => array(
					'type'        => 'string',
					'description' => 'Caption for the media in plain text format',
				),
				'description' => array(
					'type'        => 'string',
					'description' => 'Description of the media in plain text format',
				),
				'post_id'     => array(
					'type'        => 'integer',
					'description' => 'Post ID to attach media to (optional)',
				),
			),
			'required'   => array( 'url' ),
		);
	}

	/**
	 * 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['url'] ) || empty( $args['url'] ) ) {
			return $this->error_response( 'URL is required' );
		}

		if ( ! function_exists( 'media_sideload_image' ) ) {
			require_once ABSPATH . 'wp-admin/includes/media.php';
			require_once ABSPATH . 'wp-admin/includes/file.php';
			require_once ABSPATH . 'wp-admin/includes/image.php';
		}

		$url     = esc_url_raw( $args['url'] );
		$post_id = isset( $args['post_id'] ) ? intval( $args['post_id'] ) : 0;
		$title   = isset( $args['title'] ) ? sanitize_text_field( $args['title'] ) : '';

		$attachment_id = media_sideload_image( $url, $post_id, $title, 'id' );

		if ( is_wp_error( $attachment_id ) ) {
			return $this->error_response( 'Failed to upload media: ' . $attachment_id->get_error_message() );
		}

		// Update additional fields
		$update_args = array();
		if ( isset( $args['caption'] ) ) {
			$update_args['post_excerpt'] = sanitize_textarea_field( $args['caption'] );
		}
		if ( isset( $args['description'] ) ) {
			$update_args['post_content'] = sanitize_textarea_field( $args['description'] );
		}
		if ( ! empty( $update_args ) ) {
			$update_args['ID'] = $attachment_id;
			wp_update_post( $update_args );
		}

		if ( isset( $args['alt'] ) && ! empty( $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'] ) ) );
		}

		$attachment = get_post( $attachment_id );

		return $this->success_response(
			'Media uploaded successfully',
			array(
				'attachment_id' => $attachment_id,
				'title'         => $attachment->post_title,
				'url'           => wp_get_attachment_url( $attachment_id ),
				'mime_type'     => $attachment->post_mime_type,
			)
		);
	}
}
