<?php
/**
 * Database Execute Tool.
 *
 * Execute write SQL statements (INSERT, UPDATE, DELETE) using wpdb.
 * Returns affected row count for data modification queries.
 *
 * @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;
}

/**
 * DB_Execute_Tool class.
 */
class DB_Execute_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Execute a write SQL statement (INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, TRUNCATE).';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'Use {prefix} placeholder for the WordPress table prefix.';
	}

	/**
	 * 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(
				'statement' => array(
					'type'        => 'string',
					'description' => 'SQL statement to execute. Use {prefix} for table prefix.',
				),
			),
			'required'   => array( 'statement' ),
		);
	}

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

	/**
	 * 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 ) {
		global $wpdb;

		$statement = $args['statement'];

		$statement = str_replace( '{prefix}', $wpdb->prefix, $statement );

		$statement_upper = strtoupper( trim( $statement ) );
		$write_prefixes  = array( 'INSERT', 'UPDATE', 'DELETE', 'REPLACE', 'CREATE', 'ALTER', 'DROP', 'TRUNCATE' );
		$is_write        = false;
		foreach ( $write_prefixes as $prefix ) {
			if ( strncmp( $statement_upper, $prefix, strlen( $prefix ) ) === 0 ) {
				$is_write = true;
				break;
			}
		}

		if ( ! $is_write ) {
			return $this->error_response( 'Only write statements (INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, TRUNCATE) are allowed. Use db_query for SELECT queries.' );
		}

		$previous_suppress = $wpdb->suppress_errors( true );
		try {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $statement is intentionally raw SQL from admin tool call; caching not applicable.
			$result    = $wpdb->query( $statement );
			$error     = $wpdb->last_error;
			$insert_id = $wpdb->insert_id;
		} finally {
			$wpdb->suppress_errors( $previous_suppress );
		}

		if ( $error ) {
			return $this->error_response( 'Statement failed: ' . $error );
		}

		$data = array(
			'rows_affected' => $result,
		);

		if ( strncmp( $statement_upper, 'INSERT', 6 ) === 0 ) {
			$data['insert_id'] = $insert_id;
		}

		return $this->success_response( 'Statement executed', $data );
	}
}
