<?php
/**
 * Create Page Tool.
 *
 * Allows the agent to create new WordPress pages with specified content, title,
 * status, and other page attributes. Handles validation and error reporting.
 *
 * @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;
}

/**
 * Create_Page_Tool class.
 */
class Create_Page_Tool extends Tool {

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

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

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

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

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

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

		if ( ! isset( $args['content'] ) || empty( $args['content'] ) ) {
			return $this->error_response( 'Content is required' );
		}

		$status           = $args['status'] ?? 'draft';
		$allowed_statuses = array( 'draft', 'publish', 'pending', 'private' );

		if ( ! in_array( $status, $allowed_statuses, true ) ) {
			return $this->error_response( 'Invalid status. Must be one of: ' . implode( ', ', $allowed_statuses ) );
		}

		$page_args = array(
			'post_title'   => wp_strip_all_tags( $args['title'] ),
			'post_content' => $args['content'],
			'post_status'  => $status,
			'post_type'    => 'page',
			'post_author'  => get_current_user_id(),
		);

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

		// Insert the page
		$page_id = wp_insert_post( $page_args );

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

		// Set page template if specified
		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'] ) ) );
		}

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

		return $this->success_response(
			'Page created successfully',
			array(
				'page_id'     => $page_id,
				'page_title'  => $args['title'],
				'page_status' => $status,
				'edit_link'   => get_edit_post_link( $page_id, 'raw' ),
				'view_link'   => get_permalink( $page_id ),
			)
		);
	}
}
