<?php
/**
 * Update Option Tool.
 *
 * Update or create a WordPress option. Supports autoload configuration and
 * handles serialized values automatically.
 *
 * @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;
}

/**
 * Update_Option_Tool class.
 */
class Update_Option_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update the value of a WordPress option/setting. Creates the option if it does not exist.';
	}

	/**
	 * 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(
				'option_name' => array(
					'type'        => 'string',
					'description' => 'The name of the option to update or create.',
				),
				'value'       => array(
					'description' => 'The new value for the option. Can be string, number, boolean, array, or object.',
				),
				'autoload'    => array(
					'type'        => 'string',
					'enum'        => array( 'yes', 'no' ),
					'description' => 'Whether to autoload the option. Default: yes for new options, unchanged for existing.',
				),
			),
			'required'   => array( 'option_name', 'value' ),
		);
	}

	/**
	 * Get the default enabled status for this tool.
	 *
	 * @return bool True if enabled by default, false otherwise.
	 * @since     1.0.0
	 */
	public function get_default_enabled_status() {
		return false;
	}

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

	/**
	 * 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 ) {
		$option_name = trim( $args['option_name'] );
		if ( ! preg_match( '/^[a-zA-Z0-9_-]+$/', $option_name ) ) {
			return $this->error_response( 'Invalid option name format. Use only letters, numbers, underscores, and hyphens.' );
		}

		$value    = $args['value'];
		$autoload = $args['autoload'] ?? null;

		$old_value = get_option( $option_name );
		$existed   = false !== $old_value || get_option( $option_name, '__not_set__' ) !== '__not_set__';

		if ( null !== $autoload ) {
			$result = update_option( $option_name, $value, $autoload );
		} else {
			$result = update_option( $option_name, $value );
		}

		if ( ! $result && $value === $old_value ) {
			return $this->success_response(
				'Option unchanged (same value)',
				array(
					'option_name' => $option_name,
					'action'      => 'unchanged',
				)
			);
		}

		if ( ! $result ) {
			return $this->error_response( 'Failed to update option', array( 'option_name' => $option_name ) );
		}

		return $this->success_response(
			$existed ? 'Option updated' : 'Option created',
			array(
				'option_name' => $option_name,
				'action'      => $existed ? 'updated' : 'created',
				'old_value'   => $old_value,
				'new_value'   => $value,
			)
		);
	}
}
