<?php
/**
 * Update Page Tool.
 *
 * Allows the agent to update existing WordPress pages by ID or slug. Supports
 * partial updates for title, content, status, and hierarchy.
 *
 * @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_Page_Tool class.
 */
class Update_Page_Tool extends Tool {

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

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

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

	/**
	 * 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 page content as HTML. Use HTML tags like <p>, <h2>, <ul>, <li>, <a>, <strong>, <em>, etc.';
	}

	/**
	 * Get the parameters 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 page to update',
				),
				'title'              => array(
					'type'        => 'string',
					'description' => 'The new title of the page',
				),
				'content'            => array(
					'type'        => 'string',
					'description' => 'The new content of the page in HTML format (raw HTML, NOT markdown)',
				),
				'status'             => array(
					'type'        => 'string',
					'description' => 'The new status of the page',
					'enum'        => array( 'draft', 'publish', 'pending', 'private' ),
				),
				'parent_id'          => array(
					'type'        => 'integer',
					'description' => 'ID of the parent page if this is a subpage',
				),
				'template'           => array(
					'type'        => 'string',
					'description' => 'Page template to use (if supported by the theme)',
				),
				'featured_image_url' => array(
					'type'        => 'string',
					'description' => 'URL of an image to set as featured image',
				),
			),
			'required'   => array( 'id' ),
		);
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return     bool False - this tool modifies content.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

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

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param      array $args The arguments for the tool.
	 * @return     array The result of executing the tool.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		if ( ! isset( $args['id'] ) || empty( $args['id'] ) ) {
			return $this->error_response( 'Page ID is required' );
		}

		$page_id = intval( $args['id'] );
		$page    = get_post( $page_id );

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

		// Check if post type is 'page'
		if ( 'page' !== $page->post_type ) {
			return $this->error_response( 'The specified ID is not a page' );
		}

		// Check if user can edit this page
		if ( ! current_user_can( 'edit_page', $page_id ) ) {
			return $this->error_response( 'You do not have permission to edit this page' );
		}

		// Build update arguments
		$page_args = array(
			'ID' => $page_id,
		);

		// Update title if provided
		if ( isset( $args['title'] ) && ! empty( $args['title'] ) ) {
			$page_args['post_title'] = wp_strip_all_tags( $args['title'] );
		}

		// Update content if provided
		if ( isset( $args['content'] ) && ! empty( $args['content'] ) ) {
			$page_args['post_content'] = $args['content'];
		}

		// Update status if provided
		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 ) );
			}
			$page_args['post_status'] = $args['status'];
		}

		// Update parent if provided
		if ( isset( $args['parent_id'] ) && is_numeric( $args['parent_id'] ) ) {
			$parent = get_post( $args['parent_id'] );
			if ( ! $parent || 'page' !== $parent->post_type ) {
				return $this->error_response( 'Parent page not found or not a valid page' );
			}
			$page_args['post_parent'] = intval( $args['parent_id'] );
		}

		// Update the page
		$updated = wp_update_post( $page_args );

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

		// Update page template if provided
		if ( isset( $args['template'] ) && ! empty( $args['template'] ) ) {
			// 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( $page_id, '_wp_page_template', wp_slash( sanitize_text_field( $args['template'] ) ) );
		}

		// Update featured image if URL provided
		if ( isset( $args['featured_image_url'] ) && ! empty( $args['featured_image_url'] ) ) {
			WordPress_Utils::set_featured_image_from_url( $page_id, $args['featured_image_url'] );
		}

		// Get updated page
		$updated_page = get_post( $page_id );

		return $this->success_response(
			'Page updated successfully',
			array(
				'page_id'     => $page_id,
				'page_title'  => $updated_page->post_title,
				'page_status' => $updated_page->post_status,
				'edit_link'   => get_edit_post_link( $page_id, 'raw' ),
				'view_link'   => get_permalink( $page_id ),
			)
		);
	}
}
